- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
好的伙计们,这是我的问题。
我正在开发一个带有打包机器人的 Slack 应用程序,允许用户在 Slack 中玩游戏。我已经按照 API guidelines 成功构建了机器人并将其与应用程序打包在一起.一旦我发现 Interactive Messages功能,我决定实现上述功能,以便在游戏中更加人性化。
交互式消息功能允许您发布带有按钮的消息,用户可以单击这些按钮来调用操作。我的机器人脚本,我们称它为 bot.py
,提示用户(使用 Slack chat.postMessage 函数)一条消息,其中包含一些可供选择的按钮。这个脚本有一个类(我知道它应该更模块化,但一切都很及时),它打开一个网络套接字,通过 Slack RTM API 进行通信。 .因此,当脚本运行时,它始终“监听”来自 channel 中用户的命令,如下所示:@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 中实例化一个
文件,这当然不会按预期工作,因为该函数将使用新的 Bot()
对象.pyBot()
实例调用,因此不会处于与当前游戏相同的状态.
那么我到底如何才能将 POST 信息返回到 bot.py
中所需的 Bot()
实例以进行进一步处理呢?我是 Python 中 OOP 的新手,尤其是 Flask 和 Slack API 的新手,所以请放轻松 ;)。
提前致谢。
最佳答案
长话短说:基本上,解决方案是创建一个 Celery 任务,该任务使用 Slack Events API 从 Flask 应用程序实例化机器人实例。您将任务设置为在输入所需输入后启动,立即将所需的 Response(200) 返回给 Slack,同时机器人脚本(启动 RTM API 网络套接字)并行启动。
细节:因此,如上所述,事实证明所需的是 a queuing service of some sort .我最终选择了 Celery因为它相对容易与 Heroku 集成(我在其中托管 Slack 应用程序)及其易于理解的文档。
以这种方式开发您的 Slack 应用程序需要设置和使用 Slack Events API从发布消息的 Slack channel 接收命令(本例中为“play my_game”)。程序的 Flask 应用程序 (app.py) 部分会监听此事件,并在输入与您的内容匹配时在寻找时,它会并行启动 Celery 任务(在 tasks.py 中,在此示例中实例化 bot.py 的 Bot() 实例)。 :) 现在,机器人可以使用 Slack RTM API 和 Slack Events API 进行监听和响应。这允许您在 Slack 框架内构建丰富的应用程序/服务。
如果您希望设置类似的东西,下面是我的项目布局和重要的代码详细信息。请随意将它们用作模板。
项目布局:
__init__.py:
from celery import Celery
app = Celery('tasks')
import os
app.conf.update(BROKER_URL=os.environ['RABBITMQ_BIGWIG_URL']) # Heroku Celery broker
我的应用程序.py:
from flask import Flask, request, Response, render_template
import app
from app import tasks
app = Flask(__name__)
@app.route('/events', methods=['POST'])
def events():
"""
Handles the inbound event of a post to the main Slack channel
"""
data = json.loads(request.data)
try:
for k, v in data['event'].iteritems():
ts = data['event']['ts']
channel = data['event']['channel']
user_id = data['event']['user']
team_id = data['team_id']
if 'play my_game' in str(v):
tasks.launch_bot.delay(user_id, channel, ts, team_id) # launch the bot in parallel
return Response(), 200
except Exception as e:
raise
bot.py:
from slackclient import SlackClient
class Bot():
def main():
# opening the Slack web-socket connection
READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose
if self.slack_client.rtm_connect():
while True:
command, channel, user, ts = self.parse_slack_output()
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, ts)
else:
self.handle_command(command, channel, user, ts)
time.sleep(READ_WEBSOCKET_DELAY)
任务.py:
import bot
from bot import Bot
from app import app
@app.task
def launch_bot(user_id, channel, ts, team_id):
'''
Instantiates the necessary objects to play a game
Args:
[user_id] (str) The id of the user from which the command was sent
[channel] (str) The channel the command was posted in
[ts] (str) The timestamp of the command
'''
print "launch_bot(user_id,channel)"
app.control.purge()
bot = Bot()
bot.initialize(user_id, channel)
bot.main()
Procfile(如果使用 Heroku):
web: gunicorn --pythonpath app my_app:app
worker: celery -A app.tasks worker -B --loglevel=DEBUG
如果您有任何问题,请告诉我。这花了我一些时间才弄清楚,如果您正在努力解决这个问题,我很乐意为您提供帮助。
关于python - 如何将通过 HTTP POST 接收的数据从 Python Flask 脚本传递到单独的 Python 脚本进行处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42378011/
我有一个存储结构向量的应用程序。这些结构保存有关系统上每个 GPU 的信息,如内存和 giga-flop/s。每个系统上有不同数量的 GPU。 我有一个程序可以同时在多台机器上运行,我需要收集这些数据
我很好奇 MPI 中缺少此功能: MPI_Isendrecv( ... ); 即,非阻塞发送和接收,谁能告诉我其省略背后的基本原理? 最佳答案 我的看法是 MPI_SENDRECV存在是为了方便那些想
当我用以下方法监听TCP或UDP套接字时 ssize_t recv(int sockfd, void *buf, size_t len, int flags); 或者 ssize_t recvfrom
SUM:如何在 azure 事件网格中推迟事件触发或事件接收? 我设计的系统需要对低频对象状态(创建、启动、检查长时间启动状态、结束)使用react。它看起来像是事件处理的候选者。我想用azure函数
我正在 MPI 中实现一个程序,其中主进程(等级 = 0)应该能够接收来自其他进程的请求,这些进程要求只有根才知道的变量值。如果我按等级 0 进行 MPI_Recv(...),我必须指定向根发送请求的
我正在学习DX12,并在此过程中学习“旧版Win32”。 我在退出主循环时遇到问题,这似乎与我没有收到WM_CLOSE消息有关。 在C++,Windows 10控制台应用程序中。 #include
SUM:如何在 azure 事件网格中推迟事件触发或事件接收? 我设计的系统需要对低频对象状态(创建、启动、检查长时间启动状态、结束)使用react。它看起来像是事件处理的候选者。我想用azure函数
我想编写方法来通过号码发送短信并使用编辑文本字段中的文本。发送消息后,我想收到一些声音或其他东西来提醒我收到短信。我怎样才能做到这一点?先感谢您,狼。 最佳答案 这个网站似乎对两者都有很好的描述:ht
所以我正在用 Java 编写一个程序,在 DatagramSocket 和 DatagramPacket 的帮助下发送和接收数据。问题是,在我发送数据/接收数据之间的某个时间 - 我发送数据的程序中的
我是 Android 编程新手,我正在用 Java 编写一个应用程序,该应用程序可以打开相机拍照并保存。我通过 Intents 做到了,但看不到 onActivityResult 正在运行。 我已经在
我有一个套接字服务器和一个套接字客户端。客户端只有一个套接字。我必须使用线程在客户端发送/接收数据。 static int sock = -1; static std::mutex mutex; vo
我正在尝试使用 c 中的套接字实现 TCP 服务器/客户端。我以这样的方式编写程序,即我们在客户端发送的任何内容都逐行显示在服务器中,直到键入退出。该程序可以运行,但数据最后一起显示在服务器中。有人可
我正在使用微 Controller 与 SIM808 模块通信,我想发送和接收 AT 命令。 现在的问题是,对于某些命令,我只收到了我应该收到的答案的一部分,但对于其他一些命令,我收到了我应该
我用c设计了一个消息传递接口(interface),用于在我的系统中运行的不同进程之间提供通信。该接口(interface)为此目的创建 10-12 个线程,并使用 TCP 套接字提供通信。 它工作正
我需要澄清一下在套接字程序中使用多个发送/接收。我的客户端程序如下所示(使用 TCP SOCK_STREAM)。 send(sockfd,"Messgfromlient",15,0);
我正在构建一个真正的基本代理服务器到我现有的HTTP服务器中。将传入连接添加到队列中,并将信号发送到另一个等待线程队列中的一个线程。此线程从队列中获取传入连接并对其进行处理。 问题是代理程序真的很慢。
我正在使用 $routeProvider 设置一条类似 的路线 when('/grab/:param1/:param2', { controller: 'someController',
我在欧洲有通过 HLS 流式传输的商业流媒体服务器。http://europe.server/stream1/index.m3u8现在我在美国的客户由于距离而遇到一些网络问题。 所以我在美国部署了新服
我有一个长期运行的 celery 任务,该任务遍历一系列项目并执行一些操作。 任务应该以某种方式报告当前正在处理的项目,以便最终用户知道任务的进度。 目前,我的django应用程序和celery一起坐
我需要将音频文件从浏览器发送到 python Controller 。我是这样做的: var xmlHttp = new XMLHttpRequest(); xmlHttp.open( "POST",
我是一名优秀的程序员,十分优秀!