How do you have a Discord bot read DMs sent to it? (discord.py)

Value_Error picture Value_Error · Jun 20, 2018 · Viewed 16.7k times · Source

I've come up with a way to DM people, but I want to know what they say back to the bot through DMs, as if the bot "reads" the DM, and then forwards it to some channel in a discord server of mine, or, even better, DM it to me.

Here is my starting code:

if message.content.startswith("!dm"):
    if message.author.id == "[YOUR ID HERE]":
        memberID = "ID OF RECIPIENT"
        server = message.server
        person = discord.Server.get_member(server, memberID)
        await client.delete_message(message)
        await client.send_message(destination = person, content = "WHAT I'D LIKE TO SAY TO THEM")

I do it a different way contrary to how people do it with defining functions, I use a more basic way of making commands.

Any help is appreciated!

Answer

Patrick Haugh picture Patrick Haugh · Jun 20, 2018

Here's a quick example. I've moved your existing command into an actual Command object, so the forwarding logic is the only thing in on_message

from discord.ext import commands

bot = commands.bot('!')

# I've moved the command out of on_message so it doesn't get cluttered
@bot.event
async def on_message(message):
    channel = bot.get_channel('458778457539870742')
    if message.server is None and message.author != bot.user:
        await bot.send_message(channel, message.content)
    await bot.process_commands(message)

# This always sends the same message to the same person.  Is that what you want?
@bot.command(pass_context=True)
@commands.is_owner()  # The account that owns the bot
async def dm(ctx):
    memberID = "ID OF RECIPIENT"
    person = await bot.get_user_info(memberID)
    await bot.send_message(person, "WHAT I'D LIKE TO SAY TO THEM")
    await bot.delete_message(ctx.message)