【问题标题】:How do I make a custom discord bot @ someone that a person @ed in the command?如何在命令中创建一个自定义不和谐机器人@某人@某人?
【发布时间】:2021-09-12 12:11:38
【问题描述】:

当我输入 !best 时,它会显示我的用户名,如果我使用 !best @example 之类的相同命令 @ 其他人并输入 @nottheexample 也会这样做

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

【问题讨论】:

标签: python discord.py


【解决方案1】:

要提及用户,您必须事先定义它。你可以这样做:

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 语句。

【讨论】:

  • 不工作它会出现错误:Ignoring exception in on_message Traceback (most recent call last): File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "main.py", line 60, in on_message user = message.mentions[0] IndexError: list index out of range
  • @CameronButcher "请注意,代码仅在您同时指定用户时才有效"。你也不能有多个on_message事件并且必须注意缩进
【解决方案2】:

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)

【讨论】:

  • 第一个有效但我需要它做的是当我说 >example0: !best @example1> 我想让它说> @example1
  • 我不明白,它是否有效? ?
  • 好的,您能否编辑您的问题,对输出的外观进行更多解释(也许添加一些屏幕截图)? :D
猜你喜欢
  • 2020-12-30
  • 1970-01-01
  • 2020-04-29
  • 2020-03-26
  • 2021-03-30
  • 2021-12-05
  • 2018-07-21
  • 2021-10-14
  • 2021-06-30
相关资源
最近更新 更多