-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
389 lines (305 loc) · 12.7 KB
/
bot.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
import telebot
import json
import re
import datetime
from telebot import types
from citymappy import madBus
from citymappy import madCercanias
# Secure token read ####
with open("./acm.token", "r") as TOKEN:
bot = telebot.TeleBot(TOKEN.read().strip())
# Load all text to say from json file ####
with open("./dataBot/text.json", "r") as data_text:
text = json.load(data_text)
location_text = text['location']
help_text = text['help']
# EMT api load
with open("./EMTapi.auth", "r") as EMTapi:
EMTapi_id = EMTapi.readline().strip('\n')
EMTapi_pass = EMTapi.readline().strip('\n').strip(' ')
# GMaps Static Location api load
with open("./GMapsStaticApi.auth", "r") as GMapsStatic_api:
GMapsStatic_api_name = GMapsStatic_api.readline().strip('\n')
GMapsStatic_api_pass = GMapsStatic_api.readline().strip('\n').strip(' ')
with open('./dataBot/admins.json', 'r') as adminData:
admins = json.load(adminData)
# USER DATA ########
location = {}
with open("./data/user_fav.json", "r+") as fav:
user_fav = json.load(fav)
def sign_up(uid):
if str(uid) in user_fav:
return
user_fav[str(uid)] = {'bus_stop': [], 'railstation': []}
def add_fav_bus_stop(uid, idStop):
if str(uid) not in user_fav:
sign_up(uid)
user_fav[str(uid)]['bus_stop'].append(str(idStop))
save_fav()
def add_fav_railstation(uid, idStop):
if str(uid) not in user_fav:
sign_up(uid)
user_fav[str(uid)]['railstation'].append(str(idStop))
print(user_fav)
def get_fav_stations(uid):
if str(uid) not in user_fav:
return []
return user_fav[str(uid)]['bus_stop']
def save_fav():
with open("./data/user_fav.json", 'w') as f:
f.write(json.dumps(user_fav))
# Listener
def listener(messages):
# When new messages arrive TeleBot will call this function.
for m in messages:
now = str(datetime.datetime.now()).split(' ')[-1].split('.')[0]
if m.content_type == 'text' or m.content_type == 'location':
# Prints the sent message to the console
if m.chat.type == 'private':
print(now + ":: Chat -> " + str(m.chat.first_name) +
" [" + str(m.chat.id) + "]: " + str(m.text))
else:
print(now + ":: Group -> " + str(m.chat.title) +
" [" + str(m.chat.id) + "]: " + str(m.text))
def isAdmin_fromPrivate(message):
if message.chat.type == 'private':
userID = message.from_user.id
if str(userID) in admins:
return True
return False
def format_bus_stop_time(idStop):
# try:
response = madBus.get_stop_time(idStop)
# except Exception:
# return "Error. Por favor, intentalo de nuevo."
response_text = "{: <6}{: ^15}{: >6}\n".format("Linea", "Destino", "Salida")
try:
for i in range(response['stops'].__len__()):
n = str(response['stops'][i]['name'])
h = str(response['stops'][i]['headsign'])
h_trunk = h[:14] + (h[14:] and '.') # Prevent a big headsign
a = response['stops'][i]['arrival']
if ((a / 60) > 1):
a = str(a//60)
else:
a = '>>'
response_text += '{: <6}{: ^15}{: >6}\n'.format(n, h, a)
except:
pass
return '```\n' + response_text + '```'
def format_raildepartures(idStop):
response = madCercanias.get_departures(idStop)
response_text = "{: <6}{: ^15}{: >6}\n".format("Linea", "Destino", "Salida")
# try:
times = 7
# Prevent massive departures in text
if (response['departures'].__len__() < times):
times = response['departures'].__len__()
for i in range(times):
n = str(response['departures'][i]['route_id'])
d = str(response['departures'][i]['destination'])
d_trunk = d[:14] + (d[14:] and '.') # Prevent a big headsign
is_live = response['departures'][i]['is_live']
a = str(response['departures'][i]['arrival'])
if is_live:
a = str(a//60) + ' min.'
else:
a = a.split('T')[-1].split('+')[0].split(':00')[0] # hh:mm
response_text += '{: <6}{: <15}{: >6}\n'.format(n, d_trunk, a)
# except:
# pass
return '```\n' + response_text + '```'
# Initializing listener
bot.set_update_listener(listener)
####################
# Bot handlers #####
####################
bus_fav = re.compile(r'(/)(fav)( )(\d\d\d?\d?)')
@bot.message_handler(func=lambda m: bus_fav.search(str(m.text)))
def tiempoDeEspera_fav__lambda(m):
uid = m.chat.id
idStop = bus_fav.search(m.text).group(4)
add_fav_bus_stop(uid, str(idStop))
response = "Parada añadida a favoritas."
bot.send_message(m.chat.id, response)
@bot.message_handler(commands=['favoritas'])
def list_fav(m):
uid = m.chat.id
stations = get_fav_stations(str(uid))
response = "Estas son tus paradas favoritas"
markup = types.InlineKeyboardMarkup()
for i in range(stations.__len__()):
idStop = str(stations[i])
callback = "favStop|" + idStop
stop = types.InlineKeyboardButton(text=idStop,
callback_data=callback)
markup.add(stop)
bot.send_message(m.chat.id, response, reply_markup=markup)
callback_fav_stop = re.compile(r'(fav)')
@bot.callback_query_handler(func=lambda m: callback_fav_stop.search(str(m.data)))
def call_fav_stop(call):
idStop = str(call.data).split('|')[-1]
markup = types.InlineKeyboardMarkup()
actualizar = types.InlineKeyboardButton(text='Actualizar',
callback_data='rst|' + str(idStop))
markup.add(actualizar)
bot.send_message(call.message.chat.id, format_bus_stop_time(idStop),
parse_mode="Markdown", reply_markup=markup)
@bot.message_handler(commands=['help', 'start'])
def help(message):
bot.reply_to(message, help_text)
@bot.message_handler(func=lambda message: True, content_types=['location'])
def set_location(message):
user = str(message.chat.id)
loc = {}
loc['lat'] = message.location.latitude
loc['lon'] = message.location.longitude
location[user] = loc
print(location[user])
espera = re.compile(r'(/)(\d\d\d?\d?)')
@bot.message_handler(func=lambda m: espera.search(str(m.text)))
def tiempoDeEspera_lambda(m):
idStop = espera.search(m.text).group(2)
markup = types.InlineKeyboardMarkup()
actualizar = types.InlineKeyboardButton(text='Actualizar',
callback_data='rst|' + str(idStop))
markup.add(actualizar)
bot.send_message(m.chat.id, format_bus_stop_time(idStop),
parse_mode="Markdown", reply_markup=markup)
update_bus_stop = re.compile(r'(rst)')
@bot.callback_query_handler(func=lambda call: update_bus_stop.search(str(call.data)))
def callback_update_stop_time(call):
idStop = call.data.split('|')[1]
markup = types.InlineKeyboardMarkup()
callback_data = 'rst|' + str(idStop)
actualizar = types.InlineKeyboardButton(text='Actualizar',
callback_data=callback_data)
markup.add(actualizar)
now = str(datetime.datetime.now()).split(' ')[-1].split('.')[0]
message = format_bus_stop_time(idStop) + '_' + now + '_'
bot.edit_message_text(text=message,
chat_id=call.message.chat.id,
message_id=call.message.message_id,
parse_mode="Markdown",
reply_markup=markup)
@bot.message_handler(commands=['tiempoDeEspera', 't'])
def tiempoDeEspera(m):
idStop = m.text.split(' ')[-1]
markup = types.InlineKeyboardMarkup()
actualizar = types.InlineKeyboardButton(text='Actualizar',
callback_data='rst' + idStop)
markup.add(actualizar)
bot.send_message(m.chat.id,
format_bus_stop_time(idStop),
reply_markup=markup)
@bot.callback_query_handler(func=lambda call: call.data.split(',')[0] == 'uca')
def callback_raildepartures(call):
idStop = call.data.split(',')[-1]
markup = types.InlineKeyboardMarkup()
actualizar = types.InlineKeyboardButton(text='Actualizar',
callback_data='uca,' + str(idStop))
markup.add(actualizar)
bot.edit_message_text(format_raildepartures(idStop),
chat_id=call.message.chat.id,
message_id=call.message.message_id,
parse_mode="Markdown",
reply_markup=markup)
# CERCANIAS
@bot.message_handler(commands=['cerca']) # Tiempo de espera de cercanias
def nearby(m):
user = str(m.chat.id)
if not str(user) in location:
response = "Por favor, comparte tu ubicación conmigo y después pregúntame de nuevo:\n /cerca"
bot.send_message(m.chat.id, response)
return
lat = str(location[user]['lat'])
lon = str(location[user]['lon'])
request = lat + ',' + lon
near = madCercanias.nearby(request)
response = "Elige la estación de Cercanías"
markup = types.InlineKeyboardMarkup()
for i in range(near['railstations'].__len__()):
station = near['railstations'][i]
callback = 'cerca|' + user + '|' + station['id']
button = types.InlineKeyboardButton(text=station['name'],
callback_data=callback)
markup.add(button)
bot.send_message(m.chat.id, response, reply_markup=markup)
@bot.callback_query_handler(func=lambda call: call.data.split('|')[0] == 'cerca')
def callback_nearby(m):
user = m.data.split('|')[1]
idStop = m.data.split('|')[-1]
bot.send_message(user,
format_raildepartures(idStop),
parse_mode="Markdown")
@bot.message_handler(commands=['cercanias', 'c']) # Tiempo de espera de cercanias
def cercanias_departures(m):
idStop = m.text.split(' ')[-1]
markup = types.InlineKeyboardMarkup()
actualizar = types.InlineKeyboardButton(text='Actualizar',
callback_data='uca|' + idStop)
# uca = update cercanias arrivals
markup.add(actualizar)
bot.send_message(m.chat.id,
format_raildepartures(idStop),
parse_mode="Markdown",
reply_markup=markup)
@bot.message_handler(commands=['whereami'])
def whereiam(m):
teclado = types.ReplyKeyboardMarkup(one_time_keyboard=True,
resize_keyboard=True)
itemLoc = types.KeyboardButton("Compartir mi localización",
request_location=True)
teclado.row(itemLoc)
bot.send_message(m.chat.id, location_text, reply_markup=teclado)
@bot.message_handler(commands=['route'])
def route(m):
with open("./dataBot/testRoute.json", "r") as route:
route = json.load(route)
i = 1
step = 'Paso ' + str(i)
indicacion = route[step]
markup = types.InlineKeyboardMarkup()
izquierda = types.InlineKeyboardButton(text="<<",
callback_data="<<, " + str(i-1))
derecha = types.InlineKeyboardButton(text=">>",
callback_data=">>, " + str(i+1))
markup.add(izquierda, derecha)
bot.send_message(m.chat.id, indicacion, reply_markup=markup)
@bot.callback_query_handler(func=lambda call:
(call.data.split(',')[0] == "<<") or
(call.data.split(', ')[0] == ">>"))
def callback_route(call):
with open("./dataBot/testRoute.json", "r") as route:
route = json.load(route)
i = int(call.data.split(', ')[1])
step = 'Paso ' + str(i)
indicacion = route[step]
markup = types.InlineKeyboardMarkup()
izquierda = types.InlineKeyboardButton(text="<<",
callback_data="<<, " +
str((i) % 3 + 1))
derecha = types.InlineKeyboardButton(text=">>",
callback_data=">>, " +
str((i) % 3 + 1))
markup.add(izquierda, derecha)
bot.edit_message_text(indicacion, chat_id=call.message.chat.id,
message_id=call.message.message_id,
reply_markup=markup)
@bot.message_handler(commands=['location'])
def send_location(m):
lat = 40.4101932
lon = - 3.7391411,
bot.send_location(m.chat.id, lat, lon)
@bot.message_handler(commands=['update'])
def auto_update(message):
if isAdmin_fromPrivate(message):
bot.reply_to(message,
"Reiniciando..")
print("Updating..")
exit()
else:
pass
bot.skip_pending = True
print("Running...")
bot.polling()