【问题标题】:Discord.py Making the bot not interact with DM channelsDiscord.py 使机器人不与 DM 频道交互
【发布时间】:2020-11-16 04:13:20
【问题描述】:

我正在编写一个小型消息记录程序,我希望机器人只记录来自特定公会的消息,为此,我检查了message.guild.id。然而,当在 DM 频道中发送消息时,这会引发问题。我希望机器人完全忽略 Dm 频道,但我运气不佳

代码:

@commands.Cog.listener()
    async def on_message(self, message):
        if message.guild.id == Guild ID HERE:
            print(f"{message.author} said --- {message.clean_content} --- in #{message.channel.name}")
        elif message.channel.type is discord.ChannelType.private:
            pass
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Python38\lib\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "d:\Documents\Bots\DS BOT\cog\Listener.py", line 13, in on_message
    if message.guild.id == Guild ID HERE:
AttributeError: 'NoneType' object has no attribute 'id'
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Python38\lib\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "d:\Documents\Bots\DS BOT\cog\Logger.py", line 12, in on_message
    if message.guild.id == Guild ID HERE:
AttributeError: 'NoneType' object has no attribute 'id'

【问题讨论】:

  • if message.guild is None: return

标签: python discord discord.py discord.py-rewrite nonetype


【解决方案1】:

我解决这个问题的方法很简单。当时我设置了一个自定义前缀系统,该系统将为每个服务器提供机器人在其自己的默认前缀中,以后可以更改。 Dm 的问题是它不是服务器,因此不在导致错误的前缀数据库中。

解决了这个问题:

def get_prefix(bot, message):
    if (message.guild is None):
        return '.'
    else:
        with open('prefixes.json', 'r') as f:
            prefixes = json.load(f)
        return prefixes[str(message.guild.id)]

如果收到的消息或命令不是从服务器发送的,它会简单地使用默认前缀

【讨论】:

    【解决方案2】:

    你可以这样做

    if not message.guild:
       # message is from a server
    else:
       # message is from a dm.
    

    就是这样。无需检查类型。

    【讨论】:

    • 感谢您的回答,但不再需要了
    【解决方案3】:

    在你的 if 声明中传递这个:

    if message.channel.type is discord.ChannelType.private: 
        return
    

    这应该适合你!

    【讨论】:

      【解决方案4】:

      在进行公会检查之前,您必须检查频道是否为私人频道,否则会引发错误。这应该可以完成工作:

      @commands.Cog.listener()
          async def on_message(self, message):
              if isinstance(message.channel, discord.DMChannel):
                  return
              if message.guild.id == Guild ID HERE:
                  print(f"{message.author} said --- {message.clean_content} --- in #
      

      【讨论】:

      • 抱歉,这并没有改变
      • 你确定你做的一切都正确吗?我自己试过了,它按预期工作。
      • 这是我的完整代码hastebin.com/aqedusugar.py
      • 我为我删除了公会检查,但除此之外,它可以正常使用此代码 hastebin.com/ekosoxikud.py
      • 使用if message.guild is None: return 比检查DMChannel 更省钱。
      猜你喜欢
      • 2022-01-23
      • 2021-11-14
      • 2023-03-31
      • 2021-04-30
      • 2019-04-08
      • 2021-06-12
      • 2018-06-16
      • 2020-08-20
      • 2022-01-14
      相关资源
      最近更新 更多