-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
187 lines (170 loc) · 6.44 KB
/
bot.py
File metadata and controls
187 lines (170 loc) · 6.44 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
import urllib
import json
import time
from boat import Boat
import re
import pickle
from os import path
posre = re.compile('!\d')
IDLE = 0
WAITING_NEW_CONFIRM = 1
WAITING_REPLACE_CONFIRM = 2
DATA_FILE = 'RowingBot.dat'
class Bot(object):
def __init__(self, token):
self.__token = token
self.__last_received_update = None
self.__boat = {}
self.__status = {}
self.__cache_pos = {}
self.__cache_name = {}
self.__cache_size = {}
def __run_method(self, method, params=None):
p = None
if params is not None:
p = urllib.urlencode(params)
return json.loads(urllib.urlopen('https://api.telegram.org/bot%s/%s' % (self.__token,
method),p).read())
def __get_updates(self,offset=None):
params = None
if offset is None:
if self.__last_received_update is not None:
offset = self.__last_received_update + 1
if offset is not None:
params = {'offset': offset}
updates = self.__run_method('getUpdates',params)
if len(updates['result']) > 0:
self.__last_received_update = updates['result'][-1]['update_id']
return updates['result']
def send_message(self, chat_id, text):
params = {'chat_id': chat_id, 'text': text.encode('utf-8')}
updates = self.__run_method('sendMessage',params)
def __handle_message(self, msg):
sender = msg['from']
text = msg['text'].strip()
chat_id = msg['chat']['id']
splitted = text.split(' ',1)
cmd = splitted[0]
params = None
boat = None
if chat_id in self.__boat:
boat = self.__boat[chat_id]
if len(splitted) > 1:
params = splitted[1].strip()
if cmd == '!new' or cmd == '!yes' and chat_id in self.__status and self.__status[chat_id] == WAITING_NEW_CONFIRM:
if boat and cmd == '!new':
self.send_message(chat_id, 'Are you sure you want to erase the last practice?')
self.__status[chat_id] = WAITING_NEW_CONFIRM
self.__cache_size[chat_id] = params
return
self.__status[chat_id] = IDLE
print 'New boat!'
if params is None:
params = 8
if chat_id in self.__cache_size:
params = self.__cache_size[chat_id]
if params is None:
params = 8
self.__boat[chat_id] = Boat(int(params))
self.send_message(chat_id, 'Who is coming to the next ' +
'practice?\nPress "!" and the number you would like ' +
'to take. For example, if you would like to sit at ' +
'Liron\'s place with a view to Loch-Blecher, send the ' +
'message "!1"')
elif posre.match(cmd) or cmd == '!yes' and chat_id in self.__status and self.__status[chat_id] == WAITING_REPLACE_CONFIRM:
if boat is None:
return
pos = 0
name = '%s %s' % (sender['first_name'], sender['last_name'])
if params is not None:
name = params
if cmd == '!yes':
pos = self.__cache_pos[chat_id]
name = self.__cache_name[chat_id]
else:
pos = int(cmd[1])
if name == '-':
if boat.rowers[pos-1] is None:
return
self.send_message(chat_id,
'%s was removed from the boat, %d now is free' %
(boat.rowers[pos-1],pos))
boat.add_rower(pos, None)
return
print 'New rower!'
if boat.rowers[pos-1] is not None and cmd != '!yes':
self.send_message(chat_id, 'This spot is already taken by ' +
'%s, are you sure you want to replace it?' %
boat.rowers[pos-1])
self.__status[chat_id] = WAITING_REPLACE_CONFIRM
self.__cache_pos[chat_id] = pos
self.__cache_name[chat_id] = name
return
self.__status[chat_id] = IDLE
print pos,name
boat.add_rower(pos, name)
if len(boat.get_missing()) == 0:
self.send_message(chat_id, u'\U0001F3BA\U0001F3BA\U0001F3BA')
rowers = boat.rowers
ret = ''
i = 1
for x in rowers:
if x is None:
x = "???"
ret = '\n%d. %s' % (i,x) + ret
i += 1
self.send_message(chat_id,
r'We have a boat!' + ret)
elif cmd == '!missing':
self.__status[chat_id] = IDLE
if boat is None:
return
missing = ', '.join([str(x) for x in boat.get_missing()])
if len(missing) == 0:
self.send_message(chat_id, 'No one is missing!')
else:
self.send_message(chat_id, 'We are still missing %s!' % missing)
elif cmd == '!status':
self.__status[chat_id] = IDLE
if boat is None:
self.send_message(chat_id, 'No active session')
else:
rowers = boat.rowers
ret = ''
i = 1
for x in rowers:
if x is None:
x = "???"
ret = '\n%d. %s' % (i,x) + ret
i+=1
self.send_message(chat_id,'Current status:' + ret)
def message_loop(self):
while True:
try:
time.sleep(1)
updates = self.__get_updates()
for x in updates:
try:
msg = x['message']
self.__handle_message(msg)
except:
pass
with open(DATA_FILE,'wb') as f:
pickle.dump(self,f)
except:
print 'Error on message loop'
pass
def main():
b = None
if path.isfile(DATA_FILE):
with open(DATA_FILE,'rb') as f:
b = pickle.load(f)
else:
import sys
if len(sys.argv) < 2:
print 'Usage: ./%s token' % sys.argv[0]
return
b = Bot(sys.argv[1])
b.message_loop()
if __name__ == '__main__':
main()