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

Telegram按钮点击无活动至Bot控制器及报错问题排查

Troubleshooting Telegram Button Clicks Not Reaching Bot Controller & "Bot Code Issue" Error

Hey there, let’s dig into why your Telegram bot’s button clicks aren’t hitting your MessagesController and throwing that frustrating "sorry, my bot code is having an issue" message. I’ve worked through similar headaches with Bot Framework and Telegram integrations, so here are the key fixes and checks to try:

1. Verify Your Telegram Webhook & Channel Configuration

First things first: if Telegram can’t send button click callbacks to your bot service, nothing will reach your controller.

  • Check Webhook Status: Use Telegram’s API to confirm your webhook is set correctly. Run this command (replace <YOUR_BOT_TOKEN> with your actual token):
    GET https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getWebhookInfo
    
    Look for the url field to ensure it matches your bot’s public endpoint, and check last_error_message for any delivery failures (like SSL issues or unreachable endpoints).
  • Confirm Bot Framework Channel Setup: Make sure you’ve added the Telegram channel in the Bot Framework Portal and entered the correct Telegram bot token. Mismatched tokens will block callbacks from being processed.
  • Ensure Public Access: If you’re testing locally, use a tool like ngrok to expose your service to the internet—Telegram can’t send requests to localhost.

2. Capture Raw Request Data to Diagnose Binding Issues

Your standard [FromBody] Activity activity binding might be failing silently. Let’s bypass it temporarily to see if requests are even reaching your controller:

[BotAuthentication]
public class MessagesController : ApiController
{
    private readonly ILogger<MessagesController> _logger;

    public MessagesController(ILogger<MessagesController> logger)
    {
        _logger = logger;
    }

    [ResponseType(typeof(void))]
    public virtual async Task<HttpResponseMessage> Post()
    {
        // Read raw request content first
        var rawRequest = await Request.Content.ReadAsStringAsync();
        _logger.LogInformation("Received raw request: {RawRequest}", rawRequest);

        // Try deserializing manually to catch errors
        Activity activity = null;
        try
        {
            activity = JsonConvert.DeserializeObject<Activity>(rawRequest);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to deserialize Activity from raw request");
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }

        if (activity == null)
        {
            _logger.LogWarning("Deserialized Activity is null");
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }

        // Now process the activity as usual
        await HandleActivity(activity);
        return Request.CreateResponse(HttpStatusCode.OK);
    }

    private async Task HandleActivity(Activity activity)
    {
        // Your existing message/event handling logic here
    }
}

This will let you see:

  • If any request is coming in when you click the button
  • If deserialization is failing (common if Telegram’s callback data is malformed or too long)

3. Handle the Correct Activity Type for Button Clicks

Telegram inline button clicks don’t come through as ActivityTypes.Message—they’re sent as ActivityTypes.Event! If your controller only checks for Message type, you’ll completely miss button callbacks.

Update your logic to handle Event types, where the button’s callback_data is stored in the Activity.Value property:

private async Task HandleActivity(Activity activity)
{
    if (activity.Type == ActivityTypes.Message)
    {
        // Handle regular messages
        var reply = activity.CreateReply("Got your message!");
        await ConnectorClient.Conversations.ReplyToActivityAsync(reply);
    }
    else if (activity.Type == ActivityTypes.Event)
    {
        // Handle Telegram button clicks
        var callbackData = activity.Value?.ToString();
        _logger.LogInformation("Received button callback: {CallbackData}", callbackData);
        
        // Send a response to confirm the click was received
        var reply = activity.CreateReply($"You clicked the button with data: {callbackData}");
        await ConnectorClient.Conversations.ReplyToActivityAsync(reply);
    }
}

4. Fix Bot Authentication & Adapter Configuration

The [BotAuthentication] attribute relies on your app settings to validate requests. Double-check:

  • Your appsettings.json has the correct MicrosoftAppId and MicrosoftAppPassword from the Bot Framework Portal.
  • If you’re using a custom Telegram adapter, ensure it’s registered correctly in your Startup.cs with the right token:
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers().AddNewtonsoftJson();

    services.AddSingleton<ICredentialProvider>(new SimpleCredentialProvider(
        Configuration["MicrosoftAppId"], 
        Configuration["MicrosoftAppPassword"]));

    services.AddSingleton<IBotFrameworkHttpAdapter, TelegramAdapter>(sp =>
    {
        var credentialProvider = sp.GetRequiredService<ICredentialProvider>();
        var adapter = new TelegramAdapter(credentialProvider);
        adapter.OnTurnError = async (turnContext, exception) =>
        {
            // Log errors instead of letting them bubble up to the default message
            var logger = sp.GetRequiredService<ILogger<TelegramAdapter>>();
            logger.LogError(exception, "Unhandled error during turn");
            await turnContext.SendActivityAsync("Oops, something went wrong!");
        };
        return adapter;
    });

    services.AddSingleton<IBot, YourBotClass>();
}

Adding an OnTurnError handler will also let you replace the generic "bot code issue" message with something more helpful, while logging the real error.

5. Check for Telegram Callback Data Limits

Telegram limits callback_data to 64 bytes. If your button’s payload is longer than that, Telegram will truncate it, leading to invalid Activity data that Bot Framework can’t parse. Keep your callback data short (e.g., use IDs instead of full strings) to avoid this.


By working through these steps, you should be able to pinpoint whether the issue is with delivery, binding, activity type handling, or configuration. Let me know if you find specific errors in the logs—I can help narrow it down further!

内容的提问来源于stack exchange,提问作者Nikita Zakoryuchkin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:52:09