Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discord.py Making the bot not interact with DM channels

I am writing a small message logging program, I want the bot to only log messages from a specific Guild and for that, 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 I did not have much luck in that

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'
like image 782
Dan A Avatar asked Oct 15 '22 01:10

Dan A


1 Answers

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.

like image 167
Sairam Avatar answered Dec 31 '22 14:12

Sairam