Python - DM 用户 Discord 机器人

Rub*_*hon 3 python bots dm discord discord.py

我正在 Python 中开发一个 User Discord 机器人。如果机器人所有者键入!DM @user,那么机器人将通过 DM 发送所有者提到的用户。

@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)
Run Code Online (Sandbox Code Playgroud)

Pat*_*ugh 5

最简单的方法是使用扩展discord.ext.commands。这里我们使用转换器来获取目标用户,并使用仅关键字参数作为可选消息来发送给他们:

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")
Run Code Online (Sandbox Code Playgroud)

对于较新的 1.0+ 版本的discord.py,您应该使用send而不是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")
Run Code Online (Sandbox Code Playgroud)