2

我正在使用 Python 开发 User Discord Bot。如果 bot 所有者键入!DM @user,那么 bot 将 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)
4

5 回答 5

4

最简单的方法是使用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")

对于较新的 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")
于 2018-09-15T13:58:18.313 回答
3

自从大迁移到v1.0,send_message就不复存在了。
相反,他们已经迁移到.send()各个端点(成员、行会等)。

v1.0 的一个示例是:

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

哪个会 DM 的发件人!verify。明智地,您可以这样做:

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

如果您想向您的所有服务器和机器人所在的所有频道发送“hi yall”消息。

由于可能并不完全清楚(根据评论判断),因此棘手的部分可能会从客户端/会话中获取用户身份句柄。如果您需要向尚未发送消息的用户发送消息,并且在on_message事件之外。您将不得不:

  1. 循环浏览您的频道并根据某些标准抓住手柄
  2. 存储用户句柄/实体并使用内部标识符访问它们

但是发送给用户的唯一方法是通过客户端身份句柄,该句柄on_message位于 中message.author,或者位于 中的通道中guild.channels[index].members[index]。为了更好地理解这一点,我建议阅读有关如何发送 DM 的官方文档?.

于 2020-06-22T16:17:47.453 回答
0

我注意到我放入代码行的每个代码都不能完全正常工作,所以我在其中添加了自己的代码,并且成功了!将此添加到您的机器人代码时,不要忘记在此处显示机器人名称的位置添加机器人名称。它只会 DM 发送它的人,但您可以更改它每天所说的内容,让使用该命令的每个人都感到惊讶。它每次都对我有用。

@client.command()
async def botdm(ctx):
  await ctx.message.author.send('hi my name is *bot name here* and i am a bot!')
于 2021-07-04T11:10:20.923 回答
0
@bot.command()
async def dm(ctx, user: discord.User, *, message=None):
    if message == None:
      message = "Hi!"
    embed = make_embed(title=f"Sent by {user}", desc=message)
    await user.send(embed=embed)
    await ctx.send("Message sent!")```
于 2021-01-25T00:12:44.330 回答
0

我过去使用过这个命令,我认为它最适合我:

@bot.command(pass_context=True)
async def mall(ctx, *, message):
  await ctx.message.delete()
  for user in ctx.guild.members:
    try:
      await user.send(message)
      print(f"Successfully DMed users!")
    except:
      print(f"Unsuccessfully DMed users, try again later.")
于 2020-10-07T15:17:20.383 回答