【问题标题】:How can I delete all chat history using Telegram Bot?如何使用 Telegram Bot 删除所有聊天记录?
【发布时间】:2022-03-25 23:04:45
【问题描述】:

是否可以删除我与机器人聊天的所有聊天记录(消息)。

所以控制台版本是这样的:

import os
os.sys("clear") - if Linux
os.sys("cls") - if Windows

我只想使用机器人删除聊天中的所有消息。

def deleteChat(message):
    #delete chat code

【问题讨论】:

    标签: python python-3.x telegram telegram-bot python-telegram-bot


    【解决方案1】:

    首先,如果您想删除机器人的历史记录,您应该保存消息 ID。 否则,您可以使用用户机器人(使用用户帐户)来清除它。 您可以迭代所有聊天消息并获取它们的 ID,并在每次迭代中以 100 条消息为单位删除它们。

    警告:由于 Telegram 的限制,无法使用机器人和 BotAPI 迭代聊天的消息历史记录。因此,您应该使用 MTProto API 框架,以及前面所说的用户帐户。

    首先,需要 pyrogram 库来执行此操作(您也可以使用 telethon),并实例化一个客户端,然后您可以添加一个处理程序或使用 with 关键字启动客户端.然后通过迭代聊天获取所有消息 id,并将它们保存在列表中。最后,使用 delete_messages 客户端方法删除它们:

    import time, asyncio
    from pyrogram import Client, filters
        
        app = Client(
            "filename", # Will create a file named filename.session which will contain userbot "cache"
            # You could also change "filename" to ":memory:" for better performance as it will write userbot session in ram
            api_id=0, # You can get api_hash and api_id by creating an app on
            api_hash="", # my.telegram.org/apps (needed if you use MTProto instead of BotAPI)
        )
    
    
    @app.on_message(filters.me & filters.command("clearchat") & ~filters.private)
    async def clearchat(app_, msg):
        start = time.time()
    
        async for x in app_.iter_history(msg.chat.id, limit=1, reverse=True):
              first = x.message_id
    
        chunk = 98
    
        ids = range(first, msg.message_id)
    
        for _ in (ids[i:i+chunk] for i in range(0, len(ids), chunk)):
            try:
                asyncio.create_task(app_.delete_messages(msg.chat.id, _))
            except:
                pass
        
        end = time.time() - start
    
        vel = len(ids) / end
        await msg.edit_text(f"{len(ids)} messages were successfully deleted in {end-start}s.\n{round(vel, 2)}mex/s")
    
    
    app.run()
    

    启动用户机器人后,将其添加到组中,然后发送“/clearchat”。如果用户机器人有删除消息权限,它将开始删除所有消息。

    有关热解图文档,请参阅https://docs.pyrogram.org


    (但是,您不应在终端中打印所有消息,以免服务器过载)

    清除控制台的正确代码是这样的:

    import os
    
    def clear():
        os.system("cls" if os.name == "nt" else "clear")
    

    如在How to clear the interpreter console? 中看到的那样。

    附: 您可以使用相同的代码,将 bot_token="" 参数添加到客户端,并删除 iter_history 部分,如果您有消息 ID,则使用机器人删除消息。

    如果将来您希望接收来自群组的消息并打印它们,但您没有收到消息更新,请将机器人添加为群组中的管理员或禁用机器人隐私模式BotFather.

    为了获得更好的热解图性能,您应该安装tgcrypto 库。

    【讨论】:

      猜你喜欢
      • 2016-12-05
      • 2016-05-17
      • 1970-01-01
      • 2017-05-09
      • 2021-04-01
      • 2019-10-01
      • 2020-04-14
      • 1970-01-01
      • 2021-04-03
      相关资源
      最近更新 更多