VB.NET中Telegram Bot V18接收消息报错问题求助
问题解决:Telegram Bot V18 VB.NET StartReceiving 参数不匹配错误
需要修改的核心点
- 异步方法类型修正:Telegram Bot V18的
StartReceiving要求更新和错误处理方法是返回Task的异步函数,而非异步Sub。异步Sub无法匹配框架要求的委托类型,这是参数报错的直接原因。 - 数据类型修正:
update.Message.Chat.Id是Long类型,不能直接赋值给String变量,会引发类型转换错误。 - 接收配置优化:显式指定
AllowedUpdates,只接收需要的更新类型,避免不必要的资源消耗。
修改后的完整可运行代码
Imports Telegram.Bot Imports Telegram.Bot.Exceptions Imports Telegram.Bot.Polling Imports Telegram.Bot.Types Imports Telegram.Bot.Types.Enums Imports System.Threading Public Class Form1 Public TelegramBotToken As String = "YOUR TELEGRAM TOKEN HERE" Private cancellationTokenSource As CancellationTokenSource Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click cancellationTokenSource = New CancellationTokenSource() Dim bot1 = New TelegramBotClient(TelegramBotToken) Dim receiverOptions1 = New ReceiverOptions With { .AllowedUpdates = {UpdateType.Message} '仅接收消息类型更新 } bot1.StartReceiving( updateHandler:=AddressOf UpdateHandler, pollingErrorHandler:=AddressOf ErrorHandler, receiverOptions:=receiverOptions1, cancellationToken:=cancellationTokenSource.Token ) End Sub Private Async Function ErrorHandler(botClient As ITelegramBotClient, exception As Exception, ct As CancellationToken) As Task '添加错误日志逻辑,可根据需求输出到控制台或窗体控件 Dim errorMsg = $"错误类型: {exception.GetType().Name}, 消息: {exception.Message}" Console.WriteLine(errorMsg) '处理API专属错误,获取更多细节 If TypeOf exception Is ApiRequestException Then Dim apiEx = DirectCast(exception, ApiRequestException) Console.WriteLine($"API错误码: {apiEx.ErrorCode}, 描述: {apiEx.Description}") End If End Function Private Async Function UpdateHandler(botClient As ITelegramBotClient, update As Update, ct As CancellationToken) As Task If update.Type = UpdateType.Message Then Dim message = update.Message If message.Type = MessageType.Text Then Dim text As String = message.Text Dim chatId As Long = message.Chat.Id '修正为正确的Long类型 Dim username As String = If(message.Chat.Username, "无用户名") '处理空用户名情况 '将消息内容同步到窗体控件(避免跨线程操作报错) Me.Invoke(Sub() TextBox1.Text = $"收到消息: {text}{Environment.NewLine}" & "Chat ID: " & chatId & Environment.NewLine & "用户名: " & username End Sub) End If End If End Function '窗体关闭时优雅停止Bot接收任务 Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing cancellationTokenSource?.Cancel() End Sub End Class
关键细节说明
- 异步函数的必要性:VB.NET中异步
Sub仅适用于事件触发场景,而Telegram Bot框架需要通过返回Task来追踪异步操作的执行状态,确保消息处理流程的可靠性。 - 取消令牌管理:通过
CancellationTokenSource可以在窗体关闭或需要停止Bot时,安全终止接收任务,避免资源泄漏。 - 跨线程操作处理:在WinForm环境中,更新UI控件必须通过
Invoke方法切换到主线程,否则会引发跨线程操作异常。
内容的提问来源于stack exchange,提问作者Paul Falleyn
相关产品推荐
相关产品推荐

