Aiogram Telegram Bot: Multiple Instances Causing Termination Error

Help! My Telegram bot keeps crashing

I’m having trouble with my Telegram bot. It starts fine but when users interact with it, it crashes. I’ve tried changing the API and bot token, but nothing helps. Here’s the error I’m getting:

ERROR: Failed to fetch updates - TelegramConflictError: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running

I’m sure I’m only running one instance of the bot. Has anyone else faced this issue? How can I fix it?

Here’s a simplified version of my code:

import asyncio
from aiogram import Bot, Dispatcher

TOKEN = 'my_secret_token'

async def handle_error(update, error):
    print('Error occurred. Shutting down bot...')

bot_instance = Bot(token=TOKEN)
dispatcher = Dispatcher(bot_instance)
dispatcher.register_errors_handler(handle_error, exception=Exception)

async def run_bot():
    await dispatcher.start_polling()

if __name__ == '__main__':
    asyncio.run(run_bot())

Any ideas what might be causing this?

yo, i had similar probs with my bot. try clearing ur webhook first:

await bot.delete_webhook(drop_pending_updates=True)

put this before starting polling. sometimes telegram gets stuck on old webhooks n causes weird errors. alsO, check ur hosting - some restart crashed apps automatically, messin things up. good luck!

I’ve dealt with this exact issue before. The problem might not be in your code, but in how Telegram’s servers are handling your bot’s requests. Sometimes, if your bot makes too many requests in a short time, Telegram can get confused and think there are multiple instances running.

One solution that worked for me was implementing exponential backoff. This means if your bot encounters an error, it waits a bit before trying again, and increases the wait time if it keeps failing. Here’s a simple implementation:

import time

max_retries = 5
retry_delay = 1

for attempt in range(max_retries):
    try:
        await dispatcher.start_polling()
        break
    except Exception as e:
        if attempt < max_retries - 1:
            time.sleep(retry_delay)
            retry_delay *= 2
        else:
            raise e

This approach can help reduce the load on Telegram’s servers and might resolve your issue. If it persists, you might want to check your network connectivity or consider using a different bot framework.

I’ve encountered this issue before, and it can be frustrating. The error suggests multiple instances are running, but that’s not always the case. One thing that helped me was implementing a graceful shutdown mechanism.

Try adding a signal handler to your code:

import signal

def signal_handler(sig, frame):
    print('Shutting down...')
    dispatcher.stop_polling()
    asyncio.create_task(bot_instance.close())

signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)

This ensures your bot shuts down properly when terminated. Also, double-check your hosting environment. Some platforms automatically restart crashed applications, which could lead to multiple instances.

If the problem persists, consider using a long polling interval:

await dispatcher.start_polling(timeout=60)

This reduced update frequency might help avoid conflicts. Hope this helps!