尝试让机器人在使用命令时记录一些内容discord.py

2024-02-12

我试图让我的机器人在使用时记录一个事件,也称为 mod 命令。由于我的机器人位于多个服务器中,因此我有一个命令,人们可以在其中设置他们希望机器人记录事件的日志通道。到目前为止,我已经

@commands.command()
    @commands.has_permissions(manage_messages=True)
    async def setlogchannel(self, ctx, channel: discord.TextChannel):
      with open('logchannel.json', 'r', encoding='utf-8') as fp:
        log_channel = json.load(fp)

      try:
        log_channel[str(ctx.guild.id)] = channel.id
      except KeyError:
        new = {str(ctx.guild.id): channel.id}
        log_channel.update(new)

      await ctx.send(f"Log Channel set to: `{channel}`!")

      with open('logchannel.json', 'w', encoding='utf-8') as fpp:
        json.dump(log_channel, fpp, indent=2)

这是一个命令,人们可以在其中设置日志通道,并且将其放入 .json 文件时效果很好。但举例来说,我希望机器人在有人使用时记录>clear命令。到目前为止我已经,

@commands.command()
    @commands.has_permissions(manage_messages=True)
    async def clear(self, ctx, amount=5):

      def log_channel(bot, channel):
        with open('logchannel.json', 'r') as fp:
          log_channel = json.load(fp)
          return log_channel[str(ctx.guild.id)]

      await ctx.channel.purge(limit=amount+1)
      embed=discord.Embed(title="Messages Cleared", description=f'{amount} messages were deleted!', color=0x00FFFF)
      author = ctx.message.author
      pfp = author.avatar_url
      embed.set_author(name=f"{ctx.author}", icon_url=pfp)
      await ctx.send(embed=embed)
      await asyncio.sleep(3)
      await ctx.channel.purge(limit=1)
      log_channel = discord.utils.get(ctx.guild.text_channels, id=log_channel[str(ctx.guild.id)])
      await log_channel.send(f"**{ctx.author.name}** cleared **{amount}** messages in the channel, **{ctx.channel.name}**!")

我做了一些更改,看看它们是否有效,但机器人不会将消息发送到指定的日志通道。如何获取要发送的日志消息?谢谢。


您请求日志通道的方式似乎是错误的。

你实际上必须打开你的JSON再次归档并查找log_channel[str(ctx.guild.id).

下面是一个关于它如何工作的示例:

    @commands.command()
    async def clear(self, ctx, amount=5):
        # Do what you want to do
        embed = discord.Embed(title="Test",
        description=f"{ctx.message.author} cleared {amount} messages".) # Your embed/msg
        with open('logchannel.json', 'r', encoding='utf-8') as fp:
            log_channel = json.load(fp)

        try:
            if log_channel:
                log_c = ctx.guild.get_channel(log_channel[str(ctx.guild.id)])
                await log_c.send(embed=embed)
            else:
                await ctx.send(embed=embed)
        except (AttributeError, KeyError):
            await ctx.send(embed=embed)
  • 我还内置了一些except如果未找到该通道,则声明。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尝试让机器人在使用命令时记录一些内容discord.py 的相关文章

随机推荐