Jacopown
Jacopown

Reputation: 11

How to send a DM message knowing the user ID?

import discord
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv("token.env")
token = os.getenv("TOKEN")
bot = commands.Bot(command_prefix="!")

@bot.event
async def on_message(message):
    user="An_ID"
    if message.author == bot.user :
        return
    if message.content.startswith("!"):
        await bot.process_commands(message)
        return
    else :
      embed = discord.Embed(title="message",color=0x4a1775)
      await message.author.send(embed=embed)
      return

This piece of code sends a message to the author of the message that has triggered the function. I want instead to send it to the user that corresponds at the ID saved in the "user" variable. This is part of a bigger project and the ID is imported from an external database where i've saved different user IDs.

Upvotes: 0

Views: 545

Answers (1)

damaredayo
damaredayo

Reputation: 1077

To message a user if you know their ID, do the following:

user_object = bot.get_user(id)
await user_object.send("Message")

with id being an integer see API docs at:
https://discordpy.readthedocs.io/en/latest/api.html?highlight=get_user#discord.Client.get_user
https://discordpy.readthedocs.io/en/latest/api.html?highlight=get_user#discord.User.send

Upvotes: 1

Related Questions