Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

修复了消息文本中出现和指令相同的字符串会错误激活指令的问题 #164

Open
wants to merge 6 commits into
base: master
Choose a base branch
from

Conversation

CheckeyZerone
Copy link
Contributor

@CheckeyZerone CheckeyZerone commented Dec 12, 2023

修改前的代码,如果在文本中出现了和指令相同的字符串,会直接执行指令,示例如下:

import botpy
from botpy import logger
from botpy.message import GroupMessage
from botpy.ext.command_util import Commands

@Commands("cmd_01")
async def cmd_01(api: BotAPI, message: GroupMessage, params=None):
    await message.reply(content=f"/cmd_01 {params}")
    return True

@Commands("cmd_02")
async def cmd_02(api: BotAPI, message: GroupMessage, params=None):
    await message.reply(content=f"/cmd_02 {params}")
    return True

class MyClient(botpy.Client):
    async def on_group_at_message_create(self, message: GroupMessage):
        """
        在群聊中机器人被@的事件处理器
        :param message: @机器人的聊天信息
        :return: None
        """
        logger.info(message)
        command = get_command(message.content)
        handlers = [
            cmd_01,
            cmd_02,
        ]
        for handler in handlers:
            if await handler(api=self.api, message=message):
                return
        await message.reply(content="收到!")

if __name__ == "__main__":
    intents = botpy.Intents(public_guild_messages=True, guild_messages=True, public_messages=True)
    client = MyClient(intents=intents)
    client.run(appid=__config["appid"], secret=__config["secret"])

若向机器人发送消息:@机器人 /cmd_01 123
期望得到回复: /cmd_01 123
实际的到回复: /cmd_01 123

若向机器人发送消息:@机器人 /cmd_02 123
期望得到回复: /cmd_02 123
实际的到回复: /cmd_02 123

若向机器人发送消息:@机器人 123
期望得到回复: 收到!
实际的到回复: 收到!

若向机器人发送消息:@机器人 /cmd_02 /cmd_01
期望得到回复: /cmd_02 /cmd_01
实际的到回复: /cmd_01

若向机器人发送消息:@机器人 命令/cmd_02
期望得到回复: 收到!
实际的到回复: /cmd_02

@liaoyanglay
Copy link
Collaborator

PR里没看到代码变更,麻烦看下是不是漏了提交

CheckeyZerone

This comment was marked as off-topic.

@CheckeyZerone
Copy link
Contributor Author

CheckeyZerone commented Dec 19, 2023

PR里没看到代码变更,麻烦看下是不是漏了提交

刚刚提交了漏掉的代码

Copy link
Collaborator

@liaoyanglay liaoyanglay left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

频道中机器人收到at消息"@机器人 /指令",message.content的开头是机器人id,而不是指令,会导致频道中无法匹配

@CheckeyZerone
Copy link
Contributor Author

频道中机器人收到at消息"@机器人 /指令",message.content的开头是机器人id,而不是指令,会导致频道中无法匹配

@机器人的消息文本中出现机器人id信息的位置为用户在频道发送消息中@机器人的位置,这个位置通常在文本开头,但是也有可能出现在文本中间位置。修改后的代码在获取到文本信息后先把机器人id的字符串从文本中剔除,然后再进行切分,判断指令是否出现在文本开头,在频道中经过测试,暂时没有出现@机器人时无法触发指令的问题

Copy link

@iatbsky iatbsky left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

可以使用更严格的判断方法,防止误触发
你的pr:

for command in self.commands:
        if command in message.content:
            # 剔除消息文本中@机器人的字符串
            content = message.content.replace(f"<@!{(await message.api.me())['id']}>", "")
            content_split = content.lstrip().split(command)
            # 当指令出现在消息文本(已剔除@机器人的信息)的开头执行指令
            if len(content_split[0]) == 0:
                # 分割指令后面的指令参数
                kwargs["params"] = content_split[1].strip()
                return await func(*args, **kwargs)
return False

我的建议:

content_split = message.content.split(' ',3)
bot_id = await message.api.me())['id']
for command in self.commands:
    # 保证消息开头为@机器人,且接下来为/cmd,以符合客户端的设计
    if content_split[0] == f"<@!{bot_id}>" and content_split[1] == f'/{command}':
        # 分割指令后面的指令参数
        kwargs["params"] = content_split[2].strip()
        return await func(*args, **kwargs)
return False

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants