-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsupportmethods.py
1565 lines (1447 loc) · 84.4 KB
/
supportmethods.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Detective Yellowcopyrightedrat - A Telegram bot to organize Pokémon GO raids
# Copyright (C) 2017 Jorge Suárez de Lis <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import re
from datetime import datetime, timedelta, date
from pytz import timezone
import time
import html
import logging
from threading import Thread
import telegram
from telegram import ChatAction, InlineKeyboardButton, InlineKeyboardMarkup
from Levenshtein import distance
import cv2
import tempfile
import os, sys
import numpy as np
import pytesseract
from PIL import Image, ImageOps
from skimage.measure import compare_ssim as ssim
from unidecode import unidecode
import googlemaps
import math
import gettext
from config import config
from storagemethods import getRaidbyMessage, getCreadorRaid, getRaidPeople, getRaid, getAlertsByPlace, getGroup, getZones, updateRaidsStatus, updateValidationsStatus, getPlace, getAutorefloatGroups, getActiveRaidsforGroup, saveRaid, updateLastAutorefloat, savePlace, getGroupTimezoneOffsetFromServer, getCurrentPokemons, getCurrentGyms, removeIncompleteRaids, getAutorankingGroups, getRanking, getCachedRanking, saveCachedRanking, getUser
from telegram.error import (TelegramError, Unauthorized, BadRequest, TimedOut, ChatMigrated, NetworkError)
pokemonlist = ['Bulbasaur','Ivysaur','Venusaur','Charmander','Charmeleon','Charizard','Squirtle','Wartortle','Blastoise','Caterpie','Metapod','Butterfree','Weedle','Kakuna','Beedrill','Pidgey','Pidgeotto','Pidgeot','Rattata','Raticate','Spearow','Fearow','Ekans','Arbok','Pikachu','Raichu','Sandshrew','Sandslash','Nidoran♀','Nidorina','Nidoqueen','Nidoran♂','Nidorino','Nidoking','Clefairy','Clefable','Vulpix','Ninetales','Jigglypuff','Wigglytuff','Zubat','Golbat','Oddish','Gloom','Vileplume','Paras','Parasect','Venonat','Venomoth','Diglett','Dugtrio','Meowth','Persian','Psyduck','Golduck','Mankey','Primeape','Growlithe','Arcanine','Poliwag','Poliwhirl','Poliwrath','Abra','Kadabra','Alakazam','Machop','Machoke','Machamp','Bellsprout','Weepinbell','Victreebel','Tentacool','Tentacruel','Geodude','Graveler','Golem','Ponyta','Rapidash','Slowpoke','Slowbro','Magnemite','Magneton','Farfetch\'d','Doduo','Dodrio','Seel','Dewgong','Grimer','Muk','Shellder','Cloyster','Gastly','Haunter','Gengar','Onix','Drowzee','Hypno','Krabby','Kingler','Voltorb','Electrode','Exeggcute','Exeggutor','Cubone','Marowak','Hitmonlee','Hitmonchan','Lickitung','Koffing','Weezing','Rhyhorn','Rhydon','Chansey','Tangela','Kangaskhan','Horsea','Seadra','Goldeen','Seaking','Staryu','Starmie','Mr.Mime','Scyther','Jynx','Electabuzz','Magmar','Pinsir','Tauros','Magikarp','Gyarados','Lapras','Ditto','Eevee','Vaporeon','Jolteon','Flareon','Porygon','Omanyte','Omastar','Kabuto','Kabutops','Aerodactyl','Snorlax','Articuno','Zapdos','Moltres','Dratini','Dragonair','Dragonite','Mewtwo','Mew','Chikorita','Bayleef','Meganium','Cyndaquil','Quilava','Typhlosion','Totodile','Croconaw','Feraligatr','Sentret','Furret','Hoothoot','Noctowl','Ledyba','Ledian','Spinarak','Ariados','Crobat','Chinchou','Lanturn','Pichu','Cleffa','Igglybuff','Togepi','Togetic','Natu','Xatu','Mareep','Flaaffy','Ampharos','Bellossom','Marill','Azumarill','Sudowoodo','Politoed','Hoppip','Skiploom','Jumpluff','Aipom','Sunkern','Sunflora','Yanma','Wooper','Quagsire','Espeon','Umbreon','Murkrow','Slowking','Misdreavus','Unown','Wobbuffet','Girafarig','Pineco','Forretress','Dunsparce','Gligar','Steelix','Snubbull','Granbull','Qwilfish','Scizor','Shuckle','Heracross','Sneasel','Teddiursa','Ursaring','Slugma','Magcargo','Swinub','Piloswine','Corsola','Remoraid','Octillery','Delibird','Mantine','Skarmory','Houndour','Houndoom','Kingdra','Phanpy','Donphan','Porygon2','Stantler','Smeargle','Tyrogue','Hitmontop','Smoochum','Elekid','Magby','Miltank','Blissey','Raikou','Entei','Suicune','Larvitar','Pupitar','Tyranitar','Lugia','Ho-Oh','Celebi','Treecko','Grovyle','Sceptile','Torchic','Combusken','Blaziken','Mudkip','Marshtomp','Swampert','Poochyena','Mightyena','Zigzagoon','Linoone','Wurmple','Silcoon','Beautifly','Cascoon','Dustox','Lotad','Lombre','Ludicolo','Seedot','Nuzleaf','Shiftry','Taillow','Swellow','Wingull','Pelipper','Ralts','Kirlia','Gardevoir','Surskit','Masquerain','Shroomish','Breloom','Slakoth','Vigoroth','Slaking','Nincada','Ninjask','Shedinja','Whismur','Loudred','Exploud','Makuhita','Hariyama','Azurill','Nosepass','Skitty','Delcatty','Sableye','Mawile','Aron','Lairon','Aggron','Meditite','Medicham','Electrike','Manectric','Plusle','Minun','Volbeat','Illumise','Roselia','Gulpin','Swalot','Carvanha','Sharpedo','Wailmer','Wailord','Numel','Camerupt','Torkoal','Spoink','Grumpig','Spinda','Trapinch','Vibrava','Flygon','Cacnea','Cacturne','Swablu','Altaria','Zangoose','Seviper','Lunatone','Solrock','Barboach','Whiscash','Corphish','Crawdaunt','Baltoy','Claydol','Lileep','Cradily','Anorith','Armaldo','Feebas','Milotic','Castform','Kecleon','Shuppet','Banette','Duskull','Dusclops','Tropius','Chimecho','Absol','Wynaut','Snorunt','Glalie','Spheal','Sealeo','Walrein','Clamperl','Huntail','Gorebyss','Relicanth','Luvdisc','Bagon','Shelgon','Salamence','Beldum','Metang','Metagross','Regirock','Regice','Registeel','Latias','Latios','Kyogre','Groudon','Rayquaza','Jirachi','Deoxys']
egglist = ['N1','N2','N3','N4','N5','EX']
iconthemes = [
{ "Rojo": "🔥", "Azul": "❄️", "Amarillo": "⚡️" },
{ "Rojo": "🔴", "Azul": "🔵", "Amarillo": "🌕" },
{ "Rojo": "❤", "Azul": "💙", "Amarillo": "💛" },
{ "Rojo": "🔴", "Azul": "🔵", "Amarillo": "🔶" },
{ "Rojo": "♨️", "Azul": "🌀", "Amarillo": "🔆" },
{ "Rojo": "🦊", "Azul": "🐳", "Amarillo": "🐥" }
]
validation_pokemons = ["chikorita", "machop", "growlithe", "diglett", "spinarak", "ditto", "teddiursa", "cubone", "sentret", "voltorb", "zigzagoon", "gulpin", "jigglypuff"]
validation_profiles = ["model1", "model2", "model3", "model4", "model5", "model6"]
validation_names = ["Calabaza", "Puerro", "Cebolleta", "Remolacha", "Aceituna", "Pimiento", "Zanahoria", "Tomate", "Guisante", "Coliflor", "Pepino", "Berenjena", "Perejil", "Batata", "Aguacate", "Alcaparra", "Escarola", "Lechuga", "Hinojo"]
def is_admin(chat_id, user_id, bot):
is_admin = False
for admin in bot.get_chat_administrators(chat_id):
if user_id == admin.user.id:
is_admin = True
return is_admin
def extract_update_info(update):
logging.debug("supportmethods:extract_update_info")
try:
message = update.message
except:
message = update.channel_post
if message is None:
message = update.channel_post
text = message.text
try:
user_id = message.from_user.id
except:
user_id = None
chat_id = message.chat.id
chat_type = message.chat.type
return (chat_id, chat_type, user_id, text, message)
def send_message_timed(chat_id, text, sleep_time, bot, reply_markup=None):
logging.debug("supportmethods:send_message_timed: %s %s %s %s" % (chat_id, text, sleep_time, bot))
time.sleep(sleep_time)
bot.sendMessage(chat_id=chat_id, text=text, reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN)
def delete_message_timed(chat_id, message_id, sleep_time, bot):
time.sleep(sleep_time)
delete_message(chat_id, message_id, bot)
def delete_message(chat_id, message_id, bot):
try:
bot.deleteMessage(chat_id=chat_id,message_id=message_id)
return True
except:
return False
def count_people(gente):
count = 0
if gente is not None:
for user in gente:
if user["novoy"] > 0:
continue
count = count + 1
if (user["plus"] is not None and user["plus"]>0) or\
(user["plusb"] is not None and user["plusb"]>0) or\
(user["plusy"] is not None and user["plusy"]>0) or\
(user["plusr"] is not None and user["plusr"]>0):
count = count + user["plus"] + user["plusr"] + user["plusy"] + user["plusb"]
return count
def count_people_disaggregated(gente):
numrojos = 0
numazules = 0
numamarillos = 0
numotros = 0
count = 0
if gente is not None:
for user in gente:
if user["novoy"] > 0:
continue
count = count + 1
if user["plus"] is not None and user["plus"] > 0:
count = count + user["plus"]
numotros = numotros + user["plus"]
if user["plusr"] is not None and user["plusr"] > 0:
count = count + user["plusr"]
numrojos = numrojos + user["plusr"]
if user["plusb"] is not None and user["plusb"] > 0:
count = count + user["plusb"]
numazules = numazules + user["plusb"]
if user["plusy"] is not None and user["plusy"] > 0:
count = count + user["plusy"]
numamarillos = numamarillos + user["plusy"]
if user["team"] == "Rojo":
numrojos = numrojos + 1
elif user["team"] == "Azul":
numazules = numazules + 1
elif user["team"] == "Amarillo":
numamarillos = numamarillos + 1
else:
numotros = numotros + 1
return (numazules, numrojos, numamarillos, numotros, count)
def send_alerts_delayed(raid, bot):
time.sleep(2)
send_alerts(raid, bot)
def send_alerts(raid, bot):
logging.debug("supportmethods:send_alerts: %s" % (raid))
alerts = getAlertsByPlace(raid["gimnasio_id"])
group = getGroup(raid["grupo_id"])
if group["alerts"] == 1:
what_text = format_text_pokemon(raid["pokemon"], raid["egg"], "html", langfunc=_)
what_day = format_text_day(raid["timeraid"], group["timezone"], langfunc=_)
if group["alias"] is not None:
incursion_text = "<a href='https://t.me/%s/%s'>incursión</a>" % (group["alias"], raid["message"])
group_text = "<a href='https://t.me/%s'>%s</a>" % (group["alias"], html.escape(group["title"]))
else:
incursion_text = "incursión"
try:
group_text = "<i>%s</i>" % (html.escape(group["title"]))
except:
group_text = "<i>(Grupo sin nombre guardado)</i>"
logging.debug("supportmethods:send_alerts: Sending %i alerts" % len(alerts))
for alert in alerts:
logging.debug("supportmethods:send_alerts: Sending alert %s" % alert)
try:
bot.sendMessage(chat_id=alert["user_id"], text="🔔 Se ha creado una %s %s en <b>%s</b> %sa las <b>%s</b> en el grupo %s.\n\n<i>Recibes esta alerta porque has activado las alertas para ese gimnasio. Si no deseas recibir más alertas, puedes usar el comando</i> <code>/clearalerts</code>" % (incursion_text, what_text, raid["gimnasio_text"], what_day, extract_time(raid["timeraid"]), group_text), parse_mode=telegram.ParseMode.HTML, disable_web_page_preview=True)
except:
logging.debug("supportmethods:send_alerts: Error sending alert %s" % alert)
def update_message(chat_id, message_id, reply_markup, bot):
logging.debug("supportmethods:update_message: %s %s %s" % (chat_id, message_id, reply_markup))
raid = getRaidbyMessage(chat_id, message_id)
text = format_message(raid)
return bot.edit_message_text(text=text, chat_id=chat_id, message_id=message_id, reply_markup=reply_markup, parse_mode=telegram.ParseMode.HTML, disable_web_page_preview=True, timeout=8)
def format_gym_emojis(tags):
logging.debug("supportmethods:format_gym_emojis: %s" % tags)
tags_emojis = ""
for t in tags:
if unidecode(t).lower() == "jardin":
tags_emojis = tags_emojis + "🌷"
if unidecode(t).lower() == "parque":
tags_emojis = tags_emojis + "🌳"
if unidecode(t).lower() == "juegos":
tags_emojis = tags_emojis + "⚽️"
if unidecode(t).lower() in ["hierba","campo"]:
tags_emojis = tags_emojis + "🌱"
if unidecode(t).lower() == "patrocinado":
tags_emojis = tags_emojis + "💵"
if unidecode(t).lower() == "ex":
tags_emojis = tags_emojis + "🌟"
return tags_emojis
def fetch_gym_address(gym):
logging.debug("supportmethods:fetch_gym_address %s" % gym["id"])
try:
gmaps = googlemaps.Client(key=config["googlemaps"]["key"], retry_timeout=3)
reverse_geocode_result = gmaps.reverse_geocode((gym["latitude"], gym["longitude"]))
address = reverse_geocode_result[0]["formatted_address"]
gym["address"] = address
savePlace(gym)
except:
logging.debug("detectivepikachubot:raidbutton:ubicacion Error fetching address! Key limit reached?")
gym["address"] = "-"
return gym
def format_message(raid):
logging.debug("supportmethods:format_message: %s" % (raid))
creador = getCreadorRaid(raid["id"])
group = getGroup(raid["grupo_id"])
icons = iconthemes[group["icontheme"]]
ordering = "addedtime" if group["listorder"] == 0 else "teamlevel"
gente = getRaidPeople(raid["id"], ordering)
_ = set_language(group["language"])
if "edited" in raid.keys() and raid["edited"]>0:
text_edited = " " + _("<em>(editada)</em>")
else:
text_edited = ""
if "refloated" in raid.keys() and raid["refloated"]>0:
text_refloated = " " +_("<em>(reflotada)</em>")
else:
text_refloated = ""
if "timeend" in raid.keys() and raid["timeend"] is not None:
t = extract_time(raid["timeend"], group["timeformat"])
raidend_near = raidend_is_near_raidtime(raid["timeraid"], raid["timeend"], group["timezone"])
timeend_warn = "⚠️" if raidend_near >= 0 else ""
text_endtime = "\n" + timeend_warn + _("<em>Desaparece a las {0}</em>").format(t)
else:
timeend_warn = ""
text_endtime = ""
if group["locations"] == 1:
if "gimnasio_id" in raid.keys() and raid["gimnasio_id"] is not None:
gym_emoji="🌎"
place = getPlace(raid["gimnasio_id"])
if place["tags"] is not None:
tags_emojis = format_gym_emojis(place["tags"])
if len(tags_emojis) > 0:
gym_emoji = tags_emojis
else:
gym_emoji="❓"
else:
gym_emoji=""
what_text = format_text_pokemon(raid["pokemon"], raid["egg"], "html", langfunc=_)
what_day = format_text_day(raid["timeraid"], group["timezone"], "html", langfunc=_)
if creador["username"] is not None:
if creador["trainername"] is not None:
created_text = "\n" + _("Creada por <a href='https://t.me/{0}'>{1}</a>{2}{3}").format(creador["username"], creador["trainername"], text_edited, text_refloated)
else:
created_text = "\n" + _("Creada por @{0}{1}{2}").format(creador["username"], text_edited, text_refloated)
else:
created_text = ""
text = _("Incursión {0} {1}a las {2}<b>{3}</b> en {4}<b>{5}</b>{6}{7}").format(what_text, what_day, timeend_warn, extract_time(raid["timeraid"], group["timeformat"]), gym_emoji, raid["gimnasio_text"], created_text, text_endtime) + "\n"
if raid["status"] == "cancelled":
text = text + _("❌ <b>Incursión cancelada</b>")
else:
if group["disaggregated"] == 1:
(numazules, numrojos, numamarillos, numotros, numgente) = count_people_disaggregated(gente)
if numotros > 0:
otros_text = "❓%s · " % numotros
else:
otros_text = ""
text = text + "%s%s · %s%s · %s%s · %s👩👩👧👧%s" % (icons["Amarillo"], numamarillos, icons["Azul"], numazules, icons["Rojo"], numrojos, otros_text, numgente)
else:
numgente = count_people(gente)
text = text + _("{0} entrenadores apuntados:").format(numgente)
if raid["status"] != "cancelled" and gente is not None:
diff_hours = getGroupTimezoneOffsetFromServer(group["id"])
for user in gente:
if group["plusdisaggregatedinline"] == 1:
plus_text = ""
if user["team"] == "Rojo":
if user["plusr"] > 0:
plus_text = plus_text + " +%i" % user["plusr"]
if user["plusy"] > 0:
plus_text = plus_text + " %s+%i" % (icons["Amarillo"],user["plusy"])
if user["plusb"] > 0:
plus_text = plus_text + " %s+%i" % (icons["Azul"],user["plusb"])
elif user["team"] == "Azul":
if user["plusb"] > 0:
plus_text = plus_text + " +%i" % user["plusb"]
if user["plusy"] > 0:
plus_text = plus_text + " %s+%i" % (icons["Amarillo"],user["plusy"])
if user["plusr"] > 0:
plus_text = plus_text + " %s+%i" % (icons["Rojo"],user["plusr"])
elif user["team"] == "Amarillo":
if user["plusy"] > 0:
plus_text = plus_text + " +%i" % user["plusy"]
if user["plusb"] > 0:
plus_text = plus_text + " %s+%i" % (icons["Azul"],user["plusb"])
if user["plusr"] > 0:
plus_text = plus_text + " %s+%i" % (icons["Rojo"],user["plusr"])
else:
if user["plusy"] > 0:
plus_text = plus_text + " %s+%i" % (icons["Amarillo"],user["plusy"])
if user["plusb"] > 0:
plus_text = plus_text + " %s+%i" % (icons["Azul"],user["plusb"])
if user["plusr"] > 0:
plus_text = plus_text + " %s+%i" % (icons["Rojo"],user["plusr"])
if user["plus"] > 0:
plus_text = plus_text + " ❓+%i" % user["plus"]
else:
if (user["plus"] is not None and user["plus"]>0) or\
(user["plusb"] is not None and user["plusb"]>0) or\
(user["plusy"] is not None and user["plusy"]>0) or\
(user["plusr"] is not None and user["plusr"]>0):
plus_text = " +%i" % (user["plus"]+user["plusr"]+user["plusb"]+user["plusy"])
else:
plus_text = ""
if user["estoy"] is not None and user["estoy"]>0:
estoy_text = "✅ "
elif user["tarde"] is not None and user["tarde"]>0:
estoy_text = "🕒 "
elif user["novoy"] >0:
estoy_text = "❌ "
else:
estoy_text = "▪️ "
if group["snail"] > 0:
user_addedtime = user["addedtime"].replace(tzinfo=timezone(group["timezone"]))
raid_starttime = raid["timeraid"].replace(tzinfo=timezone(group["timezone"])) - timedelta(minutes=diff_hours*60) - timedelta(minutes=group["snail"])
if user_addedtime > raid_starttime:
lateadded_text = "🐌"
else:
lateadded_text = ""
else:
lateadded_text = ""
if user["lotengo"] == 0:
lotengo_text = "👎"
elif user["lotengo"] == 1:
lotengo_text = "👍"
else:
lotengo_text = ""
if user["level"] is not None and user["team"] is not None:
if user["team"] is not None:
if user["team"]=="Rojo":
team_badge = icons["Rojo"]
elif user["team"]=="Amarillo":
team_badge = icons["Amarillo"]
else:
team_badge = icons["Azul"]
if user["trainername"] is not None:
text = text + "\n%s%s%s <a href='https://t.me/%s'>%s</a>%s%s%s" % (estoy_text,team_badge,user["level"],user["username"],user["trainername"],lateadded_text,lotengo_text,plus_text)
else:
text = text + "\n%s%s%s <a href='https://t.me/%s'>@%s</a>%s%s%s" % (estoy_text,team_badge,user["level"],user["username"],user["username"],lateadded_text,lotengo_text,plus_text)
else:
text = text + "\n%s➖ - - <a href='https://t.me/%s'>@%s</a>%s%s%s" % (estoy_text,user["username"],user["username"],lotengo_text,lateadded_text,plus_text)
return text
def format_text_pokemon(pokemon, egg, format="markdown", langfunc=None):
if langfunc is not None:
_ = langfunc
if pokemon is not None:
what_text = _("de <b>{0}</b>").format(pokemon) if format == "html" else _("de *{0}*").format(pokemon)
else:
if egg == "EX":
what_text = _("<b>🌟EX</b>") if format == "html" else _("*🌟EX*")
else:
what_text = egg.replace("N",_("de <b>nivel") + " ") + "</b>" if format == "html" else egg.replace("N",_("de *nivel") + " ") + "*"
return what_text
def format_text_day(timeraid, tzone, format="markdown", langfunc=None):
logging.debug("supportmethods:format_text_day %s %s" % (timeraid, tzone))
if langfunc is not None:
_ = langfunc
try:
raid_datetime = datetime.strptime(timeraid,"%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone(tzone))
except:
raid_datetime = timeraid.replace(tzinfo=timezone(tzone))
now_datetime = datetime.now(timezone(tzone))
difftime = raid_datetime - now_datetime
if difftime.total_seconds() > (3600*16):
weekdays = [_("lunes"), _("martes"), _("miércoles"), _("jueves"), _("viernes"), _("sábado"), _("domingo")]
what_day = _("el <b>{0} día {1}</b>").format(weekdays[raid_datetime.weekday()], raid_datetime.day) + " " if format == "html" else _("el *{0} día {1}*").format(weekdays[raid_datetime.weekday()], raid_datetime.day) + " "
else:
what_day = ""
return what_day
def format_text_creating(creator, langfunc=None):
logging.debug("supportmethods:format_text_creating");
if langfunc is not None:
_ = langfunc
if creator is not None and creator["username"] is not None:
if creator["trainername"] is not None:
creating_text = _("<a href='https://t.me/{0}'>{1}</a> está creando una incursión...").format(creator["username"], creator["trainername"])
else:
creating_text = _("@{0} está creando una incursión...").format(creator["username"])
else:
creating_text = _("Se está creando una incursión...")
return creating_text
def ensure_escaped(username):
if username.find("_") != -1 and username.find("\\_") == -1:
username = username.replace("_","\\_")
return username
def update_raids_status(bot):
logging.debug("supportmethods:update_raids_status")
raids = updateRaidsStatus()
for raid in raids:
logging.debug(raid)
r = getRaid(raid["id"])
logging.debug("Updating message for raid ID %s" % (raid["id"]))
try:
reply_markup = get_keyboard(r)
group = getGroup(r["grupo_id"])
_ = set_language(group["language"])
updated = update_message(r["grupo_id"], r["message"], reply_markup, bot)
logging.debug(updated)
except Exception as e:
logging.debug("supportmethods:update_raids_status error: %s" % str(e))
time.sleep(0.015)
def update_validations_status(bot):
logging.debug("supportmethods:update_validations_status")
validations = updateValidationsStatus()
for v in validations:
logging.debug(v)
logging.debug("Sending notification for validation ID %s, user ID %s" % (v["id"], v["usuario_id"]))
try:
user = getUser(v["usuario_id"])
_ = set_language(user["language"])
bot.sendMessage(chat_id=v["usuario_id"], text=_("⚠ El proceso de validación pendiente ha caducado porque han pasado 6 horas desde que empezó. Si quieres validarte, debes volver a empezar el proceso."), parse_mode=telegram.ParseMode.MARKDOWN)
except Exception as e:
logging.debug("supportmethods:update_validations_status error: %s" % str(e))
time.sleep(0.015)
def remove_incomplete_raids(bot):
logging.debug("supportmethods:remove_incomplete_raids")
raids = removeIncompleteRaids()
for raid in raids:
logging.debug(raid)
r = getRaid(raid["id"])
logging.debug("Removing message for raid ID %s" % (raid["id"]))
try:
reply_markup = get_keyboard(r)
updated = bot.deleteMessage(chat_id = r["grupo_id"], message_id = r["message"])
except Exception as e:
logging.debug("supportmethods:remove_incomplete_raids error: %s" % str(e))
time.sleep(0.015)
def auto_refloat(bot):
logging.debug("supportmethods:auto_refloat")
groups = getAutorefloatGroups()
for g in groups:
logging.debug("supportmethods:auto_refloat auto refloat group %s %s" % (g["id"],g["title"]))
updateLastAutorefloat(g["id"])
group = getGroup(g["id"])
intwohours_datetime = datetime.now(timezone(group["timezone"])).replace(tzinfo=timezone(group["timezone"])) + timedelta(minutes = 90)
tenminsago_datetime = datetime.now(timezone(group["timezone"])).replace(tzinfo=timezone(group["timezone"])) - timedelta(minutes = 9)
fifminsago_datetime = datetime.now(timezone(group["timezone"])).replace(tzinfo=timezone(group["timezone"])) - timedelta(minutes = 15)
tweminsago_datetime = datetime.now(timezone(group["timezone"])).replace(tzinfo=timezone(group["timezone"])) - timedelta(minutes = 20)
raids = getActiveRaidsforGroup(g["id"])
for raid in raids:
timeraid = raid["timeraid"].replace(tzinfo=timezone(group["timezone"]))
if raid["id"] is not None and raid["status"] != "ended" and timeraid <= intwohours_datetime and (\
(g["refloatauto"] == 5 and timeraid > tenminsago_datetime) or \
(g["refloatauto"] == 10 and timeraid > fifminsago_datetime) or \
(g["refloatauto"] == 15 and timeraid > tweminsago_datetime) or \
g["refloatauto"] == 30):
try:
raid["refloated"] = 1
text = format_message(raid)
reply_markup = get_keyboard(raid)
sent_message = bot.sendMessage(chat_id=raid["grupo_id"], text=text, reply_markup=reply_markup, parse_mode=telegram.ParseMode.HTML, disable_web_page_preview=True)
delete_message_id = raid["message"]
raid["message"] = sent_message.message_id
saveRaid(raid)
logging.debug("supportmethods:auto_refloat: auto reflotada incursión %s mensaje %s" % (raid["id"], raid["message"]))
try:
bot.deleteMessage(chat_id=raid["grupo_id"],message_id=delete_message_id)
except Exception as e:
logging.debug("supportmethods:auto_refloat: error borrando post antiguo %s" % raid["message"])
except:
logging.debug("supportmethods:auto_refloat: error reflotando incursión %s mensaje %s" % (raid["id"], raid["message"]))
time.sleep(1.0)
def auto_ranking(bot):
logging.debug("supportmethods:auto_ranking")
groups = getAutorankingGroups()
logging.debug("supportmethods:auto_ranking testing for %i groups..." % len(groups))
for g in groups:
(lastweek_start, lastweek_end, lastmonth_start, lastmonth_end) = ranking_time_periods(g["timezone"])
if g["rankingweek"] > 0:
logging.debug("supportmethods:auto_ranking testing weekly auto ranking group %s %s" % (g["id"],g["title"]))
rankingtext = getCachedRanking(g["id"], lastweek_start.strftime("%y-%m-%d"), lastweek_end.strftime("%y-%m-%d"))
if rankingtext == None:
logging.debug("supportmethods:auto_ranking [!] publishing weekly auto ranking group %s %s" % (g["id"],g["title"]))
output = ranking_text(g, lastweek_start, lastweek_end, "week")
bot.sendMessage(chat_id=g["id"], text=output, parse_mode=telegram.ParseMode.HTML, disable_web_page_preview=True)
time.sleep(1.0)
if g["rankingmonth"] > 0:
logging.debug("supportmethods:auto_ranking testing monthly auto ranking group %s %s" % (g["id"],g["title"]))
rankingtext = getCachedRanking(g["id"], lastmonth_start.strftime("%y-%m-%d"), lastmonth_end.strftime("%y-%m-%d"))
if rankingtext == None:
logging.debug("supportmethods:auto_ranking [!] publishing monthly auto ranking group %s %s" % (g["id"],g["title"]))
output = ranking_text(g, lastmonth_start, lastmonth_end, "month")
bot.sendMessage(chat_id=g["id"], text=output, parse_mode=telegram.ParseMode.HTML, disable_web_page_preview=True)
time.sleep(1.0)
def ranking_text(group, startdate, enddate, type="week"):
logging.debug("supportmethods:ranking_text")
_ = set_language(group["language"])
# Group name
if group["alias"] is not None:
group_text = "<a href='https://t.me/%s'>%s</a>" % (group["alias"],html.escape(group["title"]))
else:
try:
group_text = "<i>%s</i>" % (html.escape(group["title"]))
except:
group_text = "<i>(Grupo sin nombre guardado)</i>"
# Prepare output
if type == "month":
months = [_("enero"), _("febrero"), _("marzo"), _("abril"), _("mayo"), _("junio"), _("julio"), _("agosto"), _("septiembre"), _("octubre"), _("noviembre"), _("diciembre")]
month_text = "%s" % months[startdate.month-1]
output = _("TOP {0} de participación en incursiones del <b>mes de {1}</b> en {2}").format(group["rankingmonth"], month_text, group_text)
maxposition = group["rankingmonth"]
else:
daymonth_text = "%s/%s" % (startdate.day, startdate.month)
output = _("TOP {0} de participación en incursiones de la <b>semana del {1}</b> en {2}").format(group["rankingweek"], daymonth_text, group_text)
maxposition = group["rankingweek"]
position = 0
counter = 0
lastraidno = 0
medallas = ["🥇","🥈","🥉"]
icons = iconthemes[group["icontheme"]]
# Try to get cached ranking from database
rankingtext = getCachedRanking(group["id"], startdate.strftime("%y-%m-%d"), enddate.strftime("%y-%m-%d"))
if rankingtext is None:
logging.debug("detectivepikachubot:stats: No cached ranking found, forging a new one")
groupstats_lastmonth = getRanking(group["id"], startdate, enddate)
rankingtext = ""
logging.debug(groupstats_lastmonth)
for gs in groupstats_lastmonth:
counter = counter + 1
if gs["incursiones"] != lastraidno:
position = counter
if position > maxposition:
break
lastraidno = gs["incursiones"]
trainername = gs["trainername"] if gs["trainername"] is not None else "@%s" % gs["username"]
user_text = "<a href='https://t.me/%s'>%s</a>" % (gs["username"], trainername)
medalla_text = "" if position > 3 else " %s" % medallas[position-1]
rankingtext = rankingtext + "\n %s. %s %s (%s)%s" % (position, icons[gs["team"]], user_text, gs["incursiones"], medalla_text)
saveCachedRanking(group["id"], startdate.strftime("%y-%m-%d"), enddate.strftime("%y-%m-%d"), rankingtext)
output = output + rankingtext
return output
def error_callback(bot, update, error):
try:
raise error
except Unauthorized:
logging.debug("TELEGRAM ERROR: Unauthorized - %s" % error)
except BadRequest:
logging.debug("TELEGRAM ERROR: Bad Request - %s" % error)
except TimedOut:
logging.debug("TELEGRAM ERROR: Slow connection problem - %s" % error)
except NetworkError:
logging.debug("TELEGRAM ERROR: Other connection problems - %s" % error)
except ChatMigrated as e:
logging.debug("TELEGRAM ERROR: Chat ID migrated?! - %s" % error)
except TelegramError:
logging.debug("TELEGRAM ERROR: Other error - %s" % error)
except:
logging.debug("TELEGRAM ERROR: Unknown - %s" % error)
def send_edit_instructions(group, raid, user, bot):
user_id = user["id"]
_ = set_language(user["language"])
what_text = format_text_pokemon(raid["pokemon"], raid["egg"], langfunc=_)
what_day = format_text_day(raid["timeraid"], group["timezone"], langfunc=_)
day = extract_day(raid["timeraid"], group["timezone"])
if group["refloat"] == 1 or is_admin(raid["grupo_id"], user_id, bot):
text_refloat="\n" + _("🎈 *Reflotar incursión*: `/refloat`")
else:
text_refloat=""
if group["candelete"] == 1 or is_admin(raid["grupo_id"], user_id, bot):
text_delete="\n" + _("❌ *Borrar incursión*: `/delete`")
else:
text_delete=""
if raid["timeend"] is not None:
text_endtime = extract_time(raid["timeend"])
else:
text_endtime = extract_time(raid["timeraid"])
if day is None:
daystr = ""
else:
daystr = "%s/" % day
if raid["pokemon"] is None:
pokemon = raid["egg"]
else:
pokemon = raid["pokemon"]
try:
bot.send_message(chat_id=user_id, text=_("Puedes editar la incursión {0} {1}a las *{2}* en *{3}* (identificador `{4}`) contestando al mensaje de la incursión con los siguientes comandos:\n\n🕒 *Día/hora*: `/time {5}{6}`\n🕒 *Hora a la que desaparece*: `/endtime {7}`\n🌎 *Gimnasio*: `/gym {8}`\n👿 *Pokémon/nivel*: `/pokemon {9}`\n\n🚫 *Cancelar incursión*: `/cancel`{10}{11}").format(what_text, what_day, extract_time(raid["timeraid"]), raid["gimnasio_text"], raid["id"], daystr, extract_time(raid["timeraid"]), text_endtime, raid["gimnasio_text"], pokemon, text_delete, text_refloat), parse_mode=telegram.ParseMode.MARKDOWN)
except:
logging.debug("Error sending instructions in private. Maybe conversation not started?")
def warn_people(warntype, raid, user, chat_id, bot):
logging.debug("supportmethods:warn_people")
people = getRaidPeople(raid["id"])
group = getGroup(raid["grupo_id"])
warned = []
notwarned = []
if people is None:
return
for p in people:
_ = set_language(p["language"])
if p["username"] == user["username"] or p["novoy"] > 0:
continue
if group["alias"] is not None:
incursion_text = _("<a href='https://t.me/{0}/{1}'>incursión</a>").format(group["alias"], raid["message"])
else:
incursion_text = _("incursión")
try:
if user is not None and user["username"] is not None:
user_text = "@%s" % user["username"]
else:
user_text = _("Se")
if warntype == "cancel":
text_pokemon = format_text_pokemon(raid["pokemon"], raid["egg"], "html", langfunc=_)
text = _("❌ {0} ha <b>cancelado</b> la {1} {2} a las {3} en {4}").format(user_text, incursion_text, text_pokemon, extract_time(raid["timeraid"]), raid["gimnasio_text"])
elif warntype == "uncancel":
text_pokemon = format_text_pokemon(raid["pokemon"], raid["egg"], "html", langfunc=_)
text = _("⚠️ {0} ha <b>descancelado</b> la {1} {2} a las {3} en {4}").format(user_text, incursion_text, text_pokemon, extract_time(raid["timeraid"]), raid["gimnasio_text"])
elif warntype == "delete":
text_pokemon = format_text_pokemon(raid["pokemon"], raid["egg"], "html", langfunc=_)
text = _("🚫 {0} ha <b>borrado</b> la incursión {1} a las {2} en {3}").format(user_text, text_pokemon, extract_time(raid["timeraid"]), raid["gimnasio_text"])
elif warntype == "time":
text_day = format_text_day(raid["timeraid"], group["timezone"], "html", langfunc=_)
if text_day != "":
text_day = " " + text_day
text_pokemon = format_text_pokemon(raid["pokemon"], raid["egg"], "html", langfunc=_)
text = _("⚠️ {0} ha cambiado la hora de la {1} {2} en {3} para las <b>{4}</b>{5}").format(user_text, incursion_text, text_pokemon, raid["gimnasio_text"], extract_time(raid["timeraid"]), text_day)
elif warntype == "endtime":
text_pokemon = format_text_pokemon(raid["pokemon"], raid["egg"], "html", langfunc=_)
text = _("⚠️ {0} ha cambiado la hora a la que se termina la {1} {2} en {3} a las <b>{4}</b> (¡ojo, la incursión sigue programada para la misma hora: {5}!)").format(user_text, incursion_text, text_pokemon, raid["gimnasio_text"], extract_time(raid["timeend"]), extract_time(raid["timeraid"]))
elif warntype == "deleteendtime":
text = _("⚠️ {0} ha borrado la hora a la que se termina la {1} {2} en {3} (¡ojo, la incursión sigue programada para la misma hora: {4}!)").format(user_text, incursion_text, raid["pokemon"], raid["gimnasio_text"], extract_time(raid["timeraid"]))
elif warntype == "gym":
text_pokemon = format_text_pokemon(raid["pokemon"], raid["egg"], "html", langfunc=_)
text = _("⚠️ {0} ha cambiado el gimnasio de la {1} {2} para las {3} a <b>{4}</b>").format(user_text, incursion_text, text_pokemon, extract_time(raid["timeraid"]), raid["gimnasio_text"])
elif warntype == "pokemon":
text_pokemon = format_text_pokemon(raid["pokemon"], raid["egg"], "html", langfunc=_)
text = _("⚠️ {0} ha cambiado la {1} para las {2} en {3} a incursión {4}").format(user_text, incursion_text, extract_time(raid["timeraid"]), raid["gimnasio_text"], text_pokemon)
bot.sendMessage(chat_id=p["id"], text=text, parse_mode=telegram.ParseMode.HTML, disable_web_page_preview=True)
warned.append(p["username"])
except Exception as e:
logging.debug("supportmethods:warn_people error sending message to %s: %s" % (p["username"],str(e)))
notwarned.append(p["username"])
_ = set_language(user["language"])
if len(warned)>0:
warned_text = "@" + ", @".join(warned)
bot.sendMessage(chat_id=chat_id, text=_("He avisado por privado a {0}").format(ensure_escaped(warned_text)), parse_mode=telegram.ParseMode.MARKDOWN)
if len(notwarned)>0:
notwarned_text = "@" + ", @".join(notwarned)
bot.sendMessage(chat_id=chat_id, text=_("No he podido avisar a {0}").format(ensure_escaped(notwarned_text)), parse_mode=telegram.ParseMode.MARKDOWN)
def get_settings_keyboard(chat_id, keyboard="main", langfunc=None):
logging.debug("supportmethods:get_settings_keyboard")
group = getGroup(chat_id)
if langfunc is not None:
_ = langfunc
if group["alerts"] == 1:
alertas_text = "✅ " + _("Permitir configurar alertas")
else:
alertas_text = "▪️ " + _("Permitir configurar alertas")
if group["disaggregated"] == 1:
disaggregated_text = "✅ " + _("Mostrar totales disgregados")
else:
disaggregated_text = "▪️ " + _("Mostrar totales disgregados")
if group["plusdisaggregatedinline"] == 1:
plusdisaggregatedinline_text = "✅ " + _("Mostrar «+1» disgregados por línea")
else:
plusdisaggregatedinline_text = "▪️ " + _("Mostrar «+1» disgregados por línea")
if group["latebutton"] == 1:
latebutton_text = "✅ " + _("Botón «Tardo»")
else:
latebutton_text = "▪️ " + _("Botón «Tardo»")
if group["refloat"] == 1:
refloat_text = "✅ " + _("Reflotar incursiones (comando /refloat)")
else:
refloat_text = "▪️ " + _("Reflotar incursiones (comando /refloat)")
if group["candelete"] == 1:
candelete_text = "✅ " + _("Borrar incursiones (comando /delete)")
else:
candelete_text = "▪️ " + _("Borrar incursiones (comando /delete)")
if group["gotitbuttons"] == 1:
gotitbuttons_text = "✅ " + _("Botones «¡Lo tengo!»")
else:
gotitbuttons_text = "▪️ " + _("Botones «¡Lo tengo!»")
if group["locations"] == 1:
locations_text = "✅ " + _("Ubicaciones")
else:
locations_text = "▪️ " + _("Ubicaciones")
if group["validationrequired"] == 1:
validationrequired_text = "✅ " + _("Validación obligatoria")
else:
validationrequired_text = "▪️ " + _("Validación obligatoria")
if group["gymcommand"] == 1:
gymcommand_text = "✅ " + _("Consultar gimnasios (comando /search)")
else:
gymcommand_text = "▪️ " + _("Consultar gimnasios (comando /search)")
if group["raidcommand"] == 1:
raidcommand_text = "✅ " + _("Crear incursiones (comando /raid)")
else:
raidcommand_text = "▪️ " + _("Crear incursiones (comando /raid)")
if group["raidcommandorder"] == 1:
raidcommandorder_text = "✅ " + _("Ordenar zonas/gimnasios por actividad")
else:
raidcommandorder_text = "▪️ " + _("Ordenar zonas/gimnasios por actividad")
if group["babysitter"] == 1:
babysitter_text = "✅ " + _("Modo niñero (borra mensajes)")
else:
babysitter_text = "▪️ " + _("Modo niñero (borra mensajes)")
if group["timeformat"] == 1:
timeformat_text = "✅ " + _("Mostrar horas en formato AM/PM")
else:
timeformat_text = "▪️ " + _("Mostrar horas en formato AM/PM")
if group["listorder"] == 1:
listorder_text = "✅ " + _("Agrupar apuntados por nivel/equipo")
else:
listorder_text = "▪️ " + _("Agrupar apuntados por nivel/equipo")
if group["plusmax"] == 1:
plusmax_text = "✅ " + _("Botón «+1» (máx. 1 acompañante)")
elif group["plusmax"] in [2,3,5,10]:
plusmax_text = "✅ " + _("Botón «+1» (máx. {0} acompañantes)").format(group["plusmax"])
else:
plusmax_text = "▪️ " + _("Botón «+1»")
if group["plusdisaggregated"] == 1:
plusdisaggregated_text = "✅ " + _("Botón «+1» por cada equipo")
else:
plusdisaggregated_text = "▪️ " + _("Botón «+1» por cada equipo")
if group["snail"] == 1:
snail_text = "✅ " + _("Marcar apuntados tarde (1 minuto)")
elif group["snail"] in [3,5,10]:
snail_text = "✅ " + _("Marcar apuntados tarde ({0} minutos)").format(group["snail"])
else:
snail_text = "▪️ " + _("Marcar apuntados tarde")
if group["refloatauto"] in [5,10,15,30]:
refloatauto_text = "✅ " + _("Reflotar automático ({0} minutos)").format(group["refloatauto"])
else:
refloatauto_text = "▪️ " + _("Reflotar automático")
if group["rankingweek"] in [5,10,15,20,25]:
rankingweek_text = "✅ " + _("Ranking semanal (TOP {0})").format(group["rankingweek"])
else:
rankingweek_text = "▪️ " + _("Ranking semanal")
if group["rankingmonth"] in [15,25,35,50]:
rankingmonth_text = "✅ " + _("Ranking mensual (TOP {0})").format(group["rankingmonth"])
else:
rankingmonth_text = "▪️ " + _("Ranking mensual")
if group["rankingauto"] == 1:
rankingauto_text = "✅ " + _("Publicar automáticamente")
else:
rankingauto_text = "▪️ " + _("Publicar automáticamente")
icons = iconthemes[group["icontheme"]]
icontheme_text = "{0}{1}{2} ".format(icons["Rojo"],icons["Azul"],icons["Amarillo"]) + _("Tema de iconos")
if keyboard == "main":
settings_keyboard = [[InlineKeyboardButton(_("Funcionamiento del grupo/canal »"), callback_data='settings_goto_behaviour')], [InlineKeyboardButton(_("Comandos disponibles para usuarios »"), callback_data='settings_goto_commands')], [InlineKeyboardButton(_("Opciones de vista de incursiones »"), callback_data='settings_goto_raids')], [InlineKeyboardButton(_("Funcionamiento de incursiones »"), callback_data='settings_goto_raidbehaviour')], [InlineKeyboardButton(_("Funcionamiento de rankings »"), callback_data='settings_goto_ranking')], [InlineKeyboardButton(_("Terminado"), callback_data='settings_done')]]
elif keyboard == "behaviour":
settings_keyboard = [[InlineKeyboardButton(locations_text, callback_data='settings_locations')], [InlineKeyboardButton(alertas_text, callback_data='settings_alertas')], [InlineKeyboardButton(babysitter_text, callback_data='settings_babysitter')], [InlineKeyboardButton(validationrequired_text, callback_data='settings_validationrequired')], [InlineKeyboardButton(refloatauto_text, callback_data='settings_refloatauto')], [InlineKeyboardButton(_("« Menú principal"), callback_data='settings_goto_main')]]
elif keyboard == "commands":
settings_keyboard = [[InlineKeyboardButton(gymcommand_text, callback_data='settings_gymcommand')], [InlineKeyboardButton(raidcommand_text, callback_data='settings_raidcommand')], [InlineKeyboardButton(refloat_text, callback_data='settings_reflotar')], [InlineKeyboardButton(candelete_text, callback_data='settings_borrar')], [InlineKeyboardButton(_("« Menú principal"), callback_data='settings_goto_main')]]
elif keyboard == "raidbehaviour":
settings_keyboard = [[InlineKeyboardButton(latebutton_text, callback_data='settings_botonllegotarde')], [InlineKeyboardButton(gotitbuttons_text, callback_data='settings_lotengo')], [InlineKeyboardButton(plusmax_text, callback_data='settings_plusmax')], [InlineKeyboardButton(plusdisaggregated_text, callback_data='settings_plusdisaggregated')], [InlineKeyboardButton(_("« Menú principal"), callback_data='settings_goto_main')]]
elif keyboard == "raids":
settings_keyboard = [[InlineKeyboardButton(disaggregated_text, callback_data='settings_desagregado')], [InlineKeyboardButton(plusdisaggregatedinline_text, callback_data='settings_plusdisaggregatedinline')], [InlineKeyboardButton(timeformat_text, callback_data='settings_timeformat')], [InlineKeyboardButton(icontheme_text, callback_data='settings_icontheme')], [InlineKeyboardButton(listorder_text, callback_data='settings_listorder')], [InlineKeyboardButton(raidcommandorder_text, callback_data='settings_raidcommandorder')], [InlineKeyboardButton(snail_text, callback_data='settings_snail')], [InlineKeyboardButton(_("« Menú principal"), callback_data='settings_goto_main')]]
elif keyboard == "ranking":
settings_keyboard = [[InlineKeyboardButton(rankingweek_text, callback_data='settings_rankingweek')], [InlineKeyboardButton(rankingmonth_text, callback_data='settings_rankingmonth')], [InlineKeyboardButton(rankingauto_text, callback_data='settings_rankingauto')], [InlineKeyboardButton(_("« Menú principal"), callback_data='settings_goto_main')]]
settings_markup = InlineKeyboardMarkup(settings_keyboard)
return settings_markup
def get_pokemons_keyboard(langfunc=None):
logging.debug("supportmethods:get_pokemons_keyboard")
keyboard = []
current_pokemons = getCurrentPokemons()
maxpokes = min(12,len(current_pokemons))
if langfunc is not None:
_ = langfunc
for i in range(0, maxpokes ,3):
keyboard_row = [InlineKeyboardButton(current_pokemons[i]["pokemon"], callback_data="iraid_pokemon_%s" % current_pokemons[i]["pokemon"])]
if i+1 < len(current_pokemons):
keyboard_row.append(InlineKeyboardButton(current_pokemons[i+1]["pokemon"], callback_data="iraid_pokemon_%s" % current_pokemons[i+1]["pokemon"]))
if i+2 < len(current_pokemons):
keyboard_row.append(InlineKeyboardButton(current_pokemons[i+2]["pokemon"], callback_data="iraid_pokemon_%s" % current_pokemons[i+2]["pokemon"]))
keyboard.append(keyboard_row)
keyboard.append([InlineKeyboardButton(_("Niv. 5"), callback_data="iraid_pokemon_N5"), InlineKeyboardButton(_("Niv. 4"), callback_data="iraid_pokemon_N4"), InlineKeyboardButton(_("Niv. 3"), callback_data="iraid_pokemon_N3"), InlineKeyboardButton(_("EX"), callback_data="iraid_pokemon_EX")])
keyboard.append([InlineKeyboardButton(_("Cancelar"), callback_data="iraid_cancel")])
reply_markup = InlineKeyboardMarkup(keyboard)
return reply_markup
def get_gyms_keyboard(group_id, page=0, zone=None, order="activity", langfunc=None):
logging.debug("supportmethods:get_gyms_keyboard %s %s" % (group_id, page))
keyboard = []
current_gyms = getCurrentGyms(group_id, zone, order=order)
maxgyms = min(14*page+13, len(current_gyms))
if langfunc is not None:
_ = langfunc
for i in range(page*14, maxgyms,2):
keyboard_row = [InlineKeyboardButton(current_gyms[i]["name"], callback_data="iraid_gym_%s" % current_gyms[i]["id"])]
if i+1 < len(current_gyms):
keyboard_row.append(InlineKeyboardButton(current_gyms[i+1]["name"], callback_data="iraid_gym_%s" % current_gyms[i+1]["id"]))
keyboard.append(keyboard_row)
if len(current_gyms)>14 and int(page) == 0:
keyboard.append([InlineKeyboardButton("Página 2 >", callback_data="iraid_gyms_page2"), InlineKeyboardButton(_("Cancelar"), callback_data="iraid_cancel")])
elif int(page) > 0:
if len(current_gyms) > 14*(int(page)+1)+1:
keyboard.append([InlineKeyboardButton("< Pág.%s" % str(page), callback_data="iraid_gyms_page%s" % str(page)), InlineKeyboardButton("Pág.%s >" % str(int(page)+2), callback_data="iraid_gyms_page%s" % str(int(page)+2)), InlineKeyboardButton(_("Cancelar"), callback_data="iraid_cancel")])
else:
keyboard.append([InlineKeyboardButton("< Página %s" % str(page), callback_data="iraid_gyms_page%s" % str(page)), InlineKeyboardButton(_("Cancelar"), callback_data="iraid_cancel")])
else:
keyboard.append([InlineKeyboardButton(_("Cancelar"), callback_data="iraid_cancel")])
reply_markup = InlineKeyboardMarkup(keyboard)
return reply_markup
def get_zones_keyboard(group_id, order="activity", langfunc=None):
logging.debug("supportmethods:get_zones_keyboard %s" % (group_id))
keyboard = []
zones = getZones(group_id, order=order)
if langfunc is not None:
_ = langfunc
if len(zones) == 0:
return False
for i in range(0, len(zones), 2):
keyboard_row = [InlineKeyboardButton(zones[i], callback_data="iraid_zone_%s" % zones[i].lower())]
if i+1 < len(zones):
keyboard_row.append(InlineKeyboardButton(zones[i+1], callback_data="iraid_zone_%s" % zones[i+1].lower()))
keyboard.append(keyboard_row)
keyboard.append([InlineKeyboardButton(_("Cancelar"), callback_data="iraid_cancel")])
reply_markup = InlineKeyboardMarkup(keyboard)
return reply_markup
def get_days_keyboard(tz, langfunc=None):
logging.debug("supportmethods:get_days_keyboard")
keyboard = []
if langfunc is not None:
_ = langfunc
basedt = datetime.now(timezone(tz))
minute = math.floor(basedt.minute/10)*10
basedt = basedt.replace(minute=0,hour=0)
dts = []
for x in range(1,13):
dts.append(basedt + timedelta(days=x))
for i in range(0,10,3):
h1 = dts[i].strftime(_('Día %d'))
h1k = dts[i].strftime('%d/00:00')
h2 = dts[i+1].strftime(_('Día %d'))
h2k = dts[i+1].strftime('%d/00:00')
h3 = dts[i+2].strftime(_('Día %d'))
h3k = dts[i+2].strftime('%d/00:00')
keyboard.append([InlineKeyboardButton(h1, callback_data="iraid_date_%s" % h1k), InlineKeyboardButton(h2, callback_data="iraid_date_%s" % h2k), InlineKeyboardButton(h3, callback_data="iraid_date_%s" % h3k)])
keyboard.append([InlineKeyboardButton(_("Cancelar"), callback_data="iraid_cancel")])
reply_markup = InlineKeyboardMarkup(keyboard)
return reply_markup
pass
def get_times_keyboard(tz, date=None, offset=False, langfunc=None):
logging.debug("supportmethods:get_times_keyboard")
keyboard = []
dts = []
if langfunc is not None:
_ = langfunc
nowdt = datetime.now(timezone(tz))
try:
argdt = datetime.strptime(date,"%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone(tz))
except:
date = None
if date == None or argdt.day == nowdt.day:
basedt = nowdt
minute = math.floor(basedt.minute/10)*10
if offset is True:
basedt = basedt.replace(minute=int(minute)+5)
else:
basedt = basedt.replace(minute=int(minute))
for x in range(20,160,10):
dts.append(basedt + timedelta(minutes=x))
if offset == False:
newoffset = 5
else:
newoffset = -5
else:
try:
date = datetime.strptime(date,"%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone(tz))
except:
date = date.replace(tzinfo=timezone(tz))
if offset is True:
basedt = date.replace(hour=9,minute=15)
else:
basedt = date.replace(hour=9,minute=0)
for x in range(30,600,30):
dts.append(basedt + timedelta(minutes=x))
if offset == False:
newoffset = 15
else:
newoffset = -15
for i in range(0,len(dts)-3,3):
h1 = dts[i].strftime('%H:%M')
h1k = dts[i].strftime('%d/%H:%M')
h2 = dts[i+1].strftime('%H:%M')
h2k = dts[i+1].strftime('%d/%H:%M')
h3 = dts[i+2].strftime('%H:%M')
h3k = dts[i+2].strftime('%d/%H:%M')
keyboard.append([InlineKeyboardButton(h1, callback_data="iraid_time_%s" % h1k), InlineKeyboardButton(h2, callback_data="iraid_time_%s" % h2k), InlineKeyboardButton(h3, callback_data="iraid_time_%s" % h3k)])
if newoffset is not False:
if newoffset > 0:
hk = dts[0].strftime("%d/00" + (":" + str(newoffset).zfill(2)))
timechange_text = _("+{0} minutos >").format(newoffset)
else:
hk = dts[0].strftime('%d/00:00')
timechange_text = _("< {0} minutos").format(newoffset)
keyboard.append([InlineKeyboardButton(timechange_text, callback_data="iraid_date_%s" % hk), InlineKeyboardButton(_("Cancelar"), callback_data="iraid_cancel")])
else:
keyboard.append([InlineKeyboardButton(_("Cancelar"), callback_data="iraid_cancel")])
reply_markup = InlineKeyboardMarkup(keyboard)
return reply_markup
def get_endtimes_keyboard(timeraid, offset=False, langfunc=None):
logging.debug("supportmethods:get_endtimes_keyboard")
keyboard = []
dts = []
if langfunc is not None:
_ = langfunc
basedt = timeraid
minute = math.floor(basedt.minute/10)*10
if offset is True:
basedt = basedt.replace(minute=int(minute)+5)
else:
basedt = basedt.replace(minute=int(minute))
for x in range(10,70,5):
dts.append(basedt + timedelta(minutes=x))
if offset == False:
newoffset = 5
else:
newoffset = -5
for i in range(0,len(dts)-3,3):
h1 = dts[i].strftime('%H:%M')
h1k = dts[i].strftime('%d/%H:%M')
h2 = dts[i+1].strftime('%H:%M')
h2k = dts[i+1].strftime('%d/%H:%M')
h3 = dts[i+2].strftime('%H:%M')
h3k = dts[i+2].strftime('%d/%H:%M')
keyboard.append([InlineKeyboardButton(h1, callback_data="iraid_endtime_%s" % h1k), InlineKeyboardButton(h2, callback_data="iraid_endtime_%s" % h2k), InlineKeyboardButton(h3, callback_data="iraid_endtime_%s" % h3k)])
keyboard.append([InlineKeyboardButton(_("No sé / no poner"), callback_data="iraid_endtime_unknown"), InlineKeyboardButton(_("Cancelar"), callback_data="iraid_cancel")])
reply_markup = InlineKeyboardMarkup(keyboard)
return reply_markup
def get_keyboard(raid):
logging.debug("supportmethods:get_keyboard")
global iconthemes
group = getGroup(raid["grupo_id"])
_ = set_language(group["language"])
if raid["status"] == "started" or raid["status"] == "waiting":
icons = iconthemes[group["icontheme"]]
button_voy = InlineKeyboardButton("🙋" + _("Voy"), callback_data='voy')
button_novoy = InlineKeyboardButton("🙅" + _("No voy"), callback_data='novoy')
button_estoy = InlineKeyboardButton("✅" + _("Estoy"), callback_data='estoy')
button_plus = InlineKeyboardButton("👭" + _("+1"), callback_data='plus1')
button_plusy = InlineKeyboardButton(icons["Amarillo"] + _("+1"), callback_data='plus1yellow')
button_plusb = InlineKeyboardButton(icons["Azul"] + _("+1"), callback_data='plus1blue')
button_plusr = InlineKeyboardButton(icons["Rojo"] + _("+1"), callback_data='plus1red')
button_tardo = InlineKeyboardButton("🕒" + _("Tardo"), callback_data='llegotarde')
button_location = InlineKeyboardButton("🌎" + _("Ubicación"), callback_data='ubicacion')
button_loc = InlineKeyboardButton("🌎" + _("Ubi"), callback_data='ubicacion')
if group["plusdisaggregated"] == 0:
keyboard_row1 = [button_voy]
if group["plusmax"] > 0: