如何使用 Telegram Bot 删除所有聊天记录?

How can I delete all chat history using Telegram Bot?

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

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

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

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

def deleteChat(message):
    #delete chat code

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

警告:由于 Telegram 限制,机器人和 BotAPI 无法重复聊天的消息历史记录。因此,您应该使用 MTProto API 框架,并如前所述使用用户帐户。

首先,pyrogram library is needed for doing this (you could also use 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”。如果userbot有删除消息权限,它会开始删除所有消息。

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


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

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

import os

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

How to clear the interpreter console?.

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

如果将来您想要接收来自群组的消息并打印它们,但您没有收到消息更新,请将 bot 添加为群组中的管理员或禁用 bot privacy BotFather.

模式

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