You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.Net Core使用Telegram.Bot遇SSL连接失败及Win32Exception问题求助

解决Telegram.Bot库的SSL连接错误问题

我之前也碰到过一模一样的问题,这个“SSL Connection could not be established”错误大概率是TLS协议兼容问题或者网络环境限制导致的,给你几个实用的解决步骤:

1. 升级Telegram.Bot到最新版本

旧版本的库可能不支持Telegram API要求的TLS 1.2+协议,先通过NuGet更新到最新版:

Update-Package Telegram.Bot

2. 强制启用TLS 1.2/1.3协议

很多旧的.NET环境默认没有启用TLS 1.2,而Telegram API现在只接受这个版本以上的加密连接。在你的代码开头添加这段配置,放在创建TelegramBotClient之前:

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls13;

3. 修正Chat ID的类型

你的代码里用了int类型存储Chat ID,但很多用户/群组的ID会超出int的取值范围,建议改成long类型,避免潜在的溢出问题。

4. 检查网络环境

  • 如果是在公司或受限网络下,可能有代理或防火墙拦截了SSL连接。可以配置代理客户端:
var httpClientHandler = new HttpClientHandler
{
    Proxy = new WebProxy("http://你的代理地址:端口"),
    UseProxy = true
};
var bot = new TelegramBotClient(token, new HttpClient(httpClientHandler));
  • 确认防火墙没有阻止出站连接到api.telegram.org的443端口。

修改后的完整代码示例

using System;
using System.Net;
using System.Threading.Tasks;
using Telegram.Bot;

namespace telegram
{
    class Program
    {
        private static string token = "mytoken";
        private static string msg = "Test";
        private static long chatId = 11111111; // 改为long类型
        static async Task Main(string[] args)
        {
            // 强制启用TLS 1.2和1.3
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
            
            var bot = new TelegramBotClient(token);
            await bot.SendTextMessageAsync(chatId, msg);
            
            Console.WriteLine("消息发送成功!");
        }
    }
}

额外验证

最后别忘了确认你的Bot Token是有效的(可以通过BotFather重新获取),Chat ID也是正确的(可以给@userinfobot发消息获取准确的ID),有时候无效的凭证也会引发奇怪的连接错误。

内容的提问来源于stack exchange,提问作者Vadim Pavlovich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 06:52:31