如何用Python实现Telegram Bot删除指定消息及自定义命令?
Telegram Bot 功能实现补充方案
一、核心修改说明
要实现你需要的两个功能,需补充消息监听处理器、用线程避免阻塞Bot,并确保Bot拥有群聊消息删除权限。以下是具体实现代码:
二、完整修改后代码
import os import time import telebot import threading # 初始化Bot,简化API_KEY获取逻辑 API_KEY = os.getenv('API_KEY') bot = telebot.TeleBot(API_KEY) # -------------------------- # 功能1:删除含"Escrow Wallet"的消息并延迟发送提示 # -------------------------- def send_escrow_prompt(chat_id): """延迟3分钟发送自定义提示消息""" time.sleep(3 * 60) prompt_msg = "💬 这里替换为你需要的自定义正确提示内容,比如关于托管钱包的规范说明" bot.send_message(chat_id, prompt_msg) @bot.message_handler(func=lambda msg: "Escrow Wallet" in msg.text, content_types=['text']) def delete_escrow_messages(msg): """监听并删除所有包含"Escrow Wallet"的消息""" try: # 删除触发消息 bot.delete_message(msg.chat.id, msg.message_id) # 启动线程执行延迟发送,避免阻塞Bot主进程 threading.Thread(target=send_escrow_prompt, args=(msg.chat.id,)).start() except Exception as e: print(f"删除Escrow消息失败: {str(e)}") # -------------------------- # 功能2:处理/balance命令,删除其他Bot错误消息并延迟发送余额提示 # -------------------------- # 替换为实际的其他Bot用户ID,用于识别需要删除的错误消息发送者 OTHER_BOT_ID = 123456789 # 可通过@username_to_id_bot获取目标Bot的ID def send_balance_prompt(chat_id): """延迟2分钟发送自定义余额提示""" time.sleep(2 * 60) balance_msg = "📍 ESCROW WALLET\n\n💬 Wait for the balance to show up here, then continue with the deal. The funds will show up after 1 blockchain confirmation.\n\n💰 BALANCE: 0.00775835 BTC [$1730.94]" bot.send_message(chat_id, balance_msg) @bot.message_handler(commands=["balance"]) def handle_balance(msg): """处理/balance命令,先删除用户发送的命令消息""" try: bot.delete_message(msg.chat.id, msg.message_id) # 启动线程执行延迟发送 threading.Thread(target=send_balance_prompt, args=(msg.chat.id,)).start() except Exception as e: print(f"删除/balance命令消息失败: {str(e)}") @bot.message_handler(func=lambda msg: msg.from_user.id == OTHER_BOT_ID and "错误余额关键词" in msg.text, content_types=['text']) def delete_other_bot_errors(msg): """删除其他Bot发送的错误余额消息""" try: bot.delete_message(msg.chat.id, msg.message_id) except Exception as e: print(f"删除其他Bot错误消息失败: {str(e)}") # -------------------------- # 原有/auth命令保留(优化为线程执行避免阻塞) # -------------------------- @bot.message_handler(commands=["auth"]) def handle_auth(msg): threading.Thread(target=send_auth_prompt, args=(msg.chat.id,)).start() def send_auth_prompt(chat_id): time.sleep(3 * 60) auth_msg = "💬 @log2, the funds have been deposited in the escrow wallet. You can go ahead and deliver the product(s) to the buyer. When @Audio is satisfied, he can paste /release into the chat or /contact in case of a dispute\n\n 💡 The seller can also /refund the buyer!" bot.send_message(chat_id, auth_msg) # 启动Bot bot.infinity_polling()
三、关键注意事项
- 权限配置:必须将Bot设为群聊管理员,并授予「删除消息」权限,否则无法执行删除操作
- 线程优化:所有延迟任务都用
threading.Thread执行,避免time.sleep阻塞整个Bot的消息处理流程 - 其他Bot识别:需要将
OTHER_BOT_ID替换为实际的错误消息发送Bot的ID;如果无法确定ID,也可通过msg.from_user.is_bot判断所有Bot发送的消息,再结合内容关键词筛选需要删除的消息 - 自定义内容:根据需求修改各个提示消息的文本内容
内容的提问来源于stack exchange,提问作者yxngkxng 480
相关产品推荐
相关产品推荐

