发送 Python Telegram Bot 后删除旧的机器人消息

时间:2021-07-09 23:27:34

标签: python telegram python-telegram-bot

我的机器人是一个“夜间模式”机器人,从晚上 10 点开始到早上 7 点结束,它会删除这两者之间的消息。我正在尝试删除从机器人发送的先前的夜间模式消息,但不确定如何处理,我考虑过存储先前的消息更新,然后向其添加 1 并存储该消息,但我不确定如何进行如果机器人在多个组中运行。这是我的代码:

import logging
from telegram import Update, ForceReply
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext, Handler
import datetime as dtm
import pytz
night_hours = ['22','23','00','01','02','03','04','05','06']
allowed_groups = ['GROUP ID 1','GROUP ID 2','GROUP ID 3']

# Enable logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)

logger = logging.getLogger(__name__)
def error(update, context):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, context.error)

def start(context: CallbackContext):
    morning_time = dtm.time(hour=7, minute=0, tzinfo=pytz.timezone('Europe/London'))
    evening_time = dtm.time(hour=22, minute=0, tzinfo=pytz.timezone('Europe/London'))
    context.job_queue.run_daily(morning_message, morning_time)
    context.job_queue.run_daily(night_message, evening_time)

def log_channel(context: CallbackContext,name,chat_name,message):

    deleted_message = ("Message Deleted from *" +name+ "* in the group *'" +chat_name+ "'*: " +message)
    context.bot.send_message(chat_id="LOG CHANNEL ID", text=deleted_message,
                             disable_notification=True, parse_mode="MARKDOWNV2")
    print(deleted_message)

def morning_message(context: CallbackContext):
    context.bot.send_message(chat_id="TEST GROUP ID",text="*NIGHT MODE END:*\n\nMessage sending enabled until 10PM",
                             disable_notification=True,parse_mode="MARKDOWNV2")

def night_message(context: CallbackContext):
    context.bot.send_message(chat_id="TEST GROUP ID", text="*NIGHT MODE START:*\n\nMessage sending disabled until 7AM",
                             disable_notification=True,parse_mode="MARKDOWNV2")

def during_night_mode(update: Update,context: CallbackContext):
    UK = pytz.timezone('Europe/London')
    uk_time = dtm.datetime.now(UK).strftime('%H:%M:%S')
    hour = dtm.datetime.now(UK).strftime('%H')
    chat_id = update.message.chat.id
    chat_name = update.message.chat.title
    message_id = update.message.message_id
    print(chat_id)
    print(message_id)
    incoming_text = str(update.message.text)
    incoming_entities = update.message.entities #images, videos, files etc... probably not gonna use.
    message_sender = str(update.message.from_user.first_name)
    print(hour)
    if str(hour) in night_hours and str(chat_id) in allowed_groups: # and Enabled == True
        print("working")
        context.bot.delete_message(chat_id,message_id)
        log_channel(context,message_sender,chat_name,incoming_text)

def main() -> None:
    """Start the bot."""
    updater = Updater("BOT KEY")
    dp = updater.dispatcher
    #dp.add_handler(CommandHandler("start", start))#, pass_job_queue=True))
    #dp.add_handler(CommandHandler(start))
    dp.add_handler(MessageHandler(Filters.all,during_night_mode))
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()
    start(dp)
    updater.idle()

if __name__ == '__main__':
    main()

谢谢

编辑 1: 基本上,我只希望在聊天中始终有 1 个夜间模式消息实例。例如,当早上的消息运行时,它会删除之前的夜间消息,这样就不会用消息使聊天变得混乱。

1 个答案:

答案 0 :(得分:0)

send_message() 节目的文档

Returns: On success, the sent message is returned.

Return type: telegram.Message

所以你可以运行

msg = context.bot.send_message(...)

获取有关已发送 Message - message_idchat 等的所有信息 - 并保存所有(即使用 pickle)或仅需要的值(即使用文本文件、json 等)或保留在某个列表中(如果您一直运行代码),稍后您可以使用它来删除消息。