-1

Dear stackoverflow community. I want to add a little 'Easter egg' to my discord.py bot. If one gets a DM from a user, he should reply something like "No private messages while at work". Is that somehow possible? Unfortunately, I have no idea how to do this. That's why I can't attach code. Please help me : )

1 Answers1

0

You can have an on_message event, which will fire each time there is any new message which your bot can read. Then you can check if the message is a direct message:

@bot.event # could be client instead of bot for you
async def on_message(message):
    if message.author == bot.user: # Don't reply to itself. Could again be client for you
        return
    if isinstance(message.channel,discord.DMChannel): #If you want this to work in a group channel, you could also check for discord.GroupChannel
        await message.channel.send("No private messages while at work")
    await bot.process_commands(message)

Also don't forget to add bot.process_commands(message) add the end of on_message so your commands still work. (Could again be client instead of bot for you)

References:

LoahL
  • 2,404
  • 1
  • 9
  • 24
  • It works. Not really. I get the message, but the bot keeps sending me this message. He spams me with it. And could you please add `bot.process_commands(message)` to the code. Don't know exactly what you mean by that. Thank you. –  Mar 05 '22 at 14:42
  • 1
    @jcjms I fixed the code. Also you only need `bot.process_commands(message)` if you have commands, since you are overwriting the default on message, see: https://stackoverflow.com/questions/49331096/why-does-on-message-stop-commands-from-working – LoahL Mar 05 '22 at 14:47
  • I think you forgot the 'await' before it. Added it and it works great. Please add this to your answer in case other users look at it. Thank you for your help! : ) –  Mar 05 '22 at 15:02
  • 1
    Yes you're right, changed it. – LoahL Mar 05 '22 at 15:18