首页 > 解决方案 > 如何在知道用户 ID 的情况下发送 DM 消息?

问题描述

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

这段代码向触发该函数的消息的作者发送一条消息。我想将其发送给与保存在“用户”变量中的 ID 对应的用户。这是一个更大项目的一部分,ID 是从我保存不同用户 ID 的外部数据库导入的。

标签: pythonpython-3.xdiscorddiscord.py

解决方案


要在知道用户 ID 的情况下向用户发送消息,请执行以下操作:

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

id作为整数,请参阅 API 文档: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


推荐阅读