I’m building a Python bot for Telegram that automatically posts messages to groups. Everything works fine when I test commands manually, but I keep getting a pool timeout error during scheduled tasks.
The error happens when my scheduled function tries to fetch updates from Telegram API. Here’s my code:
import os
import random
from datetime import time
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
from telegram.request import HTTPXRequest
from dotenv import load_dotenv
load_dotenv()
BOT_TOKEN = os.getenv('BOT_TOKEN')
# Custom request configuration
custom_request = HTTPXRequest(
connection_pool_size=20,
read_timeout=60,
write_timeout=60,
connect_timeout=60,
pool_timeout=60,
media_write_timeout=60
)
# Bot setup
bot_app = Application.builder().token(BOT_TOKEN).request(request=custom_request).build()
# Send random content from file
async def broadcast_message(target_chat: int, context: ContextTypes.DEFAULT_TYPE):
print("Broadcasting message...")
with open('messages.txt', 'r', encoding='utf-8') as f:
data = f.read()
message_list = data.split('|')
selected_msg = random.choice(message_list)
await context.bot.send_message(chat_id=target_chat, text=selected_msg)
print("Message broadcasted successfully.")
# Command handlers
async def welcome_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
print("Welcome command triggered.")
greeting_text = "Hi there! I'm your automated bot. Available commands:\n\n"
command_list = [
"/welcome - Display this help message",
"/random - Send a random message"
]
greeting_text += "\n".join(command_list)
await context.bot.send_message(chat_id=update.effective_chat.id, text=greeting_text)
print("Welcome message delivered.")
async def random_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
print("Random command triggered.")
await broadcast_message(update.effective_chat.id, context)
# This is where the error occurs
async def daily_broadcast(context: ContextTypes.DEFAULT_TYPE):
print("Starting daily broadcast...")
# ERROR LINE: This call times out
chat_updates = await context.bot.get_updates(limit=100, allowed_updates=["message", "channel_post"])
for update_item in chat_updates:
if update_item.effective_chat and update_item.effective_chat.type in ['group', 'supergroup']:
await broadcast_message(update_item.effective_chat.id, context)
print("Daily broadcast completed.")
# Register handlers
bot_app.add_handler(CommandHandler('welcome', welcome_handler))
bot_app.add_handler(CommandHandler('random', random_handler))
# Schedule daily job
scheduler = bot_app.job_queue
scheduler.run_daily(daily_broadcast, time=time(hour=23, minute=0), days=(0, 1, 2, 3, 4, 5, 6))
# Start bot
print("Starting bot...")
bot_app.run_polling()
The error shows that all connections in the pool are busy and the request times out. I already tried increasing the timeout values but that didn’t fix it. The bot works fine for direct commands but fails during scheduled operations. Has anyone encountered this issue before? What’s the best way to handle connection pool management for scheduled Telegram bot tasks?