如何在Python Telegram Bot中获取频道消息并实现删除后重发?
解决方案:在重发前删除频道内对应帖子
前提条件
- 机器人必须是目标频道的管理员,且拥有删除消息的权限,否则无法执行删除操作。
- 转发的消息中需包含唯一
post_id标识(比如原代码计划添加的#<post_id>前缀),以此准确匹配需删除的旧帖子。
具体实现步骤
1. 修正API调用逻辑
python-telegram-bot v13.x 没有get_chat_messages方法,正确获取频道历史消息用context.bot.get_history(),删除消息用context.bot.delete_message()。同时这些方法为异步调用,需将start_reposting_command改为异步函数并使用await执行。
2. 修改start_reposting_command函数
以下是加入删除旧帖子逻辑的完整函数代码:
async def start_reposting_command(update, context): config = configparser.ConfigParser() config.read("config.ini") Bot_Status = config['Setting']['bot_status'] Agent_Token = config['Setting']['agent_bot_token'] f = open('Channels.json') Channels_list = json.load(f) if Bot_Status == "True": await update.message.reply_text('Reposting Started!') while Bot_Status == "True": # 实时读取配置,确保状态修改立即生效 config.read("config.ini") Bot_Status = config['Setting']['bot_status'] if Bot_Status != "True": break f = open('posts.json') data = json.load(f) for channel in Channels_list: channel_username = channel["username"] interval = int(channel["Interval"]) repost_delay = int(channel["Repost_delay"]) for post in data: post_id = post["id"] post_content = f"#{post_id}\n{post['message']}" # 步骤1:查找并删除频道内对应post_id的旧消息 try: # 获取频道最近50条消息(可根据需求调整limit值) history = await context.bot.get_history(chat_id=channel_username, limit=50) for msg in history: if msg.text and f"#{post_id}" in msg.text: await context.bot.delete_message(chat_id=channel_username, message_id=msg.message_id) print(f"已删除频道 {channel_username} 中旧帖子 #{post_id}") except Exception as e: print(f"处理旧消息出错:{str(e)}") continue # 步骤2:发送新帖子 try: await context.bot.send_message(chat_id=channel_username, text=post_content) print(f"已向频道 {channel_username} 发送帖子 #{post_id}") await asyncio.sleep(interval) except Exception as e: print(f"发送帖子出错:{str(e)}") continue # 频道间的转发延迟 await asyncio.sleep(60 * repost_delay) else: await update.message.reply_text('Bot Disabled')
3. 调整命令注册
由于函数改为异步,注册时无需额外添加run_async=True:
dp.add_handler(CommandHandler('start_rp', start_reposting_command))
关键逻辑说明
- 消息匹配:通过消息文本中的
#<post_id>标识定位旧帖子,避免误删无关内容。 - 异步处理:所有Telegram API调用使用
await,防止阻塞机器人其他操作。 - 异常捕获:添加异常处理,避免单个频道或帖子的操作失败导致机器人崩溃。
- 实时配置读取:循环内重新读取配置,确保修改机器人状态后立即生效。
内容的提问来源于stack exchange,提问作者karoakhgar82
相关产品推荐
相关产品推荐

