运行Node.js Telegram Bot时遇ETIMEDOUT错误如何解决?
解决Telegram Bot Polling时的ETIMEDOUT错误
编写了如下Telegram Bot代码:
const TelegramBot = require("node-telegram-bot-api"); const token = "*******"; const bot = new TelegramBot(token, { polling: true }); bot.onText(/\/start/, (msg) => { const message = "this is text message"; const chatid = msg.chat.id; bot.sendMessage(chatid, message); });执行
node bot.js时出现报错:error: [polling_error] {"code":"EFATAL","message":"EFATAL: Error: connect ETIMEDOUT 10.10.34.36:443"}已关闭防火墙和代理,网络连接正常,求解决方法。
可能的原因与解决步骤
1. 修复DNS解析问题
报错中的10.10.34.36属于内网IP段,说明你的设备将api.telegram.org解析到了错误的内网地址,导致无法连接Telegram官方服务器。解决步骤:
- 手动获取
api.telegram.org的正确公网IP:在能正常访问Telegram的环境中执行ping api.telegram.org或nslookup api.telegram.org,得到有效的公网IP地址 - 修改本地hosts文件:
- Windows系统路径:
C:\Windows\System32\drivers\etc\hosts - Linux/macOS系统路径:
/etc/hosts - 添加一行内容:
[获取到的公网IP] api.telegram.org(替换为实际查询到的IP)
- Windows系统路径:
- 刷新DNS缓存:
- Windows:打开命令提示符执行
ipconfig /flushdns - macOS:打开终端执行
sudo dscacheutil -flushcache - Linux:打开终端执行
sudo systemd-resolve --flush-caches(不同发行版命令可能略有差异)
- Windows:打开命令提示符执行
2. 更换公共DNS服务器
如果存在隐性DNS劫持,可切换到公共DNS服务器:
- 在系统网络设置中,将DNS服务器修改为
8.8.8.8(Google公共DNS)或1.1.1.1(Cloudflare公共DNS) - 保存设置后重新运行bot程序
3. 改用Webhook模式替代Polling
如果Polling模式的网络问题无法解决,可以切换到Webhook模式(需要你的服务器有公网可访问的HTTPS地址):
const TelegramBot = require("node-telegram-bot-api"); const token = "*******"; // 替换为你的公网HTTPS地址 const webhookUrl = "https://your-public-domain.com:8443"; const bot = new TelegramBot(token); // 设置Webhook bot.setWebHook(`${webhookUrl}/bot${token}`); bot.onText(/\/start/, (msg) => { const message = "this is text message"; const chatid = msg.chat.id; bot.sendMessage(chatid, message); });
- 注意:Telegram仅允许Webhook使用443、80、88、8443这些端口,且地址必须为HTTPS协议
内容的提问来源于stack exchange,提问作者Hamid
相关产品推荐
相关产品推荐

