【问题标题】:Send message to multiple tagged user向多个标记用户发送消息
【发布时间】:2025-11-24 12:55:01
【问题描述】:

如何通过标记向多个用户发送消息。

@bot.command(pass_context=True)
async def ping(ctx, member: discord.Member):
        await bot.send_message(member, "Pong...".format(ctx.message))

所以上面的代码在标记单个用户?ping @user1 时可以正常工作,但是当我们标记多个用户?ping @user1 @user2 时如何使它工作。

所以是否可以在频道中而不是在脚本中提供自定义消息。例如:当我们输入?ping @user1 @user2时,机器人应该要求发送一条消息,当我们添加一条消息时,它会将这条消息转发给标记的用户。

【问题讨论】:

    标签: python python-3.x discord discord.py


    【解决方案1】:

    我们可以像在任何其他 python 函数中一样为命令获取可变数量的参数。如果我们将消息放在首位,并要求将其用引号括起来,那么我们可以在一个命令中完成所有这些操作。

    @bot.command(pass_context=True)
    async def ping(ctx, message, *members: discord.Member):
        for member in members:
            await bot.send_message(member, message)
    

    用法:

    !ping "This is a message" @Demotry @PatrickHaugh
    

    编辑:

    如果您想避免强迫用户将他们的message 封装在引号中,您可以使用Clint.wait_for_message

    @bot.command(pass_context=True)
    async def ping(ctx, *members: discord.Member):
        await bot.say("What message would you like to send?")
        message = await bot.wait_for_message(channel=ctx.message.channel, author=ctx.message.author)
        for member in members:
            await bot.send_message(member, message.content)
    

    【讨论】:

    • 得到错误in wrapped raise CommandInvokeError(e) from e discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: '<class 'discord.ext.commands.bot.Bot'>' object has no attribute 'wait_from_message' 我确实将await bot.wait_from_message 更改为await bot.wait_for_message 但机器人发送消息,如
    • 这很好,您可能想发送message.content 代替
    【解决方案2】:

    message 类包含一个 mentions 属性,您可以对其进行迭代。

    @bot.command(pass_context=True)
    async def ping(ctx):
        for member in ctx.message.mentions:
            await bot.send_message(member, "Pong...".format(ctx.message))
    

    【讨论】:

    • 编辑:你错过了@bot.command 现在它告诉discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Message' object has no attribute 'members'
    • 抱歉,应该使用mentions 而不是members。现已修复
    • 是的工作.. 我的第二个问题是可能的吗?例如:当我们输入 ?ping @.user1 @.user2 bot 应该要求发送一条消息,当我们添加一条消息时,它会将这条消息转发给标记的用户。
    最近更新 更多