Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - DM a User Discord Bot

I'm working on a User Discord Bot in Python .If the bot owner types !DM @user then the bot will DM the user that was mentioned by the owner.

@client.event
async def on_message(message):
    if message.content.startswith('!DM'):
        msg = 'This Message is send in DM'
        await client.send_message(message.author, msg)
like image 922
Rubayet Python Avatar asked Aug 03 '26 07:08

Rubayet Python


2 Answers

The easiest way to do this is with the discord.ext.commands extension. Here we use a converter to get the target user, and a keyword-only argument as an optional message to send them:

from discord.ext import commands
import discord

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

@bot.command(pass_context=True)
async def DM(ctx, user: discord.User, *, message=None):
    message = message or "This Message is sent via DM"
    await bot.send_message(user, message)

bot.run("TOKEN")

For the newer 1.0+ versions of discord.py, you should use send instead of send_message

from discord.ext import commands
import discord

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

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

bot.run("TOKEN")
like image 132
Patrick Haugh Avatar answered Aug 07 '26 02:08

Patrick Haugh


Since the big migration to v1.0, send_message no longer exists.
Instead, they've migrated to .send() on each respective endpoint (members, guilds etc).

An example for v1.0 would be:

async def on_message(self, message):
    if message.content == '!verify':
        await message.author.send("Your message goes here")

Which would DM the sender of !verify. Like wise, you could do:

for guild in client.guilds:
    for channel in guild.channels:
        channel.send("Hey yall!")

If you wanted to send a "hi yall" message to all your servers and all the channels that the bot is in.

Since it might not have been entirely clear (judging by a comment), the tricky part might get the users identity handle from the client/session. If you need to send a message to a user that hasn't sent a message, and there for is outside of the on_message event. You will have to either:

  1. Loop through your channels and grab the handle based on some criteria
  2. Store user handles/entities and access them with a internal identifier

But the only way to send to a user, is through the client identity handle which, in on_message resides in message.author, or in a channel that's in guild.channels[index].members[index]. To better understand this, i recommend reading the official docs on how to send a DM?.

like image 27
Torxed Avatar answered Aug 07 '26 01:08

Torxed