如何制作自定义不和谐机器人@某人,某人在命令中@ed?

时间:2021-06-30 10:25:07

标签: python discord.py

当我输入 !best 时,它会出现我的用户名,如果我 @ 其他人使用相同的命令,例如 !best @example 并出现 @nottheexample

if message.content.startswith('!best'):
        await message.channel.send(message.author.mention)

2 个答案:

答案 0 :(得分:0)

要提及用户,您必须事先定义它。您可以按如下方式执行此操作:

user = message.mentions[0]

要提及用户,您可以使用 f-strings 或 format

基于上面的代码,这里有一个例子:

@client.event # Or whatever you use
async def on_message(message):
    user = message.mentions[0]
    if message.content.startswith('!best'):
        await message.channel.send("Hello, {}".format(user.mention))

请注意,该代码仅在您还指定了 user 时才有效。但是,如果您想以不同的方式处理它,您可以添加更多的 ifelse 语句。

答案 1 :(得分:0)

message.author.mention 总是提到消息的作者

你可以通过多种方式解决这个问题

  1. 只需发送后面的任何内容 !best
if message.content.startswith('!best'):
    args = message.content.split('!best ')
    if len(args) > 1:
        await message.channel.send(args[1])
    else:
        await message.channel.send(message.author.mention)
  1. 与数字 1 相同,但添加一些检查 !best 后面的内容是否是真实成员 - 请参阅文档中的 Utility Functions
member = discord.utils.find(lambda m: m.name == args[1], message.guild.members)

member = discord.utils.get(message.guild.members, name=agrs[1])
  1. 使用Commands - 我真的推荐这个
from discord.ext import commands

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

@bot.command()
async def best(ctx, member: discord.Member = None):
    if member is None:
        member = ctx.author
    await ctx.send(member.mention)