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

C#中TelegramBotClient如何处理接收消息?

解决TelegramBotClient无OnMessage定义的问题

你遇到的问题是因为新版本的Telegram.Bot库已经移除了旧版本中的OnMessage事件,现在需要用以下两种主流方式来接收并处理消息:

方式一:使用长轮询(GetUpdatesAsync)

这是开发调试时最常用的方式,通过循环调用GetUpdatesAsync拉取新消息:

using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;

public static TelegramBotClient BotClient;

public static async Task Main(string[] args)
{
    BotClient = new TelegramBotClient("你的BotToken");
    int offset = 0; // 用于标记已处理过的消息ID

    while (true)
    {
        // 拉取最新的消息更新
        var updates = await BotClient.GetUpdatesAsync(offset: offset, timeout: 10);
        
        foreach (var update in updates)
        {
            if (update.Message != null && update.Message.Type == MessageType.Text)
            {
                // 调用消息处理方法
                await HandleIncomingMessage(update.Message);
            }
            
            // 更新offset,避免重复处理同一消息
            offset = update.Id + 1;
        }
        
        // 短时间间隔后再次轮询
        await Task.Delay(1000);
    }
}

private static async Task HandleIncomingMessage(Message message)
{
    // 这里写你的消息处理逻辑,比如回复消息
    await BotClient.SendTextMessageAsync(
        chatId: message.Chat.Id,
        text: $"你发送了:{message.Text}"
    );
}

方式二:使用ReceiverService(官方推荐的优雅方式)

通过继承UpdateHandler类来处理不同类型的更新,适合生产环境:

1. 创建消息处理类

using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Polling;
using Telegram.Bot.Exceptions;

public class BotUpdateHandler : UpdateHandler
{
    private readonly ITelegramBotClient _botClient;

    public BotUpdateHandler(ITelegramBotClient botClient)
    {
        _botClient = botClient;
    }

    // 处理文本消息
    public override async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
    {
        if (update.Message != null && update.Message.Type == MessageType.Text)
        {
            await _botClient.SendTextMessageAsync(
                chatId: update.Message.Chat.Id,
                text: $"收到你的消息:{update.Message.Text}",
                cancellationToken: cancellationToken
            );
        }
    }

    // 处理错误
    public override async Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
    {
        var errorMessage = exception switch
        {
            ApiRequestException apiEx => $"Telegram API错误:{apiEx.ErrorCode} - {apiEx.Message}",
            _ => exception.ToString()
        };

        Console.WriteLine(errorMessage);
        await Task.CompletedTask;
    }
}

2. 在Main方法中启动服务

using Telegram.Bot;
using Telegram.Bot.Polling;
using System.Threading;

public static async Task Main(string[] args)
{
    var botClient = new TelegramBotClient("你的BotToken");
    var updateHandler = new BotUpdateHandler(botClient);
    
    // 设置接收选项
    var receiverOptions = new ReceiverOptions
    {
        AllowedUpdates = Array.Empty<UpdateType>(), // 接收所有类型的更新
        ThrowPendingUpdates = true // 启动时忽略之前未处理的消息
    };

    // 启动长轮询服务
    botClient.StartReceiving(
        updateHandler: updateHandler.HandleUpdateAsync,
        pollingErrorHandler: updateHandler.HandlePollingErrorAsync,
        receiverOptions: receiverOptions,
        cancellationToken: new CancellationTokenSource().Token
    );

    // 获取Bot信息并输出,确认启动成功
    var me = await botClient.GetMeAsync();
    Console.WriteLine($"Bot {me.Username} 已启动,等待消息...");

    // 保持程序运行
    await Task.Delay(Timeout.Infinite);
}

另外注意:你原来的代码中BotClient.OnMessage += BotClient_OnMessage();还有一个错误——订阅事件时不需要加括号,正确写法应该是BotClient.OnMessage += BotClient_OnMessage;,但这个事件在新版本中已经不存在,所以直接用上面的方式替换即可。

内容的提问来源于stack exchange,提问作者Hossein Hedayati

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:11:05