【问题标题】:discord py - message.mentions "else" makes nothingdiscord py - message.mentions "else" 什么都不做
【发布时间】:2021-04-24 07:29:35
【问题描述】:

我想获取消息中提到的用户并向他发送私人消息。这工作没有问题,但现在我想为案例添加一条消息,即提到的成员不在同一台服务器上。

我搜索了很多,现在尝试了 3 个多小时才找到解决方案。

问题展示: https://youtu.be/PYZMVXYtxpE

这是我的代码:

@bot.event
async def on_message(message):
 if len(message.mentions) == 1:
   membe1 = message.mentions[0].id
   membe2 = bot.get_user(membe1)
   guild = bot.get_guild(message.author.guild.id)
   if guild.get_member(membe1) is not None:
      await membe2.send(content=f"you was mentioned in the server chat")
   else:
      embed2 = discord.Embed(title=f"» :warning: | PING not possible", description=f"not possible")
      await message.channel.send(content=f"{message.author.mention}", embed=embed)
      await message.delete()
      return

第一部分工作没有问题,但在“else”部分,机器人什么也没做。他仍然在聊天中发布带有“无效” ping 的消息并且忽略它。我能做些什么来解决这个问题?

【问题讨论】:

  • 你能发送一个机器人输出的截图吗?
  • 没有错误,什么都没有。

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


【解决方案1】:

您尝试执行的操作存在设计错误。 在 Discord 中,如果 user 不在同一台服务器上,则您无法提及,因此您正在检查的内容将永远无法正常工作,目前您的代码很漂亮大量检查提到的用户是否存在,除非他在执行命令的同时离开公会,否则总是会发生这种情况。

例如,要使您的命令正常工作,您想提及您服务器中的用户 user123,您可以执行以下操作:

@user123 废话

这很有效,因为 Discord 内部缓存可以在您的服务器中找到 user123 并且它被提及,这意味着点击“@user123”将向我们显示一个目标他的头像,他的角色等等。

但是,如果您尝试对 无效用户 执行相同操作,假设 notuser321

@notuser321 废话

这里没有提及,例如您知道 notuser321 是谁,但他与机器人在同一台服务器上。 Discord 无法从缓存中检索此用户,它不被视为提及,只是一个字符串,因此不是代码的一部分将被触发,因为len(message.mentions) 将是0

您可以尝试使用regular expressions 来尝试在message.content 中进行标记。一个例子是这样的:

import re

message = "I love @user1 and @user2"
mention_attempt = re.findall(r'[@]\S*', message)   # ['@user1', '@user2']

【讨论】:

  • 我得到了错误:TypeError: 'in <string>' requires string as left operand, not list for if mention_attempt in message.content:
  • re.findall() 返回一个包含所有结果的列表,如果找到,要么仅检查 mention_attempt[0],要么遍历其元素以向提到的每个用户发送消息。
  • 您应该尝试调试您的代码,看看为什么会这样。这基本上意味着它不会在您的消息中识别任何语法,如 @username。您必须将message.content 传递给re.findall() 函数,而不是message 对象...
猜你喜欢
  • 2020-12-16
  • 2022-01-08
  • 2014-10-08
  • 2014-06-20
  • 1970-01-01
  • 2019-03-08
  • 2016-12-24
  • 2017-04-18
  • 2011-08-03
相关资源
最近更新 更多