Telegram Bot无法接收回调请求的问题排查求助
问题描述
我用以下代码实现Telegram Bot的回调接收:
public class TelegramBotController : ControllerBase { private readonly TelegramBotClient _botClient; private const string BotToken = "MyToken"; public TelegramBotController() { _botClient = new TelegramBotClient(BotToken); } [HttpPost] public async Task<IActionResult> Post([FromBody] Telegram.Bot.Types.Update update) { await _botClient.SendTextMessageAsync(chatId: myUserId, "Hello guys"); return Ok(); } }
已经通过Postman成功调用setwebhook接口,但给Bot发送消息时,完全收不到回调请求。试过查资料、用ChatGPT排查都没解决,需要实现「接收Telegram回调并自动回复消息」的功能。
排查与解决步骤
1. 确认Webhook地址的可访问性
- 必须用公网可访问的HTTPS地址:Telegram服务器无法访问本地localhost,本地开发可以用内网穿透工具(如Ngrok)生成临时公网HTTPS地址;线上环境要确保域名绑定有效SSL证书。
- 检查地址拼写:确保
setwebhook时传入的url参数是回调接口的完整路径(比如https://你的域名/api/TelegramBot),没有遗漏路由前缀。
2. 查看Webhook状态信息
调用Telegram的getWebhookInfo接口:
https://api.telegram.org/bot<你的BotToken>/getWebhookInfo
返回结果里的last_error_message会直接告诉你Telegram请求Webhook失败的原因,比如证书无效、地址不可达、请求超时等,这是最直接的排查依据。
3. 修复代码中的明显问题
- 补全聊天ID的正确获取方式:代码里的
myUserId是未定义的硬编码值,应该从接收到的update对象中提取用户聊天ID,否则即使收到回调,发送消息也会失败。修改后的代码:
[HttpPost] public async Task<IActionResult> Post([FromBody] Telegram.Bot.Types.Update update) { if (update.Message != null) { long chatId = update.Message.Chat.Id; await _botClient.SendTextMessageAsync(chatId: chatId, text: "Hello guys"); } return Ok(); }
- 确认Controller路由配置:给
TelegramBotController类添加路由特性,确保接口地址和Webhook设置一致:
[Route("api/[controller]")] public class TelegramBotController : ControllerBase { // ... 原有代码 }
- 添加日志排查请求是否到达:在接口中加入日志,确认是否真的没收到Telegram的请求:
private readonly ILogger<TelegramBotController> _logger; public TelegramBotController(ILogger<TelegramBotController> logger) { _botClient = new TelegramBotClient(BotToken); _logger = logger; } [HttpPost] public async Task<IActionResult> Post([FromBody] Telegram.Bot.Types.Update update) { _logger.LogInformation("收到Telegram回调: {UpdateData}", System.Text.Json.JsonSerializer.Serialize(update)); // ... 后续逻辑 }
4. 检查服务器与防火墙设置
- 确保服务器开放了HTTPS端口(默认443),且允许Telegram的IP段访问;可以临时关闭防火墙测试,排除拦截问题。
- 如果用了Nginx/IIS等反向代理,检查配置是否正确转发POST请求,没有做不必要的重定向或拦截。
内容的提问来源于stack exchange,提问作者Tan Pham
相关产品推荐
相关产品推荐

