【问题标题】:Bot responding to channel mentions机器人响应频道提及
【发布时间】:2021-01-21 17:35:44
【问题描述】:

我最近一直在尝试用 python 开发一个不和谐的机器人。我这样做是为了如果一条消息包含某个数字,它会做出反应并发送一条消息。这是cog文件中的代码:

import discord

from discord.ext import commands
    
nice_numbers = ['69', '420']
    
class Auto(commands.Cog):
    def __init__(self, client):
        self.client = client
      
    @commands.Cog.listener()
    async def on_message(self, message):
        
        msg = message.content
    
        if message.author == self.client.user:
             return
    
        if any (word in msg for word in nice_numbers):
             await message.add_reaction('????')
             await message.channel.send(f'lmao nice')
        
    
def setup(client):
    client.add_cog(Auto(client))

问题是,当用户提及某个频道(在本例中为 #general、#super-private-testing 和 #resources)时,机器人也会以相同的消息和反应进行响应。我似乎无法修复它或弄清楚它为什么会发生。我对python还是很陌生,所以有人可以告诉我我做错了什么吗?

【问题讨论】:

    标签: python discord.py discord.py-rewrite


    【解决方案1】:

    基本上发生的情况是,提及在 Discord API 中有一种特殊的语法,它们基本上是一堆数字放在一起。

    例如,当您提及另一个用户时,如下所示:

    你好@User1234!

    discord 消息中的真正语法如下:

    你好!

    在提及频道的情况下,它的工作原理与提及的频道类似:

    #一般

    内部会写成:

    当然,问题在于,在这么大的数字中,找到您的 nice_numbers 可能会出现误报。可能有不同的方法来避免这种情况,例如,您可以检查 message 中是否提到了 channel 或 user 并返回那个案例。

    if message.channel_mentions or message.mentions:
        return
    

    我认为更好的解决方案是改变您检查 nice_numbers 是否在 message.content 范围内的方式。

    如果message.content 还包含类似'我最喜欢的数字是45669',则使用if word in msg 将返回true。要克服这个问题,最好使用regular expressions。

    您可以像this answers 解释的那样声明一个新函数,如果找到您作为参数传递的内容,它将返回<match object>。

    应该是这样的:

    import re
    
    def findCoincidences(w):
        return re.compile(r'\b({0})\b'.format(w)).search
    
    findCoincidences('69')('I like 69')    # -> return <match object>
    findCoincidences('69')('My favourite number is 45669')                   # -> return None
    

    【讨论】:

    • 嗯,我明白了。谢谢您的帮助!现在修复我的代码...
    【解决方案2】:

    在Shunya's answer 上展开,您可以使用message.clean_content 代替message.content:

    以“清理”方式返回内容的属性。这基本上意味着提及被转换成客户展示它的方式。例如 将转换为 #name。

    这也会将@everyone 和@here 提及转换为非提及。

    这将防止您无意中匹配频道、用户、角色等的 ID。当然,如果实际名称包含 nice_number,它仍然会匹配。

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 2020-12-28
      • 2022-01-24
      • 1970-01-01
      • 2020-09-15
      • 2019-11-15
      • 2020-07-18
      • 2020-04-18
      • 2019-12-21
      相关资源
      最近更新 更多