我正在尝试编写一个电报机器人,将消息发送到它添加的组。这是代码。我提供了整个代码,但行中出现错误: group_chats = wait context.bot.get_updates(limit=100, allowed_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.
我尝试增加超时时间,但没有帮助
你可以通过
创建一个机器人实例bot = tel.Bot(token="your_token")
创建一个发送消息的异步函数
async def send_message(text):
await bot.sendMessage(chat_id=chat_id, text=text)
调用函数
asyncio.run(send_message("your message"))
如果第一次执行函数成功而下一次执行失败,您可以删除机器人实例并在调用 send_message 函数后立即创建(启动)一个机器人实例。
当你的机器在 Windows 中运行时,你必须在调用 send_message 之前编写此代码:
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
这是完整的代码:
bot = tel.Bot(token="your_token")
async def send_message(text):
await bot.sendMessage(chat_id=chat_id, text=text)
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(send_message("your first message"))
del bot
bot = tel.Bot(token="your_token")
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(send_message("your second message"))
del bot
bot = tel.Bot(token="your_token")