Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TGbot 推送失败 #2558

Open
oceanz764 opened this issue Nov 11, 2024 · 4 comments
Open

TGbot 推送失败 #2558

oceanz764 opened this issue Nov 11, 2024 · 4 comments

Comments

@oceanz764
Copy link

Qinglong version

V2.17.12

Steps to reproduce

Telegram 发送通知消息失败😞
RequestError
at ClientRequest. (/ql/node_modules/.pnpm/got@11.8.6/node_modules/got/dist/source/core/index.js:970:111)
at Object.onceWrapper (node:events:634:26)
at ClientRequest.emit (node:events:531:35)
at origin.emit (/ql/node_modules/.pnpm/@szmarczak+http-timer@4.0.6/node_modules/@szmarczak/http-timer/dist/source/index.js:43:20)
at TLSSocket.socketErrorListener (node:_http_client:500:9)
at TLSSocket.emit (node:events:519:28)
at emitErrorNT (node:internal/streams/destroy:169:8)
at emitErrorCloseNT (node:internal/streams/destroy:128:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)AggregateError [ETIMEDOUT]:
at internalConnectMultiple (node:net:1117:18)
at internalConnectMultiple (node:net:1185:5)
at Timeout.internalConnectMultipleTimeout (node:net:1711:5)
at listOnTimeout (node:internal/timers:575:11)
at process.processTimers (node:internal/timers:514:7) {
code: 'ETIMEDOUT',
timings: {
start: 1731295532933,
socket: 1731295532934,
lookup: 1731295532940,
connect: undefined,
secureConnect: undefined,
upload: undefined,
response: undefined,
end: undefined,
error: 1731295533193,
abort: undefined,
phases: {
wait: 1,
dns: 6,
tcp: undefined,
tls: undefined,
request: undefined,
firstByte: undefined,
download: undefined,
total: 260
}
}
}

What is expected?

推送失败问题

What is actually happening?

Tgbot一直推送失败

System Info

No response

Any additional comments?

No response

@a65101855
Copy link

一样的问题,我设置了tgbot反代,但是每个人的库notify.py关于反代都不一样,
def telegram_bot(title: str, content: str) -> None:
"""
使用 telegram 机器人 推送消息。
"""
if not push_config.get("TG_BOT_TOKEN") or not push_config.get("TG_USER_ID"):
print("tg 服务的 bot_token 或者 user_id 未设置!!\n取消推送")
return
print("tg 服务启动")

if push_config.get("TG_API_HOST"):
    url = f"{push_config.get('TG_API_HOST')}/bot{push_config.get('TG_BOT_TOKEN')}/sendMessage"
else:
    url = (
        f"https://api.telegram.org/bot{push_config.get('TG_BOT_TOKEN')}/sendMessage"
    )
headers = {"Content-Type": "application/x-www-form-urlencoded"}
payload = {
    "chat_id": str(push_config.get("TG_USER_ID")),
    "text": f"{title}\n\n{content}",
    "disable_web_page_preview": "true",
}

有些需要加https://  有些不需要,建议添加
        url = f"{push_config.get('TG_API_HOST')}/bot{push_config.get('TG_BOT_TOKEN')}/sendMessage"
else:
        url = f"https://{push_config.get('TG_API_HOST')}/bot{push_config.get('TG_BOT_TOKEN')}/sendMessage"

@oceanz764
Copy link
Author

解决了吗, 我尝试解决,没搞定

@githubfat
Copy link

现在bark推送也是报这个错.

@s1084796293
Copy link

s1084796293 commented Dec 7, 2024

我发现是sendNotify.js的tgBotNotify方法有问题,然后我用Claude重写了这个方法,试了下,可以用。

function tgBotNotify(text, desp) {
const {
TG_BOT_TOKEN,
TG_USER_ID,
TG_API_HOST,
} = push_config;

if (!TG_BOT_TOKEN || !TG_USER_ID) {
    return Promise.resolve();
}

const tls = require('tls');
const dns = require('dns');

return new Promise((resolve) => {
    // DNS resolution
    dns.resolve4((TG_API_HOST || 'api.telegram.org').replace(/^https?:\/\//, ''), (err, addresses) => {
        if (err) {
            console.log('DNS resolution failed:', err);
            return resolve({});
        }

        // Establish TLS connection
        const socket = tls.connect({
            host: addresses[0],
            port: 443,
            servername: 'api.telegram.org',
            rejectUnauthorized: true,
            timeout: 30000,
            minVersion: 'TLSv1.2',
            maxVersion: 'TLSv1.3',
            ciphers: 'HIGH:!aNULL:!MD5:!RC4',
            keepAlive: true,
            keepAliveInitialDelay: 0
        });

        socket.setTimeout(30000);

        socket.on('secureConnect', () => {
            const data = JSON.stringify({
                chat_id: TG_USER_ID,
                text: `${text}\n\n${desp}`,
                disable_web_page_preview: true
            });

            const request = [
                `POST /bot${TG_BOT_TOKEN}/sendMessage HTTP/1.1`,
                'Host: api.telegram.org',
                'Content-Type: application/json',
                `Content-Length: ${Buffer.byteLength(data)}`,
                'Connection: close',
                '',
                data,
                ''
            ].join('\r\n');

            socket.write(request);
        });

        let response = '';
        socket.on('data', (chunk) => {
            response += chunk;
        });

        socket.on('end', () => {
            try {
                const jsonStr = response.split('\r\n\r\n')[1];
                const data = JSON.parse(jsonStr);
                
                if (data.ok) {
                    console.log('Telegram notification sent successfully.');
                } else if (data.error_code === 400) {
                    console.log('Please send a message to the bot first and check if the User ID is correct.');
                } else if (data.error_code === 401) {
                    console.log('Telegram bot token is incorrect.');
                }
                resolve(data);
            } catch (error) {
                console.log('Failed to parse Telegram response:', response);
                resolve({});
            }
            socket.destroy();
        });

        socket.on('timeout', () => {
            console.log('Telegram connection timeout');
            socket.destroy();
            resolve({});
        });

        socket.on('error', (error) => {
            console.log('Telegram notification failed:', error);
            resolve({});
        });
    });
});

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants