1
votes

trying to make my bot reply to DMs with "this is a dm" but no luck, here's my code:

@client.event
async def on_message(message):
    if message.guild == null:
        await message.channel.send('this is a dm')
    else:
        pass

I've also tried using this:

@client.event
async def on_message(message):
    if isinstance(message.channel, discord.channel.DMChannel):
        await ctx.send('This is a DM')

On that last one, I get an error due to context (ctx)

3

3 Answers

2
votes

The first code you sent uses null which isn’t event a thing in python. The second one is a bit unnecessary, use this instead:

@client.event
async def on_message(message):
    if not message.guild:
        await message.channel.send('this is a dm')
1
votes

I know this is quite a late response, but I really need to point this out.

I would recommend using this code, as it otherwise might keep responding to its own messages, and you would get a loop of responses. This code also catches the error if the user has private DM's disabled.

@client.event()
async def on_message(message):
    if message.author == client.user:
        return
    if not message.guild:
        try:
            await message.channel.send("This is a DM.")
        except discord.errors.Forbidden:
            pass
    else:
        pass
0
votes

Try this:

import discord

client = discord.Client()

@client.event
async def on_message(message):
    if isinstance(message.channel, discord.channel.DMChannel) and message.author != client.user:
        await message.channel.send('This is a DM')

client.run("KEY")