【发布时间】:2017-02-21 21:07:47
【问题描述】:
好的,伙计们,这是我的问题。
我正在开发一个带有打包机器人的 Slack 应用程序,允许用户在 Slack 中玩游戏。我已经按照API guidelines 成功构建了机器人并将其与应用程序打包在一起。当我发现Interactive Messages 功能后,我决定实现该功能,以使游戏更加用户友好。
交互式消息功能允许您使用按钮发布消息,用户可以单击这些按钮来调用操作。我的机器人脚本,我们称之为bot.py,提示用户(使用Slack chat.postMessage 函数)一条消息,其中包含一些可供选择的按钮。这个脚本有一个类(我知道它应该更加模块化,但一切都很好),它打开一个 web-socket 用于通过Slack RTM API 进行通信。因此,当脚本运行时,它总是“侦听”来自频道中用户的命令,引导如下:@botname command。调用这种“一直在听”状态的脚本部分如下所示:
#bot.py
...
if slack_client.rtm_connect():
print("MYBOT v1.0 connected and running!")
while True:
command, channel, user = self.parse_slack_output(slack_client.rtm_read())
if command and channel:
if channel not in self.channel_ids_to_name.keys():
#this (most likely) means that this channel is a PM with the bot
self.handle_private_message(command, user)
else:
self.handle_command(command, channel, user)
time.sleep(READ_WEBSOCKET_DELAY)
else:
print("Connection failed. Invalid Slack token or bot ID?")
这一切都很好。现在,假设用户已使用命令成功创建游戏实例并开始玩游戏。在某一时刻,系统会提示用户输入王牌,如下所示:
#bot.py
...
attachments =[{
"title":"Please select index for trump suit:",
"fallback":"Your interface does not support interactive messages.",
"callback_id":"prompt_trump_suit",
"attachment_type":"default",
"actions":
[{"name":"diamonds","text":":diamonds:","type":"button","value":"0"},
{"name":"clubs","text":":clubs:","type":"button","value":"1"},
{"name":"hearts","text":":hearts:","type":"button","value":"2"},
{"name":"spades","text":":spades:","type":"button","value":"3"}]
}]
slack.chat.post_message(
channel=player_id,
as_user=True,
attachments=attachments
)
互动消息looks like this。单击此消息中的一个按钮的操作通过 HTTP POST 将有效负载发送到 Web 服务器。我在项目中的另一个脚本,我们将调用app.py,是一个 Flask 脚本,当用户单击其中一个按钮时,它成功接收到这个 POST 请求。接收 POST 请求的脚本部分如下所示:
#app.py
...
# handles interactive button responses for mybot
@app.route('/actions', methods=['POST'])
def inbound():
payload = request.form.get('payload')
data = json.loads(payload)
token = data['token']
if token == SLACK_VERIFICATION_TOKEN:
print 'TOKEN is good!'
response_url = data['response_url']
channel_info = data['channel']
channel_id = channel_info['id']
user_info = data['user']
user_id = user_info['id']
user_name = user_info['name']
actions = data['actions'][0]
value = actions['value']
print 'User sending message: ',user_name
print "Value received: ",value
return Response(), 200
当按钮被点击时,我得到了预期的输出:
TOKEN is good!
User sending message: my_username
Value received: 3
所以到目前为止一切都很成功。现在,我要做的是获取该 POST 信息并使用它来调用我的bot.py 脚本中的一个函数,该函数处理王牌套装选择。问题是,如果我要调用该函数,我们称之为handle_trump_suit_selection(),我首先必须在app.py 文件中实例化一个Bot() 对象,这当然不会按预期工作,因为该函数将是使用新的Bot() 实例调用,因此不会处于与当前游戏相同的状态。
那么,我怎么才能将 POST 信息返回到 bot.py 中所需的 Bot() 实例以进行进一步处理?我是 Python 中 OOP 的新手,尤其是 Flask 和 Slack API 的新手,所以请放轻松;)。
提前致谢。
【问题讨论】:
标签: python python-2.7 flask slack-api slack