Reputation: 414
I am writing a small message logging program; I want the bot to only log messages from a specific guild, so I check for the message.guild.id
. This, however, raises a problem when there is a message sent in a DM Channel. I want the bot to ignore the DM channel completely, but am not having much luck.
The Code:
@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'
Upvotes: 5
Views: 2924
Reputation: 371
You can just do
if message.guild:
# message is from a server
else:
# message is from a dm.
That's it. There's no need of checking for types.
Upvotes: 4
Reputation: 414
The way I solved this was simple. At the time I set up a custom prefix system that would give every server the bot is in its own default prefix which could be later changed. The thing with Dm's is that it's not a server and therefore was not in the prefix database causing the error.
This was solved with:
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)]
Simply if the message or command that was received was not sent from a server, it would simply use the default prefix
Upvotes: 0
Reputation: 402
Pass this inside your if
statement:
if message.channel.type is discord.ChannelType.private:
return
This should work for you!
Upvotes: -1
Reputation: 229
You have to check if the channel is private before doing your guild check otherwise it will raise an error. This should do the job:
@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 #
Upvotes: 0