和网页机器人的聊天记录 如何使用TelegramBot删除所有聊天记录?
小智6
首先,如果您想使用机器人删除历史记录,您必须保存消息ID。否则,您可以使用userbot(使用用户账号)来消除历史记录。您可以遍历所有聊天消息并获得他们的ID,然后一次删除100个。
警告:由于Telegram的限制,机器人和BotAPI无法迭代聊天的消息历史记录。因此,您必须使用MTProtoAPI框架,并带有如前所述的用户帐户。
首先,热解图应该图书馆那样做(也可以使用募捐活动),和例子的用户端,那么你可以添加一个处理程序,或使用推进客户端与关键字。然后借助迭代聊天获取所有消息ID,并将他们保存在列表中。最后,使用delete_messagesClient方法删除它们:
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.group & filters.command("delall"))
def func(app, message):
ids = [msg.message_id for msg in app.iter_history(message.chat.id)]
chunk_size = 100
# Splitting the list in chunks of 100 messages ids
ids = [ids[i:i + chunk_size] for i in range(0, len(ids), chunk_size)]
for m_ids in ids:
try:
app.delete_messages(
message.chat.id,
m_ids
)
except Exception as e:
app.send_message(
message.chat.id,
f"An error occurred: {e}"
)
break # Excepts errors given by Telegram, like floodwaits
app.run()
启动userbot后,将其添加到组中,然后发送“/delall”。如果userbot具有删除消息权限,它将起初删除所有消息。
有关热图文档,请参看。
(虽然,您不需要在终端中打印所有消息和网页机器人的聊天记录,以减少VPS过载)
清除控制台的恰当代码是这种的:
import os
def clear():
os.system('cls' if os.name=='nt' else 'clear')
如如何清除解释器控制台中所示?.
PS您可以使用同样的代码,将bot_token=""参数添加到用户端,并删除iter_history部分,如果您有消息ID,则可以使用机器人删除消息。
如果未来您希望接收来自组的消息并打印它们,但您没有收到消息更新和网页机器人的聊天记录,请将机器人添加为组中的管理员或在BotFather中禁用机器人隐私模式。
为了获得更好的热图性能,您必须加装tgcrypto库,并使用(今后热图将默认为async。此代码适用于0.18.x版本)。
这是删除聊天记录的诸多方式之一,我写这个是为了简单起见。