如何在“on_message”中提及某人

Posted

技术标签:

【中文标题】如何在“on_message”中提及某人【英文标题】:How to mention someone in "on_message" 【发布时间】:2021-01-19 12:09:18 【问题描述】:

所以我想让机器人在说出 n 字的作者上提及作者。我尝试使用 message.mention 但显然它不存在所以我如何提及使用 on_message 事件的人? 代码如下:

@commands.Cog.listener()
async def on_message(self, message):
  if "ni**a" in message.content:
    await message.channel.send(f"<:sniper:711509974588719216> R6 BRUH message.author")
  if 'ni**er' in message.content:
    await message.channel.send(f"<:sniper:711509974588719216> R6 BRUH message.author")
  if 'Ni**a' in message.content:
    await message.channel.send(f"<:sniper:711509974588719216> R6 BRUH message.author")
  if 'Ni**er' in message.content:
    await message.channel.send(f"<:sniper:711509974588719216> R6 BRUH message.author")

【问题讨论】:

在检查单词是否在内容中之前,您可能应该规范化您的字符串。只需将其他字母大写即可轻松绕过您的机器人。请尝试仅比较小写版本,方法是先将内容转换为小写 message.content.lower() 【参考方案1】:

如果您想提及消息的作者,可以使用message.author.mention。而且你不必做 4 个 if 语句,1 个就足够了。您可以执行以下操作:

@commands.Cog.listener()
async def on_message(self, message):
  content = message.content.lower()
  if "ni**a" in content or "ni**er" in content:
    await message.channel.send(f"<:sniper:711509974588719216> R6 BRUH message.author.mention")

【讨论】:

【参考方案2】:

成员对象

要提及某人,您需要将member object 与该人关联。

成员对象包含一个属性“mention”,可用于检索用于提及该成员的字符串。


那么如何应用呢?

因为message.author 是一个成员对象。我们可以使用message.author.mention 来获取提及该成员的字符串。产生如下代码:

@commands.Cog.listener()
async def on_message(self, message):
  if "ni**a" in message.content:
    await message.channel.send(f"<:sniper:711509974588719216> R6 BRUH message.author.mention")
  if 'ni**er' in message.content:
    await message.channel.send(f"<:sniper:711509974588719216> R6 BRUH message.author.mention")
  if 'Ni**a' in message.content:
    await message.channel.send(f"<:sniper:711509974588719216> R6 BRUH message.author.mention")
  if 'Ni**er' in message.content:
    await message.channel.send(f"<:sniper:711509974588719216> R6 BRUH message.author.mention")

简化

正如一些人之前提到的,我们可以将您的代码简化为:

@commands.Cog.listener()
async def on_message(self, message):
  content = message.content.lower()
  if "ni**a" in content or "ni**er" in content:
    await message.channel.send(f"<:sniper:711509974588719216> R6 BRUH message.author.mention")

参考资料:

Member object

Member.mention

Message object

Message.content

【讨论】:

【参考方案3】:

如果您想提及某个用户,您总是必须这样做:

await message.channel.send(f"blablabliblu------> message.authormention")#you want to mention the message author
#mention a other spezific user
user = client/bot.get_user(user_id)#get the user
await message.channel.sedn(f"hellooooooo---> user.mention)")
#so you alwas need <someuser.mention>

【讨论】:

以上是关于如何在“on_message”中提及某人的主要内容,如果未能解决你的问题,请参考以下文章

如何让我的 discord.py 机器人提及我的消息中提到的某人?

Discord.py:有没有办法使用 on_message() 函数获取命令的参数?

如何让我的 Discord Bot 提及我提及的人?

Tornado websocket 客户端:如何异步 on_message? (从未等待协程)

如何让 Discord 机器人在 on_message 中使用自定义表情符号响应消息

有没有办法在不提及/ping他们的情况下向某人添加角色? [discord.js]