-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvotemachine.py
228 lines (137 loc) · 5.55 KB
/
votemachine.py
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
# -*- coding: utf-8 -*-
import time
import json
from collections import Counter
from slackclient import SlackClient
import settings
class BaseVoteState:
def __init__(self, vote_machine):
self.vote_machine = vote_machine
def start_vote(self, vote_name, choices):
return u'Чтобы начать новое голосование необходимо завершить текущее'
def stop_vote(self):
return u'Чтобы остановить голосование его нужно сначала начать'
def vote(self, user, value):
return u'Нет запущенного голосования'
def stat(self):
return u'Нет запущенного голосования'
class VoteWaitState(BaseVoteState):
def start_vote(self, vote_name, choices):
active_state = self.vote_machine.get_vote_active_state()
self.vote_machine.set_state(active_state)
return self.vote_machine._start_vote(vote_name, choices)
class VoteActiveState(BaseVoteState):
def vote(self, user, value):
return self.vote_machine._vote(user, value)
def stop_vote(self):
wait_state = self.vote_machine.get_vote_wait_state()
self.vote_machine.set_state(wait_state)
return self.vote_machine._stat()
def stat(self):
return self.vote_machine._stat()
class VoteMachine:
def __init__(self):
self.vote_wait_state = VoteWaitState(self)
self.vote_active_state = VoteActiveState(self)
self.state = self.vote_wait_state
self.vote_name = None
self.choices = []
self.votes = {}
# getters and setter
def get_vote_wait_state(self):
return self.vote_wait_state
def get_vote_active_state(self):
return self.vote_active_state
def set_state(self, state):
self.state = state
# vote logic
def _start_vote(self, vote_name, choices):
self.vote_name = vote_name
self.choices = choices
self.votes = {}
return 'ok'
def _stat(self):
vote_stat = Counter()
for user, value in self.votes.items():
vote_stat[value] += 1
messages = []
messages.append(self.vote_name)
for choice in self.choices:
count = vote_stat.get(choice, 0)
messages.append(u'{}: {}'.format(choice, count))
return '\n'.join(messages)
def _vote(self, user, value):
try:
index = int(value)
value = self.choices[index]
except IndexError:
return u'неверное значение'
except ValueError:
pass
if value not in self.choices:
return u'неверное значение'
self.votes[user] = value
return 'ok'
# public methods
def start_vote(self, vote_name, choices):
return self.state.start_vote(vote_name, choices)
def stop_vote(self):
return self.state.stop_vote()
def vote(self, user, value):
return self.state.vote(user, value)
def stat(self):
return self.state.stat()
class VoteBot:
def __init__(self, token, vote_machine):
self.token = token
self.sc = SlackClient(self.token)
self.sc.rtm_connect()
self.vote_machine = vote_machine
def messages(self):
while True:
response = self.sc.rtm_read()
if response:
for data in response:
if 'type' in data and data['type'] == 'message':
yield data
time.sleep(1)
def process_message(self, data):
lines = data['text'].split(u'\n')
command = lines[0].split()
response = None
if command[0] == 'vote' and len(command) == 1:
response = u'Чтобы начать голосование:\n' \
u'vote start [название]\n' \
u'вариант1\nвариант2\nвариант 3\n\n' \
u'Чтобы проголосовать:\n' \
u'vote вариант1 или vote 0\n\n' \
u'Посмотреть статистику: vote stat\n\n' \
u'Остановить голосование: vote stop'
elif command[0] == 'vote' and command[1] == 'start':
if len(lines) > 1:
vote_name = ' '.join(command[2:])
choices = lines[1:]
response = self.vote_machine.start_vote(vote_name, choices)
else:
response = u'необходимо указать варианты'
elif command[0] == 'vote' and command[1] == 'stop':
response = self.vote_machine.stop_vote()
elif command[0] == 'vote' and command[1] == 'stat':
response = self.vote_machine.stat()
elif command[0] == 'vote' and len(command) > 1:
value = ' '.join(command[1:])
response = self.vote_machine.vote(data['user'], value)
if not response:
return
info = self.sc.api_call('users.info', user=data['user'])
info = json.loads(info)
user_name = info['user']['name']
response = u'@{} {}'.format(user_name, response)
self.sc.rtm_send_message(data['channel'], response)
def run(self):
for data in self.messages():
self.process_message(data)
if __name__ == '__main__':
vote_machine = VoteMachine()
vote_bot = VoteBot(settings.API_TOKEN, vote_machine)
vote_bot.run()