-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathapp.py
More file actions
249 lines (188 loc) · 8.45 KB
/
app.py
File metadata and controls
249 lines (188 loc) · 8.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
"""
Agile Scrum Pokerbot for Slack
Hosted on AWS Lambda.
:Author: Nate Yolles <yolles@adobe.com>
:Homepage: https://github.com/nateyolles/slack-pokerbot
"""
import boto3
import logging
from urlparse import parse_qs
import json
import urllib2
# Start Configuration
SLACK_TOKENS = ('<insert your Slack token>', '<additional Slack token>')
IMAGE_LOCATION = '<insert your image path> (e.g. http://www.my-site.com/images/)'
COMPOSITE_IMAGE = IMAGE_LOCATION + 'composite.png'
VALID_VOTES = {
0 : IMAGE_LOCATION + '0.png',
1 : IMAGE_LOCATION + '1.png',
2 : IMAGE_LOCATION + '2.png',
3 : IMAGE_LOCATION + '3.png',
5 : IMAGE_LOCATION + '5.png',
8 : IMAGE_LOCATION + '8.png',
13 : IMAGE_LOCATION + '13.png',
20 : IMAGE_LOCATION + '20.png',
40 : IMAGE_LOCATION + '40.png',
100 : IMAGE_LOCATION + '100.png'
}
# End Configuration
logger = logging.getLogger()
logger.setLevel(logging.INFO)
poker_data = {}
def lambda_handler(event, context):
"""The function that AWS Lambda is configured to run on POST request to the
configuration path. This function handles the main functions of the Pokerbot
including starting the game, voting, calculating and ending the game.
"""
req_body = event['body']
params = parse_qs(req_body)
token = params['token'][0]
if token not in SLACK_TOKENS:
logger.error("Request token (%s) does not match expected.", token)
raise Exception("Invalid request token")
post_data = {
'team_id' : params['team_id'][0],
'team_domain' : params['team_domain'][0],
'channel_id' : params['channel_id'][0],
'channel_name' : params['channel_name'][0],
'user_id' : params['user_id'][0],
'user_name' : params['user_name'][0],
'command' : params['command'][0],
'text' : params['text'][0] if 'text' in params.keys() else None,
'response_url' : params['response_url'][0]
}
if post_data['text'] == None:
return create_ephemeral('Type */pokerbot help* for pokerbot commands.')
command_arguments = post_data['text'].split(' ')
sub_command = command_arguments[0]
if sub_command == 'deal':
if post_data['team_id'] not in poker_data.keys():
poker_data[post_data['team_id']] = {}
poker_data[post_data['team_id']][post_data['channel_id']] = {}
message = Message('*The poker planning game has started.*')
message.add_attachment('Vote by typing */pokerbot vote <number>*.', None, COMPOSITE_IMAGE)
return message.get_message()
elif sub_command == 'vote':
if (post_data['team_id'] not in poker_data.keys() or
post_data['channel_id'] not in poker_data[post_data['team_id']].keys()):
return create_ephemeral("The poker planning game hasn't started yet.")
if len(command_arguments) < 2:
return create_ephemeral("Your vote was not counted. You didn't enter a number.")
vote_sub_command = command_arguments[1]
vote = None
try:
vote = int(vote_sub_command)
except ValueError:
return create_ephemeral("Your vote was not counted. Please enter a number.")
if vote not in VALID_VOTES:
return create_ephemeral("Your vote was not counted. Please enter a valid poker planning number.")
already_voted = poker_data[post_data['team_id']][post_data['channel_id']].has_key(post_data['user_id'])
poker_data[post_data['team_id']][post_data['channel_id']][post_data['user_id']] = {
'vote' : vote,
'name' : post_data['user_name']
}
if already_voted:
return create_ephemeral("You changed your vote to *%d*." % (vote))
else:
message = Message('%s voted' % (post_data['user_name']))
send_delayed_message(post_data['response_url'], message)
return create_ephemeral("You voted *%d*." % (vote))
elif sub_command == 'tally':
if (post_data['team_id'] not in poker_data.keys() or
post_data['channel_id'] not in poker_data[post_data['team_id']].keys()):
return create_ephemeral("The poker planning game hasn't started yet.")
message = None
names = []
for player in poker_data[post_data['team_id']][post_data['channel_id']]:
names.append(poker_data[post_data['team_id']][post_data['channel_id']][player]['name'])
if len(names) == 0:
message = Message('No one has voted yet.')
elif len(names) == 1:
message = Message('%s has voted.' % names[0])
else:
message = Message('%s have voted.' % ', '.join(sorted(names)))
return message.get_message()
elif sub_command == 'reveal':
if (post_data['team_id'] not in poker_data.keys() or
post_data['channel_id'] not in poker_data[post_data['team_id']].keys()):
return create_ephemeral("The poker planning game hasn't started yet.")
votes = {}
for player in poker_data[post_data['team_id']][post_data['channel_id']]:
player_vote = poker_data[post_data['team_id']][post_data['channel_id']][player]['vote']
player_name = poker_data[post_data['team_id']][post_data['channel_id']][player]['name']
if not votes.has_key(player_vote):
votes[player_vote] = []
votes[player_vote].append(player_name)
# reset the game by deleting the current channel's data
del poker_data[post_data['team_id']][post_data['channel_id']]
vote_set = set(votes.keys())
if len(vote_set) == 1:
message = Message('*Congratulations!*')
message.add_attachment('Everyone selected the same number.', 'good', VALID_VOTES.get(vote_set.pop()))
return message.get_message()
else:
message = Message('*No winner yet.* Discuss and continue voting.')
for vote in votes:
message.add_attachment(", ".join(votes[vote]), 'warning', VALID_VOTES[vote], True)
return message.get_message()
elif sub_command == 'help':
return create_ephemeral('Pokerbot helps you play Agile/Scrum poker planning.\n\n' +
'Use the following commands:\n' +
' /pokerbot deal\n' +
' /pokerbot vote ' + str(sorted(VALID_VOTES.keys())) + '\n' +
' /pokerbot tally\n' +
' /pokerbot reveal')
else:
return create_ephemeral('Invalid command. Type */pokerbot help* for pokerbot commands.')
def create_ephemeral(text):
"""Send private response to user initiating action
:param text: text in the message
"""
message = {}
message['text'] = text
return message
def send_delayed_message(url, message):
"""Send a delayed in_channel message.
You can send up to 5 messages per user command.
"""
req = urllib2.Request(url)
req.add_header('Content-Type', 'application/json')
try:
response = urllib2.urlopen(req, json.dumps(message.get_message()))
except urllib2.URLError:
logger.error("Could not send delayed message to %s", url)
class Message():
"""Public Slack message
see `Slack message formatting <https://api.slack.com/docs/formatting>`_
"""
def __init__(self, text):
"""Message constructor.
:param text: text in the message
:param color: color of the Slack message side bar
"""
self.__message = {}
self.__message['response_type'] = 'in_channel'
self.__message['text'] = text
def add_attachment(self, text, color=None, image=None, thumbnail=False):
"""Add attachment to Slack message.
:param text: text in the attachment
:param image: image in the attachment
:param thumbnail: image will be thubmanail if True, full size if False
"""
if not self.__message.has_key('attachments'):
self.__message['attachments'] = []
attachment = {}
attachment['text'] = text
if color != None:
attachment['color'] = color
if image != None:
if thumbnail:
attachment['thumb_url'] = image
else:
attachment['image_url'] = image
self.__message['attachments'].append(attachment)
def get_message(self):
"""Get the Slack message.
:returns: the Slack message in format ready to return to Slack client
"""
return self.__message