【问题标题】:Is there a way to stop a discord.py bot from mentioning roles?有没有办法阻止 discord.py 机器人提及角色?
【发布时间】:2021-04-02 14:45:53
【问题描述】:

我正在使用 discord.py 制作一个不和谐机器人,并且我有一个 say 命令,但你可以让机器人提及任何角色。我已经阻止它提及@everyone 和@here,但我不知道如何阻止它提及角色。这是代码

async def say(ctx, *, message=None):
message = message or "You have to type a message"
message_components = message.split()
if "@everyone" in message_components or "@here" in message_components:
    await ctx.send("You can not ping everyone")
    return

await ctx.message.delete()
await ctx.send(message)

【问题讨论】:

  • 你知道从哪里开始吗?
  • 问题解决了吗?如果是这样,请将任何答案标记为已接受。 @temp84323

标签: python discord discord.py


【解决方案1】:

您可以使用正则表达式。假设有效的用户名/角色只允许使用大写/小写字母数字字符:

import re
user_regex = r"@[a-zA-Z0-9]+"
message = "I'm tagging @you and @you2 in this message!"
match = re.findall(user_regex, message)
if match:
    await ctx.send("You can not ping everyone")
    return

当然,如果您愿意,您可以使用复杂的regex 作为您的用户名。或者您可以根据您的要求找出角色的正则表达式并尝试进行相应的匹配。

【讨论】:

  • 实际上角色提及看起来不像这样@role(只有everyone和here),而是像这样<@&role_id>
【解决方案2】:

你可以使用message.role_mentions

mentions = message.role_mentions

my_role = ctx.guild.get_role(some_id)

if my_role in mentions:
    await ctx.send("You can't mention that role")

如果你有多个角色

my_roles = [] # a list of `discord.Role` objects

mentions = message.role_mentions

if any(role in mentions for role in my_roles):
    await ctx.send("You can't mention that role")

还有一个更好的方法来检查消息内容本身是否提到了@everyone 和@here,您可以使用message.mention_everyone 属性

if message.mention_everyone:
    await ctx.send("You can't mention everyone")

参考

【讨论】:

    猜你喜欢
    • 2021-01-08
    • 2021-03-29
    • 2021-08-10
    • 1970-01-01
    • 2019-04-20
    • 2019-02-02
    • 2020-12-19
    • 2023-02-06
    • 1970-01-01
    相关资源
    最近更新 更多