我正在编写一个小型消息记录程序;我希望机器人只记录来自特定公会的消息,因此我检查
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:
# message is from a server
else:
# message is from a dm.
就是这样。无需检查类型。
在进行公会检查之前,您必须检查频道是否是私人的,否则会引发错误。这应该可以完成工作:
@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 #
我解决这个问题的方法很简单。当时,我设置了一个自定义前缀系统,该系统将为每个服务器提供机器人的默认前缀,该前缀可以稍后更改。 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)]
如果收到的消息或命令不是从服务器发送的,它只会使用默认前缀
将其传递到您的
if
声明中:
if message.channel.type is discord.ChannelType.private:
return
这应该对你有用!