Skip to content
Advertisement

How to make my bot forward DMs sent to it to a channel

So, I’ve got a bot that can send a user a DM via a very simple command. All I do is “!DM @user message” and it sends them the message. However, people sometimes try responding to the bot in DMs with their questions, but the bot does nothing with that, and I cannot see their replies. Would there be a way for me to make it so that if a user sends a DM to the bot, it will forward their message to a certain channel in my server (Channel ID: 756830076544483339).

If possible, please can someone tell me what code I would have to use to make it forward on all DMs sent to it to my channel 756830076544483339.

Here is my current code:

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='!')


@bot.event
async def on_ready():
    activity = discord.Game(name="DM's being sent", type=3)
    await bot.change_presence(
        activity=discord.Activity(
            type=discord.ActivityType.watching,
            name="Pokemon Go Discord Server!"))
    print("Bot is ready!")


@bot.command()
async def DM(ctx, user: discord.User, *, message=None):
    message = message or "This Message is sent via DM"
    await user.send(message)
    await ctx.send('DM Sent Succesfully.')

Thank you!

Note: I’m still quite new to discord.py coding, so please could you actually write out the code I would need to add to my script, rather than just telling me bits of it, as I often get confused about that. Thank you!

Advertisement

Answer

What you’re looking for is the on_message event

@bot.event
async def on_message(message):
    # Checking if its a dm channel
    if isinstance(message.channel, discord.DMChannel):
        # Getting the channel
        channel = bot.get_channel(some_id)
        await channel.send(f"{message.author} sent:n```{message.content}```")
    # Processing the message so commands will work
    await bot.process_commands(message)

Reference

Advertisement