如何解决Telegram Bot中Updater的TypeError:缺少update_queue参数?
问题解决:python-telegram-bot Updater初始化报错
错误原因
你遇到的TypeError: __init__() missing 1 required positional argument: 'update_queue',是因为python-telegram-bot v20及以上版本已完全移除Updater类,旧版本的初始化逻辑不再兼容。
修正方案
改用新版本的Application类替代Updater,同时调整代码适配异步环境(用异步请求库避免阻塞定时任务)。以下是修正后的完整代码:
import asyncio import aiohttp from bs4 import BeautifulSoup from telegram import InputMediaPhoto from telegram.ext import ApplicationBuilder # Telegram Bot API Token API_TOKEN = 'XXXXXXXXXXXXXXXXX' # URL of the website URL = 'https://chemiehalle.de' # List for storing seen posts seen_posts = [] # Async function for fetching posts async def get_posts(bot): async with aiohttp.ClientSession() as session: async with session.get(URL) as res: # Parse HTML content soup = BeautifulSoup(await res.text(), 'html.parser') # Find all posts on the website posts = soup.find_all('article') # 倒序处理,优先检测最新帖子 for post in reversed(posts): # Get title of the post title = post.find('h2', class_='entry-title').text.strip() # Check if post has already been seen if title not in seen_posts: try: # Get image URL image_src = post.find('img')['src'] # Get short text of the post text = post.find('div', class_='entry-content clearfix').find('p').text.strip() # Send image, title, and text as message await bot.send_media_group( chat_id='@chemiehalleBot', media=[InputMediaPhoto(media=image_src, caption=f"{title}\n\n{text}")] ) # Add title of the post to the list of seen posts seen_posts.append(title) print(f"New post sent: {title}") except Exception as e: print(f"Error processing post: {e}") # Main loop async def main(): # Initialize Telegram Bot with ApplicationBuilder application = ApplicationBuilder().token(API_TOKEN).build() bot = application.bot while True: await get_posts(bot) print("Checked for new posts") await asyncio.sleep(15) if __name__ == "__main__": asyncio.run(main())
关键改动说明
- 替换Updater为ApplicationBuilder:这是python-telegram-bot v20+的标准初始化方式
- 异步请求改造:用
aiohttp替代requests,避免同步请求阻塞async事件循环 - 异步消息发送:调用
bot.send_media_group时添加await,适配异步上下文 - 异常捕获:增加错误处理,避免单个帖子处理失败导致程序崩溃
- 帖子倒序处理:确保最新发布的帖子优先被检测和推送
前置依赖安装
执行代码前需要安装异步请求库:
pip install aiohttp
内容的提问来源于stack exchange,提问作者Nicholas
相关产品推荐
相关产品推荐

