RuntimeError: This event loop is already running — how to fix it in a Telegram bot
RuntimeError: This event loop is already running, and its sibling asyncio.run() cannot be called from a running event loop, mean the code tried to start an asyncio event loop inside one that is already running: python-telegram-bot's run_polling inside your own asyncio.run, aiogram's run_polling inside an async main, asyncio.run inside a handler, or a Jupyter notebook. Start the loop once, at the bottom of the program, and await everything inside it.
By Livops team, the people who build and run LivopsUpdated
The two errors, as Python raises them:
RuntimeError: This event loop is already running
RuntimeError: asyncio.run() cannot be called from a running event loop
They have two close relatives, and all four come from the same check:
| Message | Raised by |
|---|---|
This event loop is already running |
loop.run_until_complete() or loop.run_forever() on the loop that is already running[5] |
asyncio.run() cannot be called from a running event loop |
asyncio.run() while a loop is running in the same thread[1][6] |
Runner.run() cannot be called from a running event loop |
asyncio.Runner.run(), in the same situation[1][6] |
Cannot run the event loop while another loop is running |
run_until_complete() on a second loop while another one runs in the thread[5] |
This page explains what the errors mean, the ways a Telegram bot runs into them, and the right way to start python-telegram-bot and aiogram 3 so that there is exactly one loop. It ends with how it looks on Livops.
What does the error mean?
asyncio.run() is meant to be the main entry point of an asyncio program, and should ideally be called only once[1]. It creates a new event loop, runs your coroutine on it, and closes the loop at the end[1]. It cannot be called while another asyncio event loop is running in the same thread[1]: CPython checks that first and fails fast with “asyncio.run() cannot be called from a running event loop”[6].
The lower-level loop.run_until_complete() and loop.run_forever() make the same check. Asked to run a loop that is already running, they raise “This event loop is already running”; asked to run a second loop while another one runs in the thread, they raise “Cannot run the event loop while another loop is running”[5].
Inside an async def — a handler, your main() coroutine, a notebook cell — a loop is by definition already running. Any code there that tries to start a loop, rather than await something on the current one, fails. Python’s documentation says application code should typically use asyncio.run() and should rarely need the loop object or its methods at all[2].
Causes, most common first
1. python-telegram-bot: run_polling() inside your own asyncio.run()
async def main():
app = Application.builder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
await setup_database()
app.run_polling() # RuntimeError: This event loop is already running
asyncio.run(main())
Application.run_polling() is a plain function, not a coroutine. It gets the current event loop itself and drives initialization, post_init and startup with loop.run_until_complete()[8]. Called inside asyncio.run(main()), the loop it gets is the one already running main(), and run_until_complete() refuses[5]. Writing await app.run_polling() does not help: the call runs, and fails, before there is anything to await.
2. aiogram 3: dp.run_polling() inside async def main()
aiogram 3 starts long polling with either Dispatcher.start_polling() or Dispatcher.run_polling()[10]. start_polling() is a coroutine you await; run_polling() is a plain function that starts its own loop with asyncio.run(), or with asyncio.Runner on uvloop when uvloop is installed[11]. Inside a coroutine, it fails:
async def main():
bot = Bot(TOKEN)
dp.run_polling(bot) # RuntimeError: asyncio.run() cannot be called from a running event loop
asyncio.run(main())
With uvloop installed, the message names Runner.run() instead[6][11].
3. asyncio.run() or run_until_complete() inside a handler
Handlers are coroutines that the library runs on its loop. Calling asyncio.run(fetch_price(symbol)) or loop.run_until_complete(fetch_price(symbol)) there to “get the result” tries to start a loop inside the running one: the first fails with the asyncio.run() message[6], the second with “This event loop is already running”[5]. The error comes from that one handler, every time it runs, rather than at startup.
4. A synchronous helper that starts its own loop
The same thing one level down: a synchronous function — your own wrapper, or a library’s sync API — that calls asyncio.run() inside, called from a handler. The traceback ends in that function or library rather than in your handler, which makes it look like a library bug.
5. Jupyter notebooks and other hosts that already run a loop
nest_asyncio’s README names web servers, GUI applications and Jupyter notebooks as places where the loop is already running when your code starts[12]. A bot that works with python bot.py fails in a notebook cell with the same errors, because the cell itself runs inside a loop.
How to fix it
python-telegram-bot: let run_polling() own the loop
Call run_polling() from plain synchronous code at the bottom of the file, with no asyncio.run() around it. Async setup goes into post_init: run_polling() runs that callback after initialize() and before polling starts, and it is meant for startup logic that has to await coroutines[9].
from telegram.ext import Application, CommandHandler
async def post_init(app: Application) -> None:
await setup_database()
await app.bot.set_my_commands([("start", "Start the bot")])
def main() -> None:
app = Application.builder().token(TOKEN).post_init(post_init).build()
app.add_handler(CommandHandler("start", start))
app.run_polling()
if __name__ == "__main__":
main()
run_polling() shuts the application down when KeyboardInterrupt or SystemExit is raised[7], and outside Windows it listens for SIGINT, SIGTERM and SIGABRT by default[8]. With close_loop=True, the default, it closes the event loop on shutdown[7]. To stop it from inside a handler, a job or an error callback, call application.stop_running()[8].
python-telegram-bot next to other asyncio code: start it by hand
If the bot has to share one loop with something else — a web server, a second bot, a scheduler — python-telegram-bot’s documentation says run_polling() is likely not the best choice, because it blocks the event loop until a stop signal arrives. Its advice is to call the startup and shutdown methods yourself, and then keeping the loop running is your job[7]:
import asyncio
from telegram.ext import Application, CommandHandler
async def main() -> None:
app = Application.builder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
async with app: # initialize() ... shutdown()
await app.start() # processes updates
await app.updater.start_polling() # fetches them
await run_web_server_until_stopped() # your code, on the same loop
await app.updater.stop()
await app.stop()
asyncio.run(main())
async with application is roughly initialize() and, in a finally, shutdown(); start() alone does not fetch updates, which is why the updater is started too[8]. Here asyncio.run() is called exactly once, and nothing inside it starts another loop.
aiogram 3: asyncio.run(main()) with await dp.start_polling(bot)
import asyncio
from aiogram import Bot, Dispatcher
dp = Dispatcher()
async def main() -> None:
bot = Bot(TOKEN)
await setup_database()
await dp.start_polling(bot)
if __name__ == "__main__":
asyncio.run(main())
This is the shape aiogram’s long-polling documentation shows: an async main() that awaits start_polling(), run with asyncio.run(main())[10]. If you have no async setup, dp.run_polling(bot) on its own, from plain code, starts the loop for you[10][11].
Leaving out the await before dp.start_polling(bot) gives the opposite symptom: no RuntimeError, the program simply ends, and Python warns that the coroutine was never awaited[4].
Inside a handler: await, don’t run
# wrong: starts a second loop inside the running one
price = asyncio.run(fetch_price(symbol))
# right: runs on the loop that is already there
price = await fetch_price(symbol)
For work that should go on after the handler returns, asyncio.create_task() schedules it on the same loop. Keep a reference to the task: the loop holds only weak references, and a task nobody references can be garbage-collected before it finishes[3].
Sync code that starts its own loop, or blocks: a thread
asyncio.to_thread() runs a function in a separate thread[3]. That thread has no running loop, so a sync helper that calls asyncio.run() inside works there, since the restriction is per thread[1]. It is also the fix for blocking calls — a sync HTTP client, a slow SDK — which would otherwise hold up every other handler on the loop[3][4].
report = await asyncio.to_thread(legacy_client.get_report, user_id)
From another thread: run_coroutine_threadsafe()
When code in another thread — a Flask view, a scheduler’s thread — has to make the bot send something, do not start a second loop there for the bot. Submit the coroutine to the bot’s own loop with asyncio.run_coroutine_threadsafe(), which is meant to be called from a different thread than the one where the loop runs[3]:
# at startup, inside the bot's loop (post_init in python-telegram-bot, main() in aiogram)
bot_loop = asyncio.get_running_loop()
# later, in the other thread
future = asyncio.run_coroutine_threadsafe(bot.send_message(chat_id, "Done"), bot_loop)
future.result(timeout=30)
get_running_loop() returns the loop running in the current thread, and raises a RuntimeError if there is none[2], so call it from inside the bot’s startup coroutine.
In a notebook: run the bot as a script
Develop the handlers wherever you like, but start the bot with python bot.py from a terminal, not from a cell. A polling bot is a long-running process; a notebook is the wrong place to keep one alive anyway.
What about nest_asyncio?
nest_asyncio patches asyncio so that asyncio.run() and run_until_complete() can be nested[12]. Its README says nothing about production use, the repository was archived by its owner in March 2024 and is read-only, and only asyncio’s own loops can be patched — loops from other projects, such as uvloop, generally cannot[12]. aiogram’s run_polling() switches to uvloop whenever uvloop is installed[11]. Keep it, if at all, for experiments in a notebook; for a bot that runs for months, fix the structure: one loop, started once.
On Livops
- The error stops the bot at start. A RuntimeError at startup ends the process, and the deploy fails as
start_failed; the traceback is the bot’s last words on the Logs page. A bot’s old version is stopped before the new one starts, because two copies polling Telegram would conflict, so the bot is down until a deploy succeeds. See The app did not start. - No error, but the bot exits. A missing
awaitbeforestart_polling()ends the program on its own with code 0. See The program finished on its own. - The start command. A polling bot runs as a worker, an always-on background process (Cron and workers). For the layouts above the start command is
.venv/bin/python bot.py, set in Settings → Start or as aworker:line in aProcfile; a file withif __name__ == "__main__"is one of the things Livops looks for to find a bot. See No start command. - Errors in handlers. They are on the project’s Logs page too;
livops logs <service> -ffollows them from the terminal (CLI). If a bot crashes because of a bug in its own code, Livops sends you the line it failed on in Telegram.
A bot costs 19 credits a month (19,000 so’m); see Pricing.
Questions
What does RuntimeError This event loop is already running mean?
Code asked an asyncio event loop to start while that same loop was already running. In a Telegram bot it usually means loop.run_until_complete was called from inside async code, or python-telegram-bot's run_polling was called from inside your own asyncio.run. Inside async code you await things; you do not start the loop again.
Why do I get asyncio.run() cannot be called from a running event loop?
asyncio.run starts a new event loop, and Python refuses to do that while another loop is running in the same thread. It happens when asyncio.run is called inside a handler or another coroutine, or when aiogram's run_polling, which calls asyncio.run itself, is called inside an async main function.
How do I run async setup code before python-telegram-bot starts polling?
Pass it to ApplicationBuilder.post_init. run_polling awaits that coroutine after initializing the application and before polling starts, so you can connect to a database or set bot commands there. Then call application.run_polling() from plain synchronous code, without asyncio.run around it.
What is the right way to start an aiogram 3 bot?
Write an async main function that does your setup and ends with await dp.start_polling(bot), and run it once with asyncio.run(main()) at the bottom of the file. Use dp.run_polling(bot) only from plain synchronous code, never inside a coroutine.
Should I use nest_asyncio to fix it?
Not for a bot in production. It patches asyncio to allow nested loops, its README says nothing about production use, the repository has been archived and read-only since March 2024, and it cannot patch other loops such as uvloop. Fix the structure instead: one loop, started once.
Why does my bot work as a script but fail in Jupyter?
A notebook cell already runs inside an event loop, so asyncio.run or run_polling inside a cell tries to start a second one. Run the bot as a script with python bot.py from a terminal instead of from a notebook.
How do I make the bot send a message from another thread, such as a Flask view?
Do not start a new loop in that thread for the bot. Save the bot's running loop at startup and submit the coroutine to it with asyncio.run_coroutine_threadsafe, which is meant to be called from a different thread than the one running the loop.
Sources
- Python documentation — asyncio Runners (asyncio.run, asyncio.Runner) (docs.python.org). Checked .
- Python documentation — asyncio Event Loop (docs.python.org). Checked .
- Python documentation — Coroutines and Tasks (create_task, to_thread, run_coroutine_threadsafe) (docs.python.org). Checked .
- Python documentation — Developing with asyncio (docs.python.org). Checked .
- CPython source — Lib/asyncio/base_events.py (raw.githubusercontent.com). Checked .
- CPython source — Lib/asyncio/runners.py (raw.githubusercontent.com). Checked .
- python-telegram-bot documentation — telegram.ext.Application (docs.python-telegram-bot.org). Checked .
- python-telegram-bot source — telegram/ext/_application.py (raw.githubusercontent.com). Checked .
- python-telegram-bot source — telegram/ext/_applicationbuilder.py (raw.githubusercontent.com). Checked .
- aiogram documentation — Long-polling (docs.aiogram.dev). Checked .
- aiogram source — aiogram/dispatcher/dispatcher.py (raw.githubusercontent.com). Checked .
- nest_asyncio — GitHub repository and README (github.com). Checked .
Put your project online today
Connect GitHub or drop a folder. No card is asked for.
Deploy your botRelated
- telegram.error.TimedOut: Timed out — how to fix Telegram bot timeoutstelegram.error.TimedOut: Timed out in python-telegram-bot, TelegramNetworkError: HTTP Client says - Request timeout error in aiogram, and HttpError in grammY all mean the bot's request to the Bot API got no answer in time. Most often a file upload needs longer than the default timeout, or the connection, DNS or a proxy on the way to api.telegram.org is slow. Raise the timeouts for media, retry with backoff, and test the connection with curl.
- python-telegram-bot hosting: deploying a v22 botA python-telegram-bot bot runs as one Application: run_polling() for polling, run_webhook() with the webhooks extra for a webhook. Both stop cleanly on SIGTERM. On Livops it runs from a push with bot.py and requirements.txt for 19 credits a month (19,000 so'm).
- aiogram bot hosting: how to deploy an aiogram 3 botAn aiogram 3 bot needs one process that never stops, the token in an environment variable, state kept outside memory and a clean exit on SIGTERM. On Livops you push a repository with bot.py and requirements.txt, and it runs for 19 credits a month (19,000 so'm), polling or webhook.
- How to keep a Telegram bot running 24/7A bot run with python bot.py or node bot.js stops when the terminal closes, the laptop sleeps or the code crashes, and two copies polling one token knock each other off with 409 Conflict. Keep exactly one copy running under something that restarts it — systemd, Docker or a platform — and stop it cleanly on SIGTERM. On Livops a bot runs from a push for 19 credits a month (19,000 so'm).
- Conflict: terminated by other getUpdates request — how to fix itTelegram is telling your bot that another process called getUpdates with the same token and took the connection over. Two copies of the bot are polling at once: stop the other one (usually the copy still running on your computer or an old server), or get a new token from @BotFather, and the error stops.
- Bad Request: query is too old and response timeout expired or query ID is invalid — how to fix itBad Request: query is too old and response timeout expired or query ID is invalid means answerCallbackQuery came too late for a button press, or got the wrong ID. The handler did slow work before answering, or the bot was down and is now working through presses that queued up. Answer the callback query first, do the slow work after, and ignore this error for stale presses.
- How to run a Python script 24/7 (and keep it running)A script started in a terminal stops when the terminal closes, the SSH connection drops or the laptop sleeps. To keep it running you need something that starts it again: a systemd service with Restart=always, Docker with a restart policy, or a platform's background worker. On Livops it runs as a worker for 19 credits a month (19,000 so'm).
- RuntimeError: Event loop is closed — how to fix it in Python asyncioRuntimeError: Event loop is closed means code asked an asyncio event loop to do something after that loop had been closed: an aiohttp or httpx client created inside one asyncio.run() and used in the next, a session closed after the program's loop ended, python-telegram-bot's run_polling() restarted in the same process, or, on Windows, a transport cleaned up at exit. Create clients inside the running loop, close them before it ends, and run the loop once.