C# Telegram bot integration issues in ASP.NET Global.asax

I’m trying to integrate a Telegram bot into my ASP.NET web application using C#, but I’m running into problems. The bot doesn’t seem to work properly when I initialize it in the Application_Start method.

Here’s my current implementation:

using System;
using System.Web;
using Telegram.Bot;

namespace TelegramWebApp
{
    public class Global : HttpApplication
    {
        private TelegramBotClient telegramClient = new TelegramBotClient("YOUR_BOT_TOKEN");
        private DatabaseContext dbContext = new DatabaseContext();

        protected void Application_Start(object sender, EventArgs e)
        {
            telegramClient.OnMessage += HandleIncomingMessage;
            telegramClient.StartReceiving();
        }

        private void HandleIncomingMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            // Message processing logic here
        }
    }
}

My web application is hosted on a server without any hosting issues, but the Telegram bot functionality isn’t working as expected. What could be causing this problem and how can I fix it?

I hit the same issue with Telegram bots in ASP.NET. Your approach has two big problems: web apps are stateless and IIS can recycle them anytime, killing your bot’s polling connection. Plus Application_Start isn’t meant for long-running stuff like bot polling. I switched to webhooks instead of polling and it works way better. Set up a webhook endpoint in your ASP.NET app - Telegram calls it directly when messages come in. No persistent connections needed, and it plays nice with the web app lifecycle. Just create a controller method to handle incoming webhook requests and process messages there. Much more reliable than trying to keep background threads alive.

Your main problem is using the old polling approach in a web app. Web apps can’t handle persistent background operations like StartReceiving() - they’re not built for it. I ran into this same issue and fixed it with webhooks through a proper controller endpoint. You’ll need to register your webhook URL with Telegram using SetWebhookAsync, then create an API controller that handles POST requests from Telegram. The controller method should accept webhook updates and process them right away. Also, don’t initialize TelegramBotClient as an instance variable in Global.asax - use dependency injection or make it static at least. Your current setup will break when IIS restarts the application pool, which happens all the time, and you won’t even know the polling connection died.

yeah, polling doesn’t work in web apps cause of how iis handles app lifecycle. your bot connection drops every time the app pool recycles and you won’t even know it happened. webhooks are def the way to go - way more stable for web hosting.