Бот Telegram возвращает telegram.error.TimedOut: тайм-аут пулаPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Бот Telegram возвращает telegram.error.TimedOut: тайм-аут пула

Сообщение Anonymous »

Я пытаюсь написать бота для Telegram, который отправляет сообщения группам, в которые он добавлен. Вот код. Я предоставил весь код, но ошибка в строке: group_chats = await context.bot.get_updates(limit=100, Allow_updates=["message", "channel_post"])

Код: Выделить всё

from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
import random
import os
from dotenv import load_dotenv
from datetime import time
from telegram.request import HTTPXRequest

# Load environment variables from .env file
load_dotenv()

# Get the Telegram bot token from the environment variable
TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')

trequest = HTTPXRequest(connection_pool_size=20, read_timeout=60, write_timeout=60, connect_timeout=60, pool_timeout=60, media_write_timeout=60)

# Initialize the bot with your token
application = Application.builder().token(TELEGRAM_BOT_TOKEN).request(request=trequest).build()

# Function to send a random message from a file
async def send_random_message(chat_id: int, context: ContextTypes.DEFAULT_TYPE):
print("Sending a random message...")
# Read the file and split the content into an array
with open('content.txt', 'r', encoding='utf-8') as file:
content = file.read()
elements = content.split('~')

# Select a random element from the array
random_element = random.choice(elements)

# Send the message to the chat
await context.bot.send_message(chat_id=chat_id, text=random_element)
print("Random message sent.")

# Handler for the /start command
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
print("/start command received.")
welcome_message = "Hello! I'm your bot.  Here are the commands you can use:\n\n"
commands = [
"/start - Start the bot and see the available commands",
"/new - Get a random message"
]
welcome_message += "\n".join(commands)
await context.bot.send_message(chat_id=update.effective_chat.id, text=welcome_message)
print("Welcome message sent.")

# Handler for the /new command in direct messages and group chats
async def new_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
print("/new command received.")
await send_random_message(update.effective_chat.id, context)

# Scheduled job to send messages to all groups
async def scheduled_job(context: ContextTypes.DEFAULT_TYPE):
print("Scheduled job started.")
# Get a list of all group chats where the bot is added
group_chats = await context.bot.get_updates(limit=100, allowed_updates=["message", "channel_post"])
for update in group_chats:
if update.effective_chat and update.effective_chat.type in ['group', 'supergroup']:
# Send the message to the group chat
await send_random_message(update.effective_chat.id, context)
print("Scheduled job finished.")

# Add handlers
application.add_handler(CommandHandler('start', start_command))
application.add_handler(CommandHandler('new', new_command))

# Schedule the job to run at a specific time
job_queue = application.job_queue
job_queue.run_daily(scheduled_job, time=time(hour=22, minute=58), days=(0, 1, 2, 3, 4, 5, 6))

# Run the bot
print("Bot is running...")
application.run_polling()
Но возвращается по расписанию:

Код: Выделить всё

Bot is running...
Scheduled job started.
No error handlers are registered, logging exception.
Traceback (most recent call last):
File "~/.local/lib/python3.10/site-packages/anyio/_core/_tasks.py", line 115, in fail_after
yield cancel_scope
File "~/.local/lib/python3.10/site-packages/httpcore/_synchronization.py", line 123, in wait
await self._anyio_event.wait()
File "~/.local/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 1641, in wait
await self._event.wait()
File "/usr/lib/python3.10/asyncio/locks.py", line 214, in wait
await fut
asyncio.exceptions.CancelledError:  Cancelled by cancel scope 70fed2a86e90

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "~/.local/lib/python3.10/site-packages/httpcore/_exceptions.py", line 10, in map_exceptions
yield
File "~/.local/lib/python3.10/site-packages/httpcore/_synchronization.py", line 122, in wait
with anyio.fail_after(timeout):
File "/usr/lib/python3.10/contextlib.py", line 153, in __exit__
self.gen.throw(typ, value, traceback)
File "~/.local/lib/python3.10/site-packages/anyio/_core/_tasks.py", line 118, in fail_after
raise TimeoutError
TimeoutError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "~/.local/lib/python3.10/site-packages/httpx/_transports/default.py", line 69, in map_httpcore_exceptions
yield
File "~/.local/lib/python3.10/site-packages/httpx/_transports/default.py", line 373, in handle_async_request
resp = await self._pool.handle_async_request(req)
File "~/.local/lib/python3.10/site-packages/httpcore/_async/connection_pool.py", line 248, in handle_async_request
raise exc
File "~/.local/lib/python3.10/site-packages/httpcore/_async/connection_pool.py", line 239, in handle_async_request
connection = await status.wait_for_connection(timeout=timeout)
File "~/.local/lib/python3.10/site-packages/httpcore/_async/connection_pool.py", line 36, in wait_for_connection
await self._connection_acquired.wait(timeout=timeout)
File "~/.local/lib/python3.10/site-packages/httpcore/_synchronization.py", line 121, in wait
with map_exceptions(anyio_exc_map):
File "/usr/lib/python3.10/contextlib.py", line 153, in __exit__
self.gen.throw(typ, value, traceback)
File "~/.local/lib/python3.10/site-packages/httpcore/_exceptions.py", line 14, in map_exceptions
raise to_exc(exc) from exc
httpcore.PoolTimeout

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "~/.local/lib/python3.10/site-packages/telegram/request/_httpxrequest.py", line 276, in do_request
res = await self._client.request(
File "~/.local/lib/python3.10/site-packages/httpx/_client.py", line 1574, in request
return await self.send(request, auth=auth, follow_redirects=follow_redirects)
File "~/.local/lib/python3.10/site-packages/httpx/_client.py", line 1661, in send
response = await self._send_handling_auth(
File "~/.local/lib/python3.10/site-packages/httpx/_client.py", line 1689, in _send_handling_auth
response = await self._send_handling_redirects(
File "~/.local/lib/python3.10/site-packages/httpx/_client.py", line 1726, in _send_handling_redirects
response = await self._send_single_request(request)
File "~/.local/lib/python3.10/site-packages/httpx/_client.py", line 1763, in _send_single_request
response = await transport.handle_async_request(request)
File "~/.local/lib/python3.10/site-packages/httpx/_transports/default.py", line 372, in handle_async_request
with map_httpcore_exceptions():
File "/usr/lib/python3.10/contextlib.py", line 153, in __exit__
self.gen.throw(typ, value, traceback)
File "~/.local/lib/python3.10/site-packages/httpx/_transports/default.py", line 86, in map_httpcore_exceptions
raise mapped_exc(message) from exc
httpx.PoolTimeout

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "~/.local/lib/python3.10/site-packages/telegram/ext/_jobqueue.py", line 966, in _run
await self.callback(context)
File "tg_bot/./bot.py", line 56, in scheduled_job
group_chats = await context.bot.get_updates(limit=100, allowed_updates=["message", "channel_post"])
File "~/.local/lib/python3.10/site-packages/telegram/ext/_extbot.py", line 618, in get_updates
updates = await super().get_updates(
File "~/.local/lib/python3.10/site-packages/telegram/_bot.py", line 541, in decorator
result = await func(self, *args, **kwargs)
File "~/.local/lib/python3.10/site-packages/telegram/_bot.py", line 4177, in get_updates
await self._post(
File "~/.local/lib/python3.10/site-packages/telegram/_bot.py", line 629, in _post
return await self._do_post(
File "~/.local/lib/python3.10/site-packages/telegram/ext/_extbot.py", line 347, in _do_post
return await super()._do_post(
File "~/.local/lib/python3.10/site-packages/telegram/_bot.py", line 657,  in _do_post
return await request.post(
File "~/.local/lib/python3.10/site-packages/telegram/request/_baserequest.py", line 200, in post
result = await self._request_wrapper(
File "~/.local/lib/python3.10/site-packages/telegram/request/_baserequest.py", line 340, in _request_wrapper
raise exc
File "~/.local/lib/python3.10/site-packages/telegram/request/_baserequest.py", line 330, in _request_wrapper
code, payload = await self.do_request(
File "~/.local/lib/python3.10/site-packages/telegram/request/_httpxrequest.py", line 286, in do_request
raise TimedOut(
telegram.error.TimedOut: Pool timeout: All connections in the connection pool are occupied. Request was *not* sent to Telegram. Consider adjusting the connection pool size or the pool timeout.
Я пытался увеличить таймауты, но это не помогло

Подробнее здесь: https://stackoverflow.com/questions/781 ... ol-timeout
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»