如何批量删除14天前的Discord消息?py-cord速率限制问题求助
解决Discord批量删除旧消息的速率限制问题
问题分析
你遇到的是Discord API的速率限制问题:DELETE /channels/{channel_id}/messages/{message_id} 端点的限制是每个频道每秒最多1次请求。你的代码没有添加任何请求间隔,连续发送删除请求,很快就会耗尽该端点的请求配额,触发速率限制,且重试时间会随着重复触发持续增加。
另外,代码存在一个小问题:readlines()读取的每行ID会包含换行符,可能导致fetch_message失败,需要先清理ID格式。
解决方案
1. 添加请求间隔,避免触发速率限制
在每次删除操作后添加1秒延迟,刚好匹配API的速率限制要求。同时清理读取到的消息ID,去掉多余的换行符和空白字符。
2. 捕获速率限制异常,自动重试
discord.py会抛出discord.errors.RateLimited异常,我们可以捕获它并按照API返回的重试时间等待后继续执行,避免程序中断。
修改后的代码如下:
import asyncio from discord.errors import RateLimited count = 0 # 读取并清理消息ID,过滤空白行 with open("ids.txt", "r") as file: message_ids = [id.strip() for id in file if id.strip()] channel = await bot.fetch_channel(Channel_ID_OF_SERVER) for msg_id in message_ids: try: msg = await channel.fetch_message(msg_id) await msg.delete() count += 1 print(f"Deleted {count} messages") # 每秒最多删1条,添加延迟避免触发限制 await asyncio.sleep(1) except RateLimited as e: retry_after = e.retry_after print(f"触发速率限制,等待{retry_after:.2f}秒后重试") await asyncio.sleep(retry_after) # 重试当前消息删除 try: msg = await channel.fetch_message(msg_id) await msg.delete() count += 1 print(f"Deleted {count} messages") await asyncio.sleep(1) except Exception as retry_e: print(f"重试删除失败: {retry_e}") continue except Exception as e: print(f"处理消息失败: {e}") continue
额外说明
- Discord的批量删除接口(
bulk_delete)仅支持删除14天以内的消息,所以你只能用单个删除的方式处理2年前的消息,这是唯一可行的途径。 - 即使添加了延迟,删除大量消息会花费很长时间,这是正常的,必须严格遵守API的速率限制规则,否则会导致更长时间的封禁或重试惩罚。
内容的提问来源于stack exchange,提问作者Shahrukh Abrar
相关产品推荐
相关产品推荐

