【问题标题】:How to make a bot reply depending on the ping? (text message)如何根据 ping 做出机器人回复? (短信)
【发布时间】:2021-12-11 00:01:09
【问题描述】:

我正在用 Python 制作一个 Discord 机器人,我想添加一个功能,当我使用命令 _throw 并 ping 用户时,机器人将根据用户 ping 回复(最好是普通的短信, 不嵌入)。目前,我有这个代码:

if message.content == "_throw":
    user = message.mentions[0]
    await message.channel.send("You threw a hamster to " + f"{user}" + "!")

但我的机器人根本没有回复它(PyCharm 没有看到任何错误)。

这是我的机器人脚本:

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('_hi'):
        await message.channel.send(f'Hello, {message.author.mention}!')

    if message.content == "_throw":
        user = message.mentions[0]
        await message.channel.send("You threw hamster to " + f"{user}" + "!")

    if message.content.startswith("_userinfo"):
        user = message.mentions[0]
        emb14 = discord.Embed(
            title=f"@{user} info:",
            colour=discord.Colour.dark_blue()
        )
        emb14.set_image(url=user.avatar_url)
        emb14.add_field(name=f"Name", value=f"{user}", inline=True)
        emb14.add_field(name=f"Discord Joined date", value=f"{user.created_at}", inline=False)
        emb14.add_field(name=f"Server Joined date", value=f"{user.joined_at}", inline=False)
        emb14.add_field(name="Profile Picture", value=":arrow_down: :arrow_down: ", inline=False)
        await message.channel.send(embed=emb14)

client.run('TOKEN')

有什么想法吗?

【问题讨论】:

标签: python discord discord.py


【解决方案1】:

我了解到您希望您的机器人回复 _throw @user。在这种情况下,当您检查 message.content == "_throw" 时,它会过滤恰好是 _throw 而不是 @user 部分的消息。

要接受用户提及参数,最简单的方法是使用正则表达式匹配:

import re

# First checks if there are any mentions in the message
# Then uses regex "^_throw\s+<@!?[0-9]{17,22}>$" to match the message content
if message.mentions and re.match(r"^_throw\s+<@!?[0-9]{17,22}>$", message.content):
    user = message.mentions[0]
    await message.channel.send(f"You threw a hamster to {user.mention)!")

这将允许机器人回复_throw @user 并回复You threw a hamster to @user!

【讨论】:

  • 非常感谢!有用!但我有一个问题:\s+&lt;@!?[0-9]{17,22}&gt;$ 是什么?
  • 它是regex,用于匹配模式。我写的意思是:以1个或多个空格开头,后跟“”结尾。它将与 Discord 的用户提及相匹配,例如:“”(这是存储在@user 中的实际消息)。
  • 谢谢!最后一个问题:如何编写代码,当我在_throw 命令中提及自己时,机器人会回复:Woah, you threw hamster to yourself 或You can't throw things at urself lol?
  • @Aaron 您可以添加一个 if 语句来检查 if user == message.author,并在 if 和 else 块中写入您想要的输出。
  • 感谢您的回复!但是当我添加您的代码 (if user == message.author) 时,机器人会同时回复 _throw 命令和 You can't throw things at urself。似乎机器人首先回复You threw hamster to @Me,然后回复You can't throw things at urself。如何让机器人只发送一条消息 - 如果我提到自己,你不能向自己扔东西?
猜你喜欢
  • 2021-12-04
  • 2022-10-13
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
  • 2021-05-02
  • 2020-12-10
  • 2021-01-26
相关资源
最近更新 更多