首先,如果您想删除机器人的历史记录,您应该保存消息 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 库。