在发送python电报bot后删除旧的bot消息

piah890a  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(395)

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

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:基本上,我只想在聊天中的夜间模式消息的一个示例在任何时候。因此,例如,当早晨消息运行时,它将删除前一条夜间消息,这样就不会使聊天与消息混乱。

vsmadaxz

vsmadaxz1#

send_message()的文档显示

Returns: On success, the sent message is returned.

Return type: telegram.Message

这样你就可以跑了

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

要获取有关已发送邮件的所有信息,请执行以下操作- message_id , chat ,等等-并保存所有(即使用 pickle )或仅使用所需的值(即使用文本文件, json ,等等)或保留在一些列表中(如果您一直运行代码),稍后您可以使用它删除消息。

相关问题