使用Python+Slack API开发聊天机器人遇'ts未定义'错误求助
问题解决:Slack机器人中
ts未定义的错误 问题详情
Failed to run listener function (error: name 'ts' is not defined)
我在用Python和Slack API开发聊天机器人时反复遇到上述错误,明确知道是ts变量在当前作用域未定义就被使用了。这个ts是在响应函数里用到的,但我不知道该在代码的哪个位置、通过什么参数获取它的值。
我的监听函数用于响应/help命令,不确定要给函数加什么参数才能拿到ts:
@app.command('/help') # 发送命令后应显示选项菜单 # 需要获取其中一个消息对象的ts值 def message_hello(ack, respond, body, command): # 测试时加了body参数 (ack, respond,body, command) # pprint(body) ack() # def message_hello(message, say): # channel_id = message['channel'] channel_id = command['channel_id'] # 必要时可以换成body # user = message['user'] user = command['user_id'] # 必要时可以换成body # 用户发送求助后在it-helpdesk频道发送问候 hello_text = f'Hi <@{user}> *请从下拉菜单中选择与你的问题最匹配的选项。*' # say(text=hello_text, channel=channel_id, thread_ts=message['ts']) time.sleep(1)
我检查过command字典里没有ts键,但不知道该从哪里获取消息的ts值:
# 检查command字典中是否存在'ts'键 thread_ts = command.get('ts', None) # 调用respond函数并传入合适的参数 if thread_ts is not None: (respond(blocks=blocks, channel=channel_id, thread_ts=thread_ts)) else: pprint("'ts' key not found in command dictionary.") # say(text=hello_text, channel=channel_id, thread_ts=message['ts']) # ts = command['ts'] pprint(respond(blocks=blocks, channel=channel_id, thread_ts=ts)) # 传入'ts' # command['ts']
解决方案
- 从
body字典中获取命令消息的ts:当用户发送/help命令时,Slack会把命令相关的完整数据放在body参数里,其中body['message_ts']就是这条命令消息的时间戳(ts)。你可以直接提取这个值:thread_ts = body.get('message_ts') - 修正
respond的调用逻辑:不需要自己指定channel_id,respond函数默认会在命令发送的频道/线程里回复。如果要开启线程回复,直接传入thread_ts即可:# 获取命令消息的ts,用于线程回复 thread_ts = body.get('message_ts') # 用respond发送带下拉菜单的消息,自动关联线程 respond(blocks=blocks, thread_ts=thread_ts) - 移除多余的
channel_id参数:respond方法不需要手动传入channel_id,它会自动使用命令触发的上下文频道,添加上去反而可能引发问题。 - 清理无效代码:删掉最后一行直接使用未定义
ts的respond调用,保留前面的判断逻辑即可。
修改后的完整监听函数示例:
import time from slack_bolt import App from pprint import pprint # 假设已经初始化了app # app = App(token="YOUR_SLACK_BOT_TOKEN", signing_secret="YOUR_SLACK_SIGNING_SECRET") @app.command('/help') def message_hello(ack, respond, body, command): ack() user = command['user_id'] hello_text = f'Hi <@{user}> *请从下拉菜单中选择与你的问题最匹配的选项。*' # 获取命令消息的ts,用于线程回复 thread_ts = body.get('message_ts') # 假设blocks是你定义的下拉菜单区块 blocks = [ { "type": "section", "text": {"type": "mrkdwn", "text": hello_text}, "accessory": { "type": "static_select", "placeholder": {"type": "plain_text", "text": "选择问题类型"}, "options": [ {"text": {"type": "plain_text", "text": "账号问题"}, "value": "account"}, {"text": {"type": "plain_text", "text": "技术故障"}, "value": "tech"} ] } } ] # 发送带下拉菜单的回复,自动关联到命令所在线程 if thread_ts: respond(blocks=blocks, thread_ts=thread_ts) else: respond(blocks=blocks) pprint("无法获取消息ts,未开启线程回复") time.sleep(1)
内容的提问来源于stack exchange,提问作者Geena Greene
相关产品推荐
相关产品推荐

