Getting telegram.error.TimedOut: Pool timeout error in Python Telegram bot

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?

The pool timeout happens because your scheduled function calls get_updates(), which tries to access the same connection pool that your main polling loop is already using. Since run_polling() is constantly pulling connections to get updates, there aren’t enough free connections left for your scheduled task.

Here’s the fix: remove the get_updates() call from your daily_broadcast function completely. Instead, save chat IDs when users interact with your bot. When someone sends /welcome or /random, capture their chat ID and store it in a file or database. Then your scheduled function can just loop through these saved IDs without making competing API calls. This prevents connection pool conflicts and makes your bot way more reliable for scheduled tasks.

you’re mixing polling with scheduled tasks - that’s what’s causing the conflicts. drop the get_updates call from daily_broadcast since it’s draining your connection pool. just save chat ids when users interact with your bot instead of pulling updates during scheduled runs. pool config looks good tho.

Had the exact same problem with my bot running scheduled tasks. Here’s the thing - timeout values aren’t your issue. The real problem is calling get_updates() inside your scheduled function. You’re basically making your scheduled task compete with the bot’s internal polling for the same resources, which kills your connection pool. Don’t use get_updates() in scheduled tasks at all. Instead, keep a separate list of chat IDs. Just collect these IDs when users talk to your bot and save them to a file or database. Then your daily_broadcast function can loop through that stored list without any API calls. I made this switch and the timeout errors vanished completely. Bottom line: keep your scheduled tasks separate from the update polling.