I’m working on a Telegram bot that uses OpenAI. The bot was fine until I added OpenAI API calls. Now I’m getting an error about closing a running event loop. I tried to fix it by removing async from the main function, but that led to another error about thread access.
Here’s a simplified version of my code:
import asyncio
from telegram.ext import Application, CommandHandler, MessageHandler, filters
from openai import AsyncOpenAI
async def initialize():
# Set up resources
pass
async def start(update, context):
await update.message.reply_text("Bot started!")
async def handle_message(update, context):
# Process message with OpenAI
response = "AI response"
await update.message.reply_text(response)
def run_bot():
app = Application.builder().token("BOT_TOKEN").build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT, handle_message))
app.run_polling()
async def main():
await initialize()
run_bot()
if __name__ == "__main__":
asyncio.run(main())
The error occurs when the bot tries to shut down. Any ideas on how to fix this?
hey, i had a similar problem. try making ur run_bot function async and use await with app.initialize() and app.start(). also, use await app.run_polling() instead of app.run_polling(). that fixed it for me. good luck!
I’ve dealt with similar event loop issues in Python async applications. The problem often arises from mixing async and sync code. A solution that worked for me was to make everything consistently asynchronous.
This approach ensures that all operations are handled asynchronously, which should resolve the event loop closure issue. Make sure to also handle any exceptions that might occur during the bot’s operation.
I’ve encountered a similar issue when working with async and Telegram bots. The problem likely stems from mixing synchronous and asynchronous code. Here’s what worked for me: I made the run_bot() function asynchronous and awaited it in the main function, while also using app.run_polling(stop_signals=None) to avoid conflicts with asyncio’s default signal handling. Additionally, wrapping the main execution in asyncio.run() ensured the event loop was managed properly.
Try modifying your main() and run_bot() functions like this: