问题分析
在代码中你遇到了 TypeError: SocksProxyAgent is not a constructor 错误,这表示在 socks-proxy-agent 库的使用过程中出现了问题。这个问题的出现可能是由于 socks-proxy-agent 库的版本变化或者导入方式不正确导致的。
同时,error: [polling_error] {"code":"EFATAL","message":"EFATAL: Error: connect ECONNREFUSED 127.0.0.1:1080"} 错误说明在尝试连接到 127.0.0.1:1080 端口时连接被拒绝,这通常是因为代理服务器的地址或端口不正确,或代理服务器没有启动。
解决方案
1. 修正 socks-proxy-agent 的导入方式
根据最新的 socks-proxy-agent 文档,它的导入方式应该是直接导入 default 导出的类,而不是从 proxy.SocksProxyAgent 中导入。以下是更新后的导入方式:
const SocksProxyAgent = require('socks-proxy-agent');
如果你使用的是 ES 模块语法,则可以这样导入:
import SocksProxyAgent from 'socks-proxy-agent';
2. 检查代理服务器配置
确保你使用的代理端口是正确的。你提到的代理端口是 10808,而不是 1080。因此,正确的代理服务器地址和端口应该是:
const socksHost = 'socks5://127.0.0.1';
const socksPort = 10808;
或者直接合并为:
const proxyUrl = 'socks5://127.0.0.1:10808';
修正后的代码
const TelegramBot = require('node-telegram-bot-api');
const SocksProxyAgent = require('socks-proxy-agent');
// Telegram 机器人令牌
const token = 'YOUR_TELEGRAM_BOT_TOKEN'; // 将此处替换为您的真实机器人令牌
// SOCKS5 代理配置
const proxyUrl = 'socks5://127.0.0.1:10808'; // 使用正确的代理地址和端口
// 创建 SOCKS5 代理 agent
const agent = new SocksProxyAgent(proxyUrl);
// 创建 Telegram 机器人实例,并使用 SOCKS5 代理
const bot = new TelegramBot(token, {
polling: true, // 启用轮询模式
request: {
agent: agent
}
});
// 处理消息
bot.on('message', (msg) => {
const chatId = msg.chat.id;
// 发送响应消息
bot.sendMessage(chatId, '收到您的消息');
});
console.log('Telegram bot is running...');
检查代理服务器的状态
确认代理服务器正在运行,并且能够通过你指定的端口(10808)接收连接:
- 确认代理服务器(例如 Shadowsocks、V2Ray 或其他)已经正确启动。
- 使用
curl测试代理服务器:
curl -x socks5h://127.0.0.1:10808 https://www.google.com
这将测试是否可以通过指定的 SOCKS5 代理服务器连接到 Google。
环境变量设置
虽然你已经使用了 PowerShell 设置 http_proxy 和 https_proxy 环境变量,但这些对 SOCKS5 代理不起作用,因为 SOCKS5 代理通常不会通过 HTTP(S) 代理环境变量来配置。你需要在代码中明确指定 socks5 代理的地址和端口。
其他可能的调试步骤
-
确认网络访问:
- 如果通过代理仍然不能访问 Telegram API,可能需要确认是否有额外的网络限制。
- 使用
telnet或其他工具测试端口可达性:
这将确认代理服务器的端口是否在本地系统上打开。telnet 127.0.0.1 10808
-
代理认证:
- 如果你的代理服务器需要认证,确保在代理 URL 中包含认证信息,例如:
const proxyUrl = 'socks5://username:password@127.0.0.1:10808';
- 如果你的代理服务器需要认证,确保在代理 URL 中包含认证信息,例如:
-
使用其他网络:
- 通过不同的网络环境(例如手机热点)测试连接,排除当前网络设置的问题。
通过这些调整和检查,你应该能够成功地通过 SOCKS5 代理连接 node-telegram-bot-api 到 Telegram 服务器。
评论
使用 GitHub 账号登录后即可评论