Skip to content

多步回话 普通

字数统计:826 字
阅读时长:3 分钟

有时候我们希望某用户在触发机器人命令之后

还需要再接收一次或多次来自该用户或不同用户的消息

才会继续执行业务逻辑和事件流程

那么该怎么处理呢?

单用户

聊天界面
Wuyi无疑 用户
开始测试
GsCore 机器人
开始多步会话测试
GsCore 机器人
接下来你说的话我都会提取出来噢?
干扰用户 用户
你们在说什么呢?
Wuyi无疑 用户
我爱你
GsCore 机器人
你说的是 我爱你 吧?

代码示例

python
from gsuid_core.bot import Bot
from gsuid_core.sv import SL, SV
from gsuid_core.models import Event

sv_switch = SV('测试开关')

@sv_switch.on_fullmatch('开始测试')
async def get_resp_msg(bot: Bot, ev: Event):
    await bot.send('开始多步会话测试')
    resp = await bot.receive_resp(
        '接下来你说的话我都会提取出来噢?',
    )
    if resp is not None:
        await bot.send(f'你说的是 {resp.text} 吧?')

多用户

聊天界面
Wuyi无疑 用户
开始多用户测试
GsCore 机器人
开始多步会话测试
GsCore 机器人
接下来开始游戏!?所有人的会话我都会收集起来的哦!
群友A 用户
你们在说什么呢?
GsCore 机器人
你说的是 你们在说什么呢? 吧?
Wuyi无疑 用户
我爱你
GsCore 机器人
你说的是 我爱你 吧?

代码示例

python
from gsuid_core.bot import Bot
from gsuid_core.sv import SL, SV
from gsuid_core.models import Event
from async_timeout import timeout

sv_switch = SV('测试开关')

@sv_switch.on_fullmatch('开始多用户测试')
async def get_resp_msg(bot: Bot, ev: Event):
    await bot.send('开始多步会话测试')
    await bot.send('接下来开始游戏!?所有人的会话我都会收集起来的哦!')
    while True:
        resp = await bot.receive_mutiply_resp()
        if resp is not None:
            await bot.send(f'你说的是 {resp.text} 吧?')
            
# 以下为在规定时间内结束收集回复的代码
# 常用于定时结束游戏
@sv_switch.on_fullmatch('开始一场60秒的游戏')
async def get_time_limit_resp_msg(bot: Bot, ev: Event):
    await bot.send('接下来开始60秒的游戏!?')
    try:
        async with timeout(60): # 限制时长60秒
            while True:
                resp = await bot.receive_mutiply_resp()
                if resp is not None:
                    await bot.send(f'你说的是 {resp.text} 吧?')
    except asyncio.TimeoutError:
        await bot.send('时间到!!现在开始计算每个人的分数...')

总结

💡 提醒

可以看到Bot.receive_resp()后续只会接受触发该命令的用户的消息

但是Bot.receive_mutiply_resp()会接受后续全部用户的信息

注意到Bot.send_option()Bot.receive_mutiply_resp()均会调用Bot.receive_resp()

他们三个的参数都差不多,实际使用,功能区别如下:

方法说明
bot.send_option(...)发送按钮或选项提示,不等待回复
bot.receive_resp(...)发送可选消息,并等待触发命令用户的下一条消息
bot.receive_mutiply_resp(...)发送可选消息,并等待群内任意用户的后续消息

参数

  • reply:可填入 bot.send() 接受的任何值(字符串、MessageMessageSegment 等),会在等待回复前先发送一次消息。

  • option_list:类型 List[str]List[Button]List[List[str]]List[List[Button]],用于生成按钮或多选提示(部分平台支持)。

  • timeout:等待回复的超时时间(秒),默认 60

  • unsuported_platform:当平台不支持按钮时,是否转为发送多选文本提示(默认 False)。

  • sepcommand_tipscommand_start_text:在文本模式下自定义选项分隔符和提示语。