Discord Python snipe bot仅可查询单条已删消息 如何用deque实现多次查询
功能实现方案
我们用Python标准库的deque实现定长存储最近N条已删消息,修改后的完整代码如下:
import discord from discord.ext import commands from collections import deque # 新增导入deque # 每个服务器对应一个deque,maxlen设置为你想要保存的最近已删消息数量,这里示例存5条 bot.sniped_messages = {} MAX_SNIPE_COUNT = 5 @bot.event async def on_message_delete(message): guild_id = message.guild.id # 如果当前服务器没有存储记录,先初始化deque if guild_id not in bot.sniped_messages: bot.sniped_messages[guild_id] = deque(maxlen=MAX_SNIPE_COUNT) # 把新删除的消息加入deque,超出长度会自动删掉最旧的记录 bot.sniped_messages[guild_id].append( (message.content, message.author, message.channel.name, message.created_at) ) @bot.command() async def snipe(ctx, index: int = 1): # 新增可选参数,默认查最近第1条 try: # index从1开始,deque最新的内容在最右侧,用负索引匹配查询序号 contents, author, channel_name, time = bot.sniped_messages[ctx.guild.id][-index] except: # 无已删消息、查询序号超出存储范围、参数非法都会触发该提示 await ctx.channel.send("er is geen verwijderde bericht Dombo!") return embed = discord.Embed(description=contents, color=discord.Color.red(), timestamp=time) embed.set_author(name=f"{author.name}#{author.discriminator}", icon_url=author.avatar_url) embed.set_footer(text=f"Deleted in : #{channel_name}") await ctx.channel.send(embed=embed) bot.run(TOKEN)
使用说明
- 发送
!snipe默认查询最近1条已删除消息 - 发送
!snipe N(N为正整数)即可查询最近第N条已删除消息,比如!snipe 2可查询倒数第二条删除的消息 - 如需调整保存的已删消息上限,修改
MAX_SNIPE_COUNT的数值即可,超出上限后最旧的记录会被自动丢弃
内容的提问来源于stack exchange,提问作者MDMA
相关产品推荐
相关产品推荐

