电报漫游器无法正确删除在群聊中发送的消息

时间:2020-11-11 00:49:12

标签: python python-telegram-bot

我正在为Telegram机器人编写Python代码,该机器人会在24小时后删除聊天中的消息。目前,我是通过将发送到聊天室的每条消息存储在一个列表中来进行此操作的,然后在24小时标记时,该消息将被第二个功能删除。我的问题是,每到24小时(或调用命令[/ purge]来过早删除聊天记录),都不会删除所有消息。我花了很多时间思考它,但是却一无所获。我确认应该删除的每条消息都在列表的开头,所以我不确定还有什么地方会出错。

我正在使用python-telegram-bot API。这是完整的代码:

import logging
import schedule
from threading import Thread
from time import sleep

import telegram.bot as tb
from telegram import Update
from telegram.ext import (Updater,
                            CommandHandler,
                            CallbackContext,
                            MessageHandler,
                            Filters)

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

logger = logging.getLogger(__name__)

# Define API Token
TOKEN = "MY_TOKEN"

def scheduleChecker():
    while True:
        schedule.run_pending()
        sleep(.25)

# Function to know if the bot is working
def start(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('SnapBot has started successfully')

# Initialize list to hold all messages.  Cannot be in the method otherwise
#   the list would be reset every time the function is called (i.e. every
#   time there is a message sent to the chat)
messages = []
def storeChat(update: Update, context: CallbackContext) -> None:
    messages.append(update.message.message_id)
    print(str(update.message.from_user.first_name) + ': ' + update.message.text)

# cleanChat() iterates through each message in the list of messages sent that day and
#   deletes them, then deletes them in the chat with a bot, then deletes the message
#   from list as well.
def cleanChat(update: Update, context: CallbackContext) -> None:
    bot = tb.Bot(TOKEN)
    for message in messages:
        #print(messages)
        bot.delete_message(chat_id = update.message.chat_id, message_id = message)
        del messages[messages.index(message)]

# TODO: Fix bug where purge does not delete all messages from the day
#       Thread message timers so only one message gets deleted at its
#         24 hour mark
def main():
    # Initialize Updater
    updater = Updater(TOKEN, use_context=True)

    # Every 24 hours, clean the chat.  The thread is necessary so that
    #   jobs can happen simultaneously
    schedule.every(24).hours.do(cleanChat)
    Thread(target = scheduleChecker).start()

    # Get the dispatcher to register handlers
    dispatcher = updater.dispatcher

    # Listen for whenever a message is sent to the chat
    storeChatHandler = MessageHandler(Filters.text & (~Filters.command), storeChat)

    dispatcher.add_handler(storeChatHandler)
    dispatcher.add_handler(CommandHandler("start", start))
    dispatcher.add_handler(CommandHandler("purge", cleanChat))

    # Start the bot
    updater.start_polling()

    # Block until you press Ctrl-C or the process receives SIGINT, SIGTERM or
    # SIGABRT. This should be used most of the time, since start_polling() is
    # non-blocking and will stop the bot gracefully.
    updater.idle()

if __name__ == '__main__':
    main()

顺便说一句,我还有第二个问题,我不确定该如何解决。目前,漫游器启动后24小时会在设定的时间一次删除所有消息。每当对话即将进行时,这都会造成问题,因为消息即将被删除。我该如何做,以便僵尸程序在邮件本身发送后24小时删除邮件?

0 个答案:

没有答案
相关问题