-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
1776 lines (1527 loc) · 62.9 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
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
from __future__ import annotations
import json
import logging
import os
import time
import textwrap
import telegram
import asyncio
import re
from peewee import JOIN
from result import Ok, Result
from handlers.inline_keyboard_handlers import InlineKeyboardHandlers
from handlers.payment_handlers import PaymentHandlers
from handlers.start_handlers import start_handlers
from helpers.commands import Command
from helpers.constants import BLANK_ID
from helpers.locks_manager import PollsLockManager
from helpers.message_buillder import MessageBuilder
from logging import handlers as log_handlers
from datetime import datetime
from helpers import strings
from helpers.rcv_tally import RCVTally
from helpers.redis_cache_manager import GetPollWinnerStatus
from tele_helpers import ModifiedTeleUpdate
from helpers.special_votes import SpecialVotes
from bot_middleware import track_errors, admin_only
from database.database import UserID, CallbackContextState
from database.db_helpers import EmptyField, Empty
from handlers.chat_context_handlers import context_handlers, ClosePollContextHandler
from helpers import constants
from telegram import (
Message, ReplyKeyboardMarkup, InlineKeyboardMarkup,
User as TeleUser, Update as BaseTeleUpdate, Bot
)
from telegram.ext import (
ContextTypes, filters, CallbackContext, Application
)
from typing import (
List, Dict, Optional, Sequence, Iterable
)
from helpers.strings import (
POLL_OPTIONS_LIMIT_REACHED_TEXT, READ_SUBSCRIPTION_TIER_FAILED,
generate_poll_created_message
)
from helpers.chat_contexts import (
PollCreationChatContext, PollCreatorTemplate, POLL_MAX_OPTIONS,
VoteChatContext, PaySupportChatContext, ClosePollChatContext
)
from database import (
Users, Polls, PollVoters, UsernameWhitelist,
PollOptions, VoteRankings, db, ChatWhitelist, PollWinners,
MessageContextState, Payments
)
from base_api import BaseAPI, UserRegistrationStatus, CallbackCommands
from tele_helpers import TelegramHelpers
# https://stackoverflow.com/questions/15892946/
# We should empty root.handlers before calling basicConfig() method.
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
LOG_PATH = 'logs/log_events.txt'
os.makedirs(os.path.dirname(LOG_PATH), exist_ok=True)
file_log_handler = log_handlers.TimedRotatingFileHandler(
LOG_PATH, when='W6'
)
file_log_handler.setLevel(logging.WARNING)
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO,
handlers=[logging.StreamHandler(), file_log_handler]
)
logger = logging.getLogger(__name__)
logger.warning("<<< INITIALIZING >>>")
class RankedChoiceBot(BaseAPI):
def __init__(self, config_path='config.yml'):
super().__init__()
self.config_path = config_path
self.scheduled_processes = []
self.payment_handlers = None
self.webhook_url = None
self.bot = None
self.app = None
@classmethod
async def _call_polling_tasks_routine(cls):
# TODO: write tests for this
while True:
await cls._call_polling_tasks_once()
await asyncio.sleep(constants.POLLING_TASKS_INTERVAL)
def get_bot(self) -> Bot:
assert self.bot is not None
return self.bot
@classmethod
async def _call_polling_tasks_once(cls):
print(f'CALLING_CLEANUP @ {datetime.now()}')
Users.prune_deleted_users(logger)
CallbackContextState.prune_expired_contexts()
MessageContextState.prune_expired_contexts()
Payments.prune_expired()
def start_bot(self):
assert self.bot is None
self.bot = self.create_tele_bot()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# ensure scheduled tasks don't crash before running them in background
loop.run_until_complete(self._call_polling_tasks_once())
loop.create_task(self._call_polling_tasks_routine())
builder = self.create_application_builder()
builder.concurrent_updates(constants.MAX_CONCURRENT_UPDATES)
builder.post_init(self.post_init)
self.app = builder.build()
self.payment_handlers = PaymentHandlers(logger)
commands_mapping = {
Command.START: start_handlers.start_handler,
Command.USER_DETAILS: self.user_details_handler,
Command.CHAT_DETAILS: self.chat_details_handler,
Command.CREATE_PRIVATE_POLL: self.create_poll,
Command.CREATE_GROUP_POLL: self.create_group_poll,
Command.REGISTER_USER_ID: self.register_user_by_tele_id,
Command.WHITELIST_CHAT_REGISTRATION:
self.whitelist_chat_registration,
Command.BLACKLIST_CHAT_REGISTRATION:
self.blacklist_chat_registration,
Command.VIEW_POLL: self.view_poll,
Command.VIEW_POLLS: self.view_all_polls,
Command.VOTE: self.vote_for_poll_handler,
Command.POLL_RESULTS: self.fetch_poll_results,
Command.HAS_VOTED: self.has_voted,
Command.CLOSE_POLL: self.close_poll_handler,
Command.VIEW_VOTES: self.view_votes,
Command.VIEW_VOTERS: self.view_poll_voters,
Command.ABOUT: self.show_about,
Command.DELETE_POLL: self.delete_poll,
Command.DELETE_ACCOUNT: self.delete_account,
Command.HELP: self.show_help,
Command.DONE: context_handlers.complete_chat_context,
Command.SET_MAX_VOTERS: self.payment_handlers.set_max_voters,
Command.WHITELIST_USERNAME: self.whitelist_username,
Command.PAY_SUPPORT: self.payment_support_handler,
Command.VOTE_ADMIN: self.vote_for_poll_admin,
Command.CLOSE_POLL_ADMIN: self.close_poll_admin,
Command.UNCLOSE_POLL_ADMIN: self.unclose_poll_admin,
Command.LOOKUP_FROM_USERNAME_ADMIN:
self.lookup_from_username_admin,
Command.INSERT_USER_ADMIN: self.insert_user_admin,
Command.REFUND_ADMIN: self.refund_payment_support_handler,
Command.ENTER_MAINTENANCE_ADMIN: self.enter_maintenance_admin,
Command.EXIT_MAINTENANCE_ADMIN: self.exit_maintenance_admin,
Command.SEND_MSG_ADMIN: self.send_msg_admin
}
# on different commands - answer in Telegram
TelegramHelpers.register_commands(
self.app, commands_mapping=commands_mapping
)
TelegramHelpers.register_pre_checkout_handler(
self.app, self.payment_handlers.pre_checkout_callback
)
# catch-all to handle responses to unknown commands
TelegramHelpers.register_message_handler(
self.app, filters.Regex(r'^/') & filters.COMMAND,
self.handle_unknown_command
)
# handle web app updates
TelegramHelpers.register_message_handler(
self.app, filters.StatusUpdate.WEB_APP_DATA,
self.web_app_handler
)
# handle payment-related messages
TelegramHelpers.register_message_handler(
self.app, filters.SUCCESSFUL_PAYMENT,
self.payment_handlers.successful_payment_callback
)
# catch-all to handle all other messages
TelegramHelpers.register_message_handler(
self.app, filters.Regex(r'.*') & filters.TEXT,
context_handlers.handle_other_messages
)
inline_keyboard_handlers = InlineKeyboardHandlers(logger)
TelegramHelpers.register_callback_handler(
self.app, inline_keyboard_handlers.route
)
# self.app.add_error_handler(self.error_handler)
self.app.run_polling(allowed_updates=BaseTeleUpdate.ALL_TYPES)
print('<<< BOT POLLING LOOP ENDED >>>')
async def post_init(self, _: Application):
# print('SET COMMANDS')
await self.get_bot().set_my_commands([(
Command.START, 'start bot'
), (
Command.USER_DETAILS, 'shows your username and user id'
), (
Command.CHAT_DETAILS, 'shows chat id'
), (
Command.CREATE_GROUP_POLL, 'create a new poll'
), (
Command.CREATE_PRIVATE_POLL,
'create a new poll that users cannot self register for'
), (
Command.SET_MAX_VOTERS,
'set the maximum number of voters who can vote for a poll'
), (
Command.PAY_SUPPORT, 'payment support'
), (
Command.REGISTER_USER_ID,
'registers a user by user_id for a poll'
), (
Command.WHITELIST_USERNAME,
'whitelist a username for a poll'
), (
Command.WHITELIST_CHAT_REGISTRATION,
'whitelist a chat for self registration'
), (
Command.BLACKLIST_CHAT_REGISTRATION,
'removes a chat from self registration whitelist'
), (
Command.VIEW_POLL, 'shows poll details given poll_id'
), (
Command.VIEW_POLLS, 'shows all polls that you have created'
), (
Command.VOTE, 'vote for the poll with the specified poll_id'
), (
Command.POLL_RESULTS,
'returns poll results if the poll has been closed'
), (
Command.HAS_VOTED,
"check if you've voted for the poll given the poll ID"
), (
Command.CLOSE_POLL,
'close the poll with the specified poll_id'
), (
Command.VIEW_VOTES,
'view all the votes entered for the poll'
), (
Command.VIEW_VOTERS,
'show which voters have voted and which have not'
), (
Command.ABOUT, 'miscellaneous info about the bot'
), (
Command.DELETE_POLL, 'delete a poll'
), (
Command.DELETE_ACCOUNT, 'delete your user account'
), (
Command.HELP, 'view commands available to the bot'
), (
Command.DONE, 'finish creating a poll or ranked vote'
)])
@track_errors
async def web_app_handler(
self, update: ModifiedTeleUpdate, context: ContextTypes.DEFAULT_TYPE
):
# TODO: update reference poll message with latest voter count
message: Message = update.message
payload = json.loads(update.effective_message.web_app_data.data)
try:
poll_id = int(payload['poll_id'])
ranked_option_numbers: List[int] = payload['option_numbers']
except KeyError:
await message.reply_text('Invalid payload')
return False
tele_user: TeleUser = message.from_user
username: Optional[str] = tele_user.username
user_tele_id = tele_user.id
formatted_rankings = ' > '.join([
self.stringify_ranking(rank) for rank in ranked_option_numbers
])
await message.reply_text(textwrap.dedent(f"""
Your rankings are:
{poll_id}: {formatted_rankings}
"""))
vote_result = self.register_vote(
poll_id=poll_id, rankings=ranked_option_numbers,
user_tele_id=user_tele_id, username=username,
chat_id=message.chat_id
)
if vote_result.is_err():
error_message = vote_result.err()
await error_message.call(message.reply_text)
return False
await TelegramHelpers.send_post_vote_reply(
message=message, poll_id=poll_id
)
ref_info = payload.get('ref_info', str(BLANK_ID))
ref_hash = payload.get('ref_hash', '')
# print('REFS', ref_info, ref_hash)
signed_ref_info = BaseAPI.sign_data_check_string(ref_info)
if signed_ref_info != ref_hash:
# print('REJECT_HASH')
return
# update the poll voter count in the originating poll message
_, raw_poll_id, raw_ref_msg_id, raw_ref_chat_id = ref_info.split(':')
poll_id = int(raw_poll_id)
ref_msg_id = int(raw_ref_msg_id)
ref_chat_id = int(raw_ref_chat_id)
if (ref_msg_id == BLANK_ID) or (ref_chat_id == BLANK_ID):
return
poll_info = BaseAPI.unverified_read_poll_info(poll_id=poll_id)
await TelegramHelpers.update_poll_message(
poll_info=poll_info, chat_id=ref_chat_id,
message_id=ref_msg_id, context=context,
poll_locks_manager=PollsLockManager()
)
@track_errors
async def handle_unknown_command(self, update: ModifiedTeleUpdate, _):
await update.message.reply_text("Command not found")
@staticmethod
def is_whitelisted_chat(poll_id: int, chat_id: int):
query = ChatWhitelist.select().where(
(ChatWhitelist.chat_id == chat_id) &
(ChatWhitelist.poll == poll_id)
)
return query.exists()
@staticmethod
async def user_details_handler(update: ModifiedTeleUpdate, *_):
"""
returns current user id and username
"""
# when command /user_details is invoked
tele_user: TeleUser = update.message.from_user
await update.message.reply_text(textwrap.dedent(f"""
user id: {tele_user.id}
username: {tele_user.username}
"""))
@staticmethod
async def chat_details_handler(update: ModifiedTeleUpdate, *_):
"""
returns current chat id
"""
chat_id = update.message.chat.id
await update.message.reply_text(f"chat id: {chat_id}")
async def has_voted(self, update: ModifiedTeleUpdate, *_, **__):
"""
usage:
/has_voted {poll_id}
"""
message = update.message
user = update.user
extract_poll_id_result = TelegramHelpers.extract_poll_id(update)
if extract_poll_id_result.is_err():
await message.reply_text('Poll ID not specified')
return False
user_id = user.get_user_id()
poll_id = extract_poll_id_result.unwrap()
is_voter = PollVoters.is_poll_voter(
poll_id=poll_id, user_id=user_id
)
if not is_voter:
await message.reply_text(
f"You're not a voter of poll {poll_id}"
)
return False
voted = self.check_has_voted(poll_id=poll_id, user_id=user_id)
if voted:
await message.reply_text("you've voted already")
else:
await message.reply_text("you haven't voted")
async def create_group_poll(
self, update: ModifiedTeleUpdate, context: ContextTypes.DEFAULT_TYPE
):
"""
/create_group_poll @username_1 @username_2 ... @username_n:
poll title
poll option 1
poll option 2
...
poll option m
- creates a new poll that chat members can self-register for
"""
whitelisted_chat_ids = []
chat_type = update.message.chat.type
if chat_type != 'private':
chat_id = update.message.chat.id
# print('CHAT_ID', chat_id)
whitelisted_chat_ids.append(chat_id)
return await self.create_poll(
update=update, context=context, open_registration=True,
whitelisted_chat_ids=whitelisted_chat_ids
)
async def create_poll(
self, update: ModifiedTeleUpdate, context: ContextTypes.DEFAULT_TYPE,
open_registration: bool = False,
whitelisted_chat_ids: Sequence[int] = ()
):
"""
example:
---------------------------
/create_poll @asd @fad:
what ice cream is the best
mochi
potato
cookies and cream
chocolate
"""
message: Message = update.message
creator_user: TeleUser | None = message.from_user
if creator_user is None:
await message.reply_text("Creator user not specified")
return False
creator_tele_id = creator_user.id
assert isinstance(creator_tele_id, int)
user_entry: Users = update.user
user_id = user_entry.get_user_id()
raw_poll_creation_args = TelegramHelpers.read_raw_command_args(
update, strip=False
).rstrip()
# initiate poll creation context here
if raw_poll_creation_args == '':
num_user_created_polls = Polls.count_polls_created(user_id)
subscription_tier_res = user_entry.get_subscription_tier()
if subscription_tier_res.is_err():
return await message.reply_text(READ_SUBSCRIPTION_TIER_FAILED)
subscription_tier = subscription_tier_res.unwrap()
poll_creation_limit = subscription_tier.get_max_polls()
if num_user_created_polls >= poll_creation_limit:
await message.reply_text(POLL_OPTIONS_LIMIT_REACHED_TEXT)
return False
PollCreationChatContext(
user_id=user_entry.get_user_id(), chat_id=message.chat.id,
max_options=POLL_MAX_OPTIONS, poll_options=[],
open_registration=open_registration
).save_state()
await message.reply_text(
"Enter the title / question for your new poll:"
)
return True
assert raw_poll_creation_args != ''
subscription_tier_res = user_entry.get_subscription_tier()
if subscription_tier_res.is_err():
err_msg = "Unexpected error reading subscription tier"
await message.reply_text(err_msg)
return False
subscription_tier = subscription_tier_res.unwrap()
if '\n' not in raw_poll_creation_args:
await message.reply_text("poll creation format wrong")
return False
all_lines = raw_poll_creation_args.split('\n')
if ':' in all_lines[0]:
# separate poll voters (before :) from poll title and options
split_index = raw_poll_creation_args.index(':')
# first part of command is all the users that are in the poll
command_p1: str = raw_poll_creation_args[:split_index].strip()
# second part of command is the poll question + poll options
command_p2: str = raw_poll_creation_args[split_index+1:].strip()
else:
# no : on first line to separate poll voters and
# poll title + questions
command_p1 = all_lines[0]
command_p2 = raw_poll_creation_args[len(command_p1)+1:]
poll_info_lines = command_p2.split('\n')
if len(poll_info_lines) < 3:
await message.reply_text('Poll requires at least 2 options')
return False
poll_question = poll_info_lines[0].strip().replace('\n', '')
poll_options = poll_info_lines[1:]
poll_options = [
poll_option.strip().replace('\n', '')
for poll_option in poll_options
]
# print('COMMAND_P2', lines)
if (command_p1 == '') and not open_registration:
await message.reply_text('poll voters not specified!')
return False
raw_poll_usernames: List[str] = command_p1.split()
whitelisted_usernames: List[str] = []
poll_user_tele_ids: List[int] = []
for raw_poll_user in raw_poll_usernames:
if raw_poll_user.startswith('#'):
raw_poll_user_tele_id = raw_poll_user[1:]
if constants.ID_PATTERN.match(raw_poll_user_tele_id) is None:
await message.reply_text(
f'Invalid poll user id: {raw_poll_user}'
)
return False
poll_user_tele_id = int(raw_poll_user_tele_id)
poll_user_tele_ids.append(poll_user_tele_id)
continue
if raw_poll_user.startswith('@'):
whitelisted_username = raw_poll_user[1:]
else:
whitelisted_username = raw_poll_user
if len(whitelisted_username) < 4:
await message.reply_text(
f'username too short: {whitelisted_username}'
)
return False
whitelisted_usernames.append(whitelisted_username)
try:
db_user = Users.build_from_fields(tele_id=creator_tele_id).get()
except Users.DoesNotExist:
await message.reply_text(f'UNEXPECTED ERROR: USER DOES NOT EXIST')
return False
creator_id = db_user.get_user_id()
# create users if they don't exist
user_rows = [
Users.build_from_fields(tele_id=tele_id)
for tele_id in poll_user_tele_ids
]
poll_creator = PollCreatorTemplate(
creator_id=creator_id, user_rows=user_rows,
poll_user_tele_ids=poll_user_tele_ids,
poll_question=poll_question,
subscription_tier=subscription_tier,
open_registration=open_registration,
poll_options=poll_options,
whitelisted_usernames=whitelisted_usernames,
whitelisted_chat_ids=whitelisted_chat_ids
)
create_poll_res = poll_creator.save_poll_to_db()
if create_poll_res.is_err():
error_message = create_poll_res.err()
await error_message.call(message.reply_text)
return False
new_poll: Polls = create_poll_res.unwrap()
new_poll_id = int(new_poll.id)
bot_username = context.bot.username
poll_message = self.generate_poll_info(
new_poll_id, poll_question, poll_options,
bot_username=bot_username, closed=False,
num_voters=poll_creator.initial_num_voters,
max_voters=new_poll.max_voters,
add_instructions=update.is_group_chat()
)
chat_type = update.message.chat.type
reply_markup = None
if chat_type == 'private':
# create vote button for reply message
vote_markup_data = self.build_private_vote_markup(
poll_id=new_poll_id, tele_user=creator_user
)
reply_markup = ReplyKeyboardMarkup(vote_markup_data)
elif open_registration:
vote_markup_data = self.build_group_vote_markup(
poll_id=new_poll_id,
num_options=len(poll_options)
)
reply_markup = InlineKeyboardMarkup(vote_markup_data)
await message.reply_text(poll_message, reply_markup=reply_markup)
await message.reply_text(generate_poll_created_message(new_poll_id))
@classmethod
async def whitelist_chat_registration(
cls, update: ModifiedTeleUpdate, context: ContextTypes.DEFAULT_TYPE
):
extract_poll_id_result = TelegramHelpers.extract_poll_id(update)
if extract_poll_id_result.is_err():
error_message = extract_poll_id_result.err()
await error_message.call(update.message.reply_text)
return False
poll_id = extract_poll_id_result.unwrap()
return await TelegramHelpers.set_chat_registration_status(
update, context, whitelist=True, poll_id=poll_id
)
@classmethod
async def blacklist_chat_registration(
cls, update: ModifiedTeleUpdate, context: ContextTypes.DEFAULT_TYPE
):
extract_poll_id_result = TelegramHelpers.extract_poll_id(update)
if extract_poll_id_result.is_err():
error_message = extract_poll_id_result.err()
await error_message.call(update.message.reply_text)
return False
poll_id = extract_poll_id_result.unwrap()
return await TelegramHelpers.set_chat_registration_status(
update, context, whitelist=False, poll_id=poll_id
)
async def register_user_by_tele_id(
self, update: ModifiedTeleUpdate, *_, **__
):
"""
registers a user by user_tele_id for a poll
/whitelist_user_id {poll_id} {user_tele_id}
"""
message: Message = update.message
tele_user = message.from_user
raw_text = message.text.strip()
r"""
^\S+ - command name
\s+ - whitespace
([1-9]\d*) - poll_id
s+ - whitespace
([1-9]\d*) - user_tele_id
"""
pattern = re.compile(r'^\S+\s+([1-9]\d*)\s+([1-9]\d*)$')
matches = pattern.match(raw_text)
format_invalid_message = textwrap.dedent(f"""
Format invalid.
Use /{Command.REGISTER_USER_ID} {{poll_id}} {{user_tele_id}}
""")
if tele_user is None:
await message.reply_text(f'user not found')
return False
if matches is None:
await message.reply_text(format_invalid_message)
return False
capture_groups = matches.groups()
if len(capture_groups) != 2:
await message.reply_text(format_invalid_message)
return False
poll_id = int(capture_groups[0])
target_user_tele_id = int(capture_groups[1])
try:
target_user = Users.build_from_fields(
tele_id=target_user_tele_id
).get()
except Users.DoesNotExist:
await message.reply_text(f'UNEXPECTED ERROR: USER DOES NOT EXIST')
return False
try:
poll = Polls.select().where(Polls.id == poll_id).get()
except Polls.DoesNotExist:
await message.reply_text(f'poll {poll_id} does not exist')
return False
target_user_id = target_user.get_user_id()
current_user_id = update.user.get_user_id()
creator_id: UserID = poll.get_creator().get_user_id()
if creator_id != current_user_id:
await message.reply_text(
'only poll creator is allowed to whitelist chats '
'for open user registration'
)
return False
try:
PollVoters.get(poll_id=poll_id, user_id=target_user_id)
await message.reply_text(f'User #{target_user_id} already registered')
return False
except PollVoters.DoesNotExist:
pass
register_result = self.register_user_id(
poll_id=poll_id, user_id=target_user_id,
ignore_voter_limit=False, from_whitelist=False
)
if register_result.is_err():
err: UserRegistrationStatus = register_result.err_value
assert isinstance(err, UserRegistrationStatus)
response_text = self.reg_status_to_msg(err, poll_id)
await message.reply_text(response_text)
return False
await message.reply_text(f'User #{target_user_tele_id} registered')
return True
async def view_votes(self, update: ModifiedTeleUpdate, *_, **__):
message: Message = update.message
extract_result = TelegramHelpers.extract_poll_id(update)
if extract_result.is_err():
error_message = extract_result.err()
await error_message.call(message.reply_text)
return False
poll_id = extract_result.unwrap()
tele_user: TeleUser | None = update.message.from_user
user_tele_id = tele_user.id
try:
user = Users.build_from_fields(tele_id=user_tele_id).get()
except Users.DoesNotExist:
await message.reply_text(f'UNEXPECTED ERROR: USER DOES NOT EXIST')
return False
user_id = user.get_user_id()
# check if voter is part of the poll
get_poll_closed_result = self.get_poll_closed(poll_id)
if get_poll_closed_result.is_err():
error_message = get_poll_closed_result.err()
await error_message.call(message.reply_text)
return False
has_poll_access = self.has_access_to_poll_id(
poll_id, user_id, username=tele_user.username
)
if not has_poll_access:
await message.reply_text(f'You have no access to poll {poll_id}')
return False
# get poll options in ascending order
poll_option_rows = PollOptions.select().where(
PollOptions.poll == poll_id
).order_by(PollOptions.option_number)
# map poll option ids to their option ranking numbers
# (option number is the position of the option in the poll)
option_index_map = {}
for poll_option_row in poll_option_rows:
option_index_map[poll_option_row.id] = (
poll_option_row.option_number
)
relevant_voters = PollVoters.select(PollVoters.id).where(
PollVoters.poll == poll_id
)
# TODO: is this or the join query faster?
vote_rows = VoteRankings.select().where(
VoteRankings.poll_voter.in_(relevant_voters)
).order_by(
VoteRankings.option, VoteRankings.ranking
)
"""
vote_rows = VoteRankings.select().join(
PollVoters, on=(PollVoters.id == VoteRankings.poll_voter_id)
).where(
PollVoters.poll_id == poll_id
).order_by(
VoteRankings.option_id, VoteRankings.ranking
)
"""
vote_sequence_map: Dict[int, Dict[int, int]] = {}
for vote_row in vote_rows:
"""
Maps voters to their ranked vote
Each ranked vote is stored as a dictionary
mapping their vote ranking to a vote_value
Each vote_value is either a poll option_id
(which is always a positive number),
or either of the <abstain> or <withhold> special votes
(which are represented as negative numbers -1 and -2)
"""
voter_id: int = vote_row.poll_voter.id
assert isinstance(voter_id, int)
if voter_id not in vote_sequence_map:
vote_sequence_map[voter_id] = {}
option_id_row = vote_row.option
if option_id_row is None:
vote_value = vote_row.special_value
assert vote_value < 0
else:
vote_value = option_id_row.id
assert vote_value > 0
ranking = int(vote_row.ranking)
ranking_map = vote_sequence_map[voter_id]
ranking_map[ranking] = vote_value
ranking_message = ''
for voter_id in vote_sequence_map:
# format vote sequence map into string rankings
ranking_map = vote_sequence_map[voter_id]
ranking_nos = sorted(ranking_map.keys())
sorted_option_nos = [
ranking_map[ranking] for ranking in ranking_nos
]
# print('SORT-NOS', sorted_option_nos)
str_rankings = []
for vote_value in sorted_option_nos:
if vote_value > 0:
option_id = vote_value
option_rank_no = option_index_map[option_id]
str_rankings.append(str(option_rank_no))
else:
str_rankings.append(
SpecialVotes(vote_value).to_string()
)
rankings_str = ' > '.join(str_rankings).strip()
ranking_message += rankings_str + '\n'
ranking_message = ranking_message.strip()
await message.reply_text(f'votes recorded:\n{ranking_message}')
async def unclose_poll_admin(self, update, *_, **__):
await self._set_poll_status(update, False)
async def close_poll_admin(self, update, *_, **__):
await self._set_poll_status(update, True)
@admin_only
async def _set_poll_status(self, update: ModifiedTeleUpdate, closed=True):
assert isinstance(update, ModifiedTeleUpdate)
message = update.message
extract_result = TelegramHelpers.extract_poll_id(update)
if extract_result.is_err():
error_message = extract_result.err()
await error_message.call(message.reply_text)
return False
poll_id = extract_result.unwrap()
with db.atomic():
PollWinners.delete().where(
PollWinners.poll == poll_id
).execute()
# remove cached result for poll winner
Polls.update({Polls.closed: closed}).where(
Polls.id == poll_id
).execute()
await message.reply_text(f'poll {poll_id} has been unclosed')
@admin_only
async def lookup_from_username_admin(
self, update: ModifiedTeleUpdate, *_, **__
):
"""
/lookup_from_username_admin {username}
Looks up user_ids for users with a matching username
"""
assert isinstance(update, ModifiedTeleUpdate)
message = update.message
raw_text = message.text.strip()
try:
username = raw_text[raw_text.index(' '):].strip()
except ValueError:
await message.reply_text("username not found")
return False
user_tele_ids = self.resolve_username_to_user_tele_ids(username)
id_strings = ' '.join([f'#{tele_id}' for tele_id in user_tele_ids])
await message.reply_text(textwrap.dedent(f"""
matching user_ids for username [{username}]:
{id_strings}
"""))
@admin_only
async def insert_user_admin(self, update: ModifiedTeleUpdate, *_, **__):
"""
Inserts a user with the given user_id and username into
the Users table
"""
message = update.message
raw_text = message.text.strip()
if ' ' not in raw_text:
await message.reply_text('Arguments not specified')
return False
cmd_arguments = raw_text[raw_text.index(' ') + 1:]
# <user_id> <username> <--force (optional)>
args_pattern = r"^([1-9]\d*)\s+(@?[a-zA-Z0-9_]+)\s?(--force)?$"
args_regex = re.compile(args_pattern)
match = args_regex.search(cmd_arguments)
if match is None:
await message.reply_text(f'Invalid arguments {[cmd_arguments]}')
return False
capture_groups = match.groups()
tele_id = int(capture_groups[0])
username: str = capture_groups[1]
force: bool = capture_groups[2] is not None
if username.startswith('@'):
username = username[1:]
assert len(username) >= 1
if not force:
user, created = Users.build_from_fields(
tele_id=tele_id, username=username
).get_or_create()
if created:
await message.reply_text(
f'User with tele_id {tele_id} and username '
f'{username} created'
)
else:
await message.reply_text(
'User already exists, use --force to '
'override existing entry'
)
else:
Users.build_from_fields(
tele_id=tele_id, username=username
).insert().on_conflict(
preserve=[Users.tele_id],
update={Users.username: username}
).execute()
await message.reply_text(
f'User with tele_id {tele_id} and username '
f'{username} replaced'
)
@admin_only
async def lookup_from_username_admin(
self, update: ModifiedTeleUpdate, *_, **__
):
"""
Looks up user_ids for users with a matching username
"""
assert isinstance(update, ModifiedTeleUpdate)
message = update.message
raw_text = message.text.strip()
try:
username = raw_text[raw_text.index(' '):].strip()
except ValueError:
await message.reply_text("username not found")
return False
matching_users = Users.select().where(Users.username == username)
user_tele_ids = [user.tele_id for user in matching_users]
await message.reply_text(textwrap.dedent(f"""
matching user_tele_ids for username [{username}]:
{' '.join([f'#{tele_id}' for tele_id in user_tele_ids])}
"""))
@admin_only
async def insert_user_admin(self, update: ModifiedTeleUpdate, *_, **__):
"""
Inserts a user with the given user_id and username into
the Users table
"""
message = update.message
raw_text = message.text.strip()
if ' ' not in raw_text:
await message.reply_text('Arguments not specified')
return False