Discord.py on_message() but only for private messages

Viewed 8413

So, I'm working on a discord bot. And am using the on_message() event, which works both on private messages and on servers. I want this to only work in private messages and am unsure of how to go about this. If anyone can help me, that would be great.

import os
import discord
from discord.ext import commands


TOKEN = ''
quotedUsers = []

client = commands.Bot(command_prefix = '/')

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    await client.change_presence(activity=discord.Game(name='with myself.'))
    
@client.event
async def on_message(message):
    await message.author.send("Recieved: " + message.content)

@client.command()
async def search(ctx, *, question):
    await ctx.author.send("Searching: " + question)
    

client.run(TOKEN)
3 Answers

A message guild also doesn't exist in a group DM, so you have to check if the channel you messaging in is a DM. You can use the dm_channel attribute of a user:

@client.event
async def on_message(message):
    if message.channel.id == message.author.dm_channel.id: # dm only
        # do stuff here #
    elif not message.guild: # group dm only
        # do stuff here #
    else: # server text channel
        # do stuff here #

When a DM is received, it won't have a guild, so you'll be able to use that logic like so:

@client.event
async def on_message(message):
    # you'll need this because you're also using cmd decorators
    await client.process_commands(message)
    if not message.guild:
        await message.author.send(f"Received: {message.content}")

References:

Hi i had found though playing around that when discord sends a message to the bot as a dm in python this will be done using a discord.channel.DMChanneland if the message is done in the text channel discord.channel.TextChannel.

i have proved this by putting in a type fuct over the object to see what happens in the Message listener.

isinstance(message.channel, DMChannel)
Related