Skip to content

Commit 64da5d7

Browse files
committed
Add more commands to Slack bot
1 parent 54b022a commit 64da5d7

File tree

2 files changed

+221
-64
lines changed

2 files changed

+221
-64
lines changed

main_slack.py

+136-64
Original file line numberDiff line numberDiff line change
@@ -1,85 +1,157 @@
1-
from slackclient import SlackClient
1+
from flask import abort, Flask, jsonify, request
2+
import requests
23
import logging
4+
import utils
35
import json
4-
import time
56
import os
6-
import utils
77

88
# Enable logging
99
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - \
1010
%(message)s', level=logging.INFO)
1111
logger = logging.getLogger(__name__)
1212
logger.setLevel(logging.DEBUG)
13+
app = Flask(__name__)
14+
15+
slack_token = utils.get_token('res/token_slack.json')
16+
1317

14-
slack_client = SlackClient(utils.get_token('res/token_slack.json'))
15-
starterbot_id = None
18+
###
19+
# Slack API
20+
###
1621

17-
# Constants.
18-
RTM_READ_DELAY = 0.1 # 1 second delay between reading from RTM.
19-
counter = 0
22+
@app.route('/confirm', methods=['POST'])
23+
def confirm():
24+
req = request.form.to_dict()
25+
data = json.loads(req["payload"])
26+
backend = data["actions"][0]["name"]
27+
value = data["actions"][0]["value"]
2028

29+
payload = {
30+
"text": "Ok :slightly_smiling_face:",
31+
}
32+
headers = {
33+
'content-type': "application/json",
34+
}
35+
response = requests.request("POST", data['response_url'], data=json.dumps(payload), headers=headers)
36+
print(response.text)
2137

22-
def parse_bot_commands(slack_events):
23-
for event in slack_events:
24-
if event["type"] == "message" and "subtype" not in event:
25-
message = event["text"]
26-
return message, event["channel"]
27-
return None, None
38+
send_image('tmp/{}'.format(value), backend, data['channel']['id'])
2839

40+
return ""
2941

30-
def handle_command(command, channel):
31-
global counter
32-
backend = command.lower()
42+
43+
###
44+
# Bot Commands
45+
###
46+
@app.route('/calibration', methods=['POST'])
47+
def calibration():
48+
data = request.form.to_dict()
49+
backend = data['text'].lower()
50+
51+
extension = '_multiqubut_err.png'
3352

3453
if backend in utils.backends:
35-
counter += 1
36-
response = "Wait a sec ..."
37-
slack_client.api_call(
38-
"chat.postMessage",
39-
channel=channel,
40-
text=response
41-
)
42-
# utils.create_statistics(backend)
43-
slack_client.api_call(
44-
'files.upload',
45-
channels=channel,
46-
as_user=True,
47-
filename=backend,
48-
file=open('tmp/{}_to_send.png'.format(backend), 'rb'),
49-
)
50-
elif command == 'info':
51-
response = str(counter)
52-
slack_client.api_call(
53-
"chat.postMessage",
54-
channel=channel,
55-
text=response
56-
)
54+
quick_response(data['response_url'])
55+
send_image('tmp/{}{}'.format(backend, extension), backend, data['channel_id'])
5756
else:
58-
response = list()
59-
response.append("I'm sorry, I don't understand!")
60-
response.append("I understand only these messages: *ibmqx4* or *ibmqx5*")
61-
response = '\n'.join(response)
62-
slack_client.api_call(
63-
"chat.postMessage",
64-
channel=channel,
65-
text=response
66-
)
67-
68-
69-
def main():
70-
if slack_client.rtm_connect(with_team_state=False):
71-
# Read bot's user ID by calling Web API method `auth.test`.
72-
starterbot_id = slack_client.api_call("auth.test")["user_id"]
73-
logger.info("Bot is connected and running!")
74-
75-
while True:
76-
command, channel = parse_bot_commands(slack_client.rtm_read())
77-
if command:
78-
handle_command(command, channel)
79-
time.sleep(RTM_READ_DELAY)
57+
send_buttons(data["response_url"], extension)
58+
59+
return ""
60+
61+
62+
@app.route('/jobs', methods=['POST'])
63+
def jobs():
64+
data = request.form.to_dict()
65+
backend = data['text'].lower()
66+
67+
extension = '.png'
68+
69+
if backend in utils.backends:
70+
quick_response(data['response_url'])
71+
send_image('tmp/{}{}'.format(backend, extension), backend, data['channel_id'])
8072
else:
81-
logger.info("Connection failed. Exception traceback printed above.")
73+
send_buttons(data["response_url"], extension)
74+
75+
return ""
76+
77+
78+
@app.route('/full', methods=['POST'])
79+
def full():
80+
data = request.form.to_dict()
81+
backend = data['text'].lower()
82+
83+
extension = '_to_send.png'
84+
85+
if backend in utils.backends:
86+
quick_response(data['response_url'])
87+
send_image('tmp/{}{}'.format(backend, extension), backend, data['channel_id'])
88+
else:
89+
send_buttons(data["response_url"], extension)
90+
91+
return ""
92+
93+
94+
###
95+
# Helper Functions
96+
###
97+
def quick_response(response_url):
98+
payload = {
99+
"text": "Wait a sec :hourglass_flowing_sand:",
100+
}
101+
headers = {
102+
'content-type': "application/json",
103+
}
104+
response = requests.request("POST", response_url, data=json.dumps(payload), headers=headers)
105+
print(response.text)
106+
107+
108+
def send_image(path, name, channel):
109+
my_file = {
110+
'file': (path, open(path, 'rb'), 'png')
111+
}
112+
payload = {
113+
"filename": name,
114+
'token': slack_token,
115+
"channels": [channel]
116+
}
117+
118+
response = requests.post("https://slack.com/api/files.upload", params=payload, files=my_file)
119+
120+
121+
def send_buttons(response_url, extension):
122+
payload = {
123+
"text": "What backend you are interested in?",
124+
"attachments": [
125+
{
126+
"text": "Choose a backend :qiskit:",
127+
"callback_id": 42,
128+
"color": "#3AA3E3",
129+
"attachment_type": "default",
130+
"actions": [
131+
{
132+
"name": "ibmqx4",
133+
"text": "ibmqx4",
134+
"type": "button",
135+
"value": "ibmqx4{}".format(extension)
136+
},
137+
{
138+
"name": "ibmqx5",
139+
"text": "ibmqx5",
140+
"type": "button",
141+
"value": "ibmqx5{}".format(extension)
142+
},
143+
]
144+
}
145+
]
146+
}
147+
148+
headers = {
149+
'content-type': "application/json",
150+
}
151+
152+
response = requests.request("POST", response_url, data=json.dumps(payload), headers=headers)
153+
print(response.text)
82154

83155

84-
if __name__ == "__main__":
85-
main()
156+
if __name__ == '__main__':
157+
app.run(host='0.0.0.0', port=5000)

res/main_slack_old.py

+85
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
from slackclient import SlackClient
2+
import logging
3+
import json
4+
import time
5+
import os
6+
import utils
7+
8+
# Enable logging
9+
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - \
10+
%(message)s', level=logging.INFO)
11+
logger = logging.getLogger(__name__)
12+
logger.setLevel(logging.DEBUG)
13+
14+
slack_client = SlackClient(utils.get_token('res/token_slack.json'))
15+
starterbot_id = None
16+
17+
# Constants.
18+
RTM_READ_DELAY = 0.1 # 1 second delay between reading from RTM.
19+
counter = 0
20+
21+
22+
def parse_bot_commands(slack_events):
23+
for event in slack_events:
24+
if event["type"] == "message" and "subtype" not in event:
25+
message = event["text"]
26+
return message, event["channel"]
27+
return None, None
28+
29+
30+
def handle_command(command, channel):
31+
global counter
32+
backend = command.lower()
33+
34+
if backend in utils.backends:
35+
counter += 1
36+
response = "Wait a sec ..."
37+
slack_client.api_call(
38+
"chat.postMessage",
39+
channel=channel,
40+
text=response
41+
)
42+
# utils.create_statistics(backend)
43+
slack_client.api_call(
44+
'files.upload',
45+
channels=channel,
46+
as_user=True,
47+
filename=backend,
48+
file=open('tmp/{}_to_send.png'.format(backend), 'rb'),
49+
)
50+
elif command == 'info':
51+
response = str(counter)
52+
slack_client.api_call(
53+
"chat.postMessage",
54+
channel=channel,
55+
text=response
56+
)
57+
else:
58+
response = list()
59+
response.append("I'm sorry, I don't understand!")
60+
response.append("I understand only these messages: *ibmqx4* or *ibmqx5*")
61+
response = '\n'.join(response)
62+
slack_client.api_call(
63+
"chat.postMessage",
64+
channel=channel,
65+
text=response
66+
)
67+
68+
69+
def main():
70+
if slack_client.rtm_connect(with_team_state=False):
71+
# Read bot's user ID by calling Web API method `auth.test`.
72+
starterbot_id = slack_client.api_call("auth.test")["user_id"]
73+
logger.info("Bot is connected and running!")
74+
75+
while True:
76+
command, channel = parse_bot_commands(slack_client.rtm_read())
77+
if command:
78+
handle_command(command, channel)
79+
time.sleep(RTM_READ_DELAY)
80+
else:
81+
logger.info("Connection failed. Exception traceback printed above.")
82+
83+
84+
if __name__ == "__main__":
85+
main()

0 commit comments

Comments
 (0)