-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
801 lines (716 loc) · 35.7 KB
/
app.py
File metadata and controls
801 lines (716 loc) · 35.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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
# -*- coding: utf-8 -*-
import configparser
from telegram.ext import Updater, CommandHandler, MessageHandler, CallbackQueryHandler, Filters
from telegram.ext.dispatcher import run_async
from telegram import ParseMode, InlineKeyboardButton, InlineKeyboardMarkup, Bot
import time, datetime, calendar
import math
import threading
import queue
import uuid
config = configparser.ConfigParser()
config.read('config.ini', encoding="utf8")
token = config['General']['Token']
vote_queue = queue.Queue()
if config.has_section('General'):
if config.has_option('General', 'Token') and config.has_option('General', 'Lang'):
token = config['General']['Token']
else:
config.set('General', 'Token', 'REPLACE_THIS_WITH_TOKEN')
config.set('General', 'Lang', 'REPLACE_THIS_WITH_YOUR_LANG_INI')
with open('config.ini','w') as configfile:
config.write(configfile)
print("Please fill out the config file")
exit()
else:
config.add_section('General')
config.set('General', 'Token', 'REPLACE_THIS_WITH_TOKEN')
config.set('General', 'Lang', 'REPLACE_THIS_WITH_YOUR_LANG_INI')
with open('config.ini','w') as configfile:
config.write(configfile)
print("Please fill out the config file")
exit()
def getValue(dest, section, title, defaultValue):
if dest.has_option(section, title):
return dest[section][title]
else:
dest.set(section, title, defaultValue)
return defaultValue
# 讀入語言字串
strings = configparser.ConfigParser()
strings.read(config['General']['Lang'], encoding="utf8")
#讀入群組規則
group = configparser.ConfigParser()
group.read('groupPolicy.ini')
#keyboards
createButton = lambda x: [createButton(i) for i in x] if isinstance(x[0], list) else InlineKeyboardButton(x[0], callback_data=x[1])
createKeyboard = lambda x: InlineKeyboardMarkup([createButton(i) for i in x])
vote_keyboard = createKeyboard([
[
[strings['Boolean']['Agree'], '1'],
[strings['Boolean']['DisAgree'], '0'],
[strings['Boolean']['NoComment'], '2']
],
[
[strings['Boolean']['Cancel'], 'cancel']\
]
])
restrict_keyboard = createKeyboard([
[
[strings['Restriction']['SendMessage'], 'sendMessage'],
[strings['Restriction']['SendMedia'], 'sendMedia'],
[strings['Restriction']['SendOther'], 'sendOther'],
[strings['Restriction']['WebPreview'], 'webPreview']
],
[
[strings['Boolean']['Cancel'], 'cancel']
]
])
admin_keyboard = createKeyboard([
[
[strings['Admin']['CanChangeInfo'], 'canChangeInfo'],
[strings['Admin']['CanDeleteMessages'], 'canDeleteMessages'],
[strings['Admin']['CanInviteUsers'], 'canInviteUsers']
],
[
[strings['Admin']['CanRestrictMembers'], 'canRestrictMembers'],
[strings['Admin']['CanPinMessages'], 'canPinMessages'],
[strings['Admin']['CanPromoteMembers'], 'canPromoteMembers']
],
[
[strings['Boolean']['Cancel'], 'cancel']
]
])
commands = ['ban', 'unban', 'setDesc', 'setPolicy', 'setTitle', 'restrict', 'admin']
simpleCommands = ['ban', 'unban', 'setDesc', 'setPolicy', 'setTitle']
# logging
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
@run_async
def start(bot, update):
update.message.reply_text('Hi!')
@run_async
def help(bot, update):
update.message.reply_text(strings['Help']['Help'].replace('\\n', '\n').replace('^', ' '))
chat_member = {}
def checkmember(chatid,userid):
chatid=str(chatid)
userid=str(userid)
if chatid not in chat_member:
chat_member[chatid] = {}
if userid not in chat_member[chatid]:
try:
tgbot.get_chat_member(chatid,userid)
chat_member[chatid][userid] = True
except:
chat_member[chatid][userid] = False
return(chat_member[chatid][userid])
def getGroupPolicyCount(chat_id, command):
temp = False
chat_id = str(chat_id)
if group.has_option(chat_id, command):
if '%' in group.get(chat_id, command, raw=True): #百分比投票制
notNum = True
temp = group[chat_id][command]
else: #固定人數投票制
return int(group[chat_id][command])
if not temp: #查無群組資料
try:
temp = group.get('Universal', command, raw=True) #採用預設值
except configparser.NoOptionError:
temp = group.get('Universal', 'default', raw=True) #採用預設值的預設值(X
try:
return int(temp)
except ValueError:
notNum = True
if notNum:
global tgbot
return int(math.ceil(float(temp.replace('%',''))*tgbot.getChatMembersCount(chat_id)/100))
def getGroupPolicyRaw(chat_id, command):
try:
value = group.get(chat_id, command, raw=True)
except configparser.NoSectionError:
value = group.get('Universal', command, raw=True)
return value
group_vote = {}
@run_async
def vote(chat_id, title, command, commandArgs, status='voting', proposer=None): #command = 'ban', #commandArgs = {'userId':123456, 'until_date':140632804545}
chatid = str(chat_id)
group_vote[chatid] = {}
nowTime = time.time()
voteuuid = str(uuid.uuid1())
global vote_keyboard, restrict_keyboard, admin_keyboard
if command in simpleCommands:
keyboard = vote_keyboard
else:
keyboard = {'restrict': restrict_keyboard,
'admin': admin_keyboard
}[command]
global tgbot
deadlineTime = nowTime + int(getGroupPolicyCount(chatid, 'expire'))
msgid = str(tgbot.sendMessage(
chatid,
parse_mode='Markdown',
text="{}\n\n{} : 0\n{}: 0\n{}: 0\n\nUUID: {}\n{}: {}".format(
title,
strings['Boolean']['Agree'],
strings['Boolean']['Disagree'],
strings['Boolean']['NoComment'],
voteuuid,
strings['Vote']['ExpireTime'],
datetime.datetime.fromtimestamp(deadlineTime).strftime('%Y/%m/%d %H:%M:%S')),
reply_markup=keyboard).message_id)
group_vote[chatid][msgid] = {}
group_vote[chatid][msgid]['title'] = title
group_vote[chatid][msgid]['message'] = title
group_vote[chatid][msgid]['command'] = command #command == 'ban' or sth else
group_vote[chatid][msgid]['commandArgs'] = commandArgs #commandArgs = {'userId':123456, 'until_date':140632804545}
group_vote[chatid][msgid]['time'] = nowTime #投票建立時間
group_vote[chatid][msgid]['status'] = status #直接進入投票主題!!!!!!!!!!
group_vote[chatid][msgid]['proposer'] = proposer #發起者 user_id
group_vote[chatid][msgid]['voted'] = False #False 表未有任何人參與過投票
group_vote[chatid][msgid]['deadline'] = datetime.datetime.fromtimestamp(deadlineTime).strftime('%Y/%m/%d %H:%M:%S')
group_vote[chatid][msgid]['uuid'] = voteuuid
if command in simpleCommands:
group_vote[chatid][msgid]['y'] = 0
group_vote[chatid][msgid]['n'] = 0
group_vote[chatid][msgid]['u'] = 0
elif command == 'restrict':
group_vote[chatid][msgid]['sendMessage'] = [0,0,0] #[y,n,u]
group_vote[chatid][msgid]['sendMedia'] = [0,0,0]
group_vote[chatid][msgid]['sendOther'] = [0,0,0]
group_vote[chatid][msgid]['webPreview'] = [0,0,0]
elif command == 'admin':
group_vote[chatid][msgid]['canChangeInfo'] = [0,0,0]
group_vote[chatid][msgid]['canDeleteMessages'] = [0,0,0]
group_vote[chatid][msgid]['canInviteUsers'] = [0,0,0]
group_vote[chatid][msgid]['canRestrictMembers'] = [0,0,0]
group_vote[chatid][msgid]['canPinMessages'] = [0,0,0]
group_vote[chatid][msgid]['canPromoteMembers'] = [0,0,0]
vote_queue.put_nowait({ "chat_id" : chatid , "message_id" : msgid })
return(msgid)
@run_async
def vote_callback(bot, update):
query = update.callback_query
chat_id = str(query.message.chat.id)
message_id = str(query.message.message_id)
user_id = str(query.from_user.id)
command = group_vote[chat_id][message_id]['command']
status = group_vote[chat_id][message_id]['status']
#print(query)
if status == "selecting_rest":
pass
elif status == "voting":
try:
group_vote[chat_id][message_id][user_id]
except KeyError:
if command in simpleCommands:
group_vote[chat_id][message_id][user_id] = -1
elif command == 'restrict':
group_vote[chat_id][message_id][user_id] = {
'sendMessage': -1,
'sendMedia': -1,
'sendOther': -1,
'webPreview': -1
}
elif command == 'admin':
group_vote[chat_id][message_id][user_id] = {
'canChangeInfo': -1,
'canDeleteMessages': -1,
'canInviteUsers': -1,
'canRestrictMembers': -1,
'canPinMessages': -1,
'canPromoteMembers': -1
}
if query.data == "cancel":
if not group_vote[chat_id][message_id]['voted']:
group_vote[chat_id][message_id]['time'] = -48794878740 #立即過期
else:
alert= "Cancel vote."
if command in simpleCommands:
if query.data == "0" :
group_vote[chat_id][message_id]['voted'] = True
if group_vote[chat_id][message_id][user_id] == 0:
group_vote[chat_id][message_id][user_id] = -1
group_vote[chat_id][message_id]['n'] -= 1
alert=strings['Vote']["Undo"]
else:
group_vote[chat_id][message_id][user_id] = 0
group_vote[chat_id][message_id]['n'] += 1
alert=strings['Vote']["Disagree"]
elif query.data == "1":
group_vote[chat_id][message_id]['voted'] = True
if group_vote[chat_id][message_id][user_id] == 1:
group_vote[chat_id][message_id][user_id] = -1
group_vote[chat_id][message_id]['y'] -= 1
alert=strings['Vote']["Undo"]
else:
group_vote[chat_id][message_id][user_id] = 1
group_vote[chat_id][message_id]['y'] += 1
alert=strings['Vote']["Agree"]
elif query.data == "2" :
group_vote[chat_id][message_id]['voted'] = True
if group_vote[chat_id][message_id][user_id] == 2:
group_vote[chat_id][message_id][user_id] = -1
group_vote[chat_id][message_id]['u'] -=1
alert=strings['Vote']["Undo"]
else:
group_vote[chat_id][message_id][user_id] = 2
group_vote[chat_id][message_id]['u'] += 1
alert=strings['Vote']["NoComment"]
global vote_keyboard
keyboard = vote_keyboard
msg = "{}\n\n{} : {}\n{}: {}\n{}: {}".format(
group_vote[chat_id][message_id]['title'],
strings['Boolean']['Agree'],
str(group_vote[chat_id][message_id]['y']),
strings['Boolean']['Disagree'],
str(group_vote[chat_id][message_id]['n']),
strings['Boolean']['NoComment'],
str(group_vote[chat_id][message_id]['u']))
elif command in ['restrict', 'admin']:
group_vote[chat_id][message_id]['voted'] = True
if group_vote[chat_id][message_id][user_id][query.data] == -1: #對 query.data 的投票為 -1,1,0,2 之一
group_vote[chat_id][message_id][user_id][query.data] = 1
group_vote[chat_id][message_id][query.data][0] +=1
alert=strings['Vote']["Agree"]
elif group_vote[chat_id][message_id][user_id][query.data] == 1:
group_vote[chat_id][message_id][user_id][query.data] = 0
group_vote[chat_id][message_id][query.data][0] -=1
group_vote[chat_id][message_id][query.data][1] +=1
alert=strings['Vote']["Disagree"]
elif group_vote[chat_id][message_id][user_id][query.data] == 0:
group_vote[chat_id][message_id][user_id][query.data] = 2
group_vote[chat_id][message_id][query.data][1] -=1
group_vote[chat_id][message_id][query.data][2] +=1
alert=strings['Vote']["NoComment"]
elif group_vote[chat_id][message_id][user_id][query.data] == 2:
group_vote[chat_id][message_id][user_id][query.data] = 1
group_vote[chat_id][message_id][query.data][2] -=1
group_vote[chat_id][message_id][query.data][0] +=1
alert=strings['Vote']["Agree"]
global restrict_keyboard, admin_keyboard
keyboard = {'restrict': restrict_keyboard,
'admin': admin_keyboard
}[command]
if command == 'restrict':
msg = "{}\n\n{} : {}\n{}: {}\n{}: {}\n{} : {}".format(
group_vote[chat_id][message_id]['title'],
strings['Restriction']['SendMessage'],
'/'.join([str(i) for i in group_vote[chat_id][message_id]['sendMessage']]),
strings['Restriction']['SendMedia'],
'/'.join([str(i) for i in group_vote[chat_id][message_id]['sendMedia']]),
strings['Restriction']['SendOther'],
'/'.join([str(i) for i in group_vote[chat_id][message_id]['sendOther']]),
strings['Restriction']['WebPreview'],
'/'.join([str(i) for i in group_vote[chat_id][message_id]['webPreview']])
)
elif command == 'admin':
msg = "{}\n\n{} : {}\n{}: {}\n{}: {}\n{} : {}\n{} : {}\n{} : {}".format(
group_vote[chat_id][message_id]['title'],
strings['Admin']['CanChangeInfo'],
'/'.join([str(i) for i in group_vote[chat_id][message_id]['canChangeInfo']]),
strings['Admin']['CanDeleteMessages'],
'/'.join([str(i) for i in group_vote[chat_id][message_id]['canDeleteMessages']]),
strings['Admin']['CanInviteUsers'],
'/'.join([str(i) for i in group_vote[chat_id][message_id]['canInviteUsers']]),
strings['Admin']['CanRestrictMembers'],
'/'.join([str(i) for i in group_vote[chat_id][message_id]['canRestrictMembers']]),
strings['Admin']['CanPinMessages'],
'/'.join([str(i) for i in group_vote[chat_id][message_id]['canPinMessages']]),
strings['Admin']['CanPromoteMembers'],
'/'.join([str(i) for i in group_vote[chat_id][message_id]['canPromoteMembers']])
)
group_vote[chat_id][message_id]['message'] = msg
msg += '\n\nUUID: ' + group_vote[chat_id][message_id]['uuid']
msg += '\n' + strings['Vote']['ExpireTime'] + ': '+ group_vote[chat_id][message_id]['deadline']
bot.edit_message_text(text=msg,
chat_id=query.message.chat_id,
message_id=query.message.message_id,
reply_markup=keyboard,
parse_mode='Markdown')
bot.answer_callback_query(query.id,text=alert)
def checkVoteExpired():
while True:
global tgbot
item = vote_queue.get()
chat_id = str(item['chat_id'])
message_id = str(item['message_id'])
vote = group_vote[str(chat_id)][str(message_id)]
command = vote['command']
#print("林北這個Thread 在 checking Chat id" + chat_id + " Message ID " + message_id + " 的la Time : "+str(time.time()) +" Expire Time : " + str(group_vote[chat_id][message_id]['time'] + getGroupPolicyCount(chat_id, 'expire')) + " eXPIRE : " + str(getGroupPolicyCount(chat_id, 'expire')))
if int(time.time()) > (group_vote[chat_id][message_id]['time'] + getGroupPolicyCount(chat_id, 'expire')):
if command in simpleCommands:
if vote['y'] > vote['n'] and (vote['y'] + vote['n'] + vote['u']) >= getGroupPolicyCount(chat_id, command):
tgbot.edit_message_text(
parse_mode='Markdown',
text='{}\n\n{}'.format(
group_vote[chat_id][message_id]['message'],
strings['Vote']["Pass"]),
chat_id=chat_id,
message_id=message_id)
tgbot.sendMessage(chat_id, quote=True, reply_to_message_id=int(message_id), text=strings['Vote']["PassMessage"])
if command == 'setPolicy':
try:
group.set(chat_id, vote['commandArgs']['command'], vote['commandArgs']['value'])
except configparser.NoSectionError:
group.add_section(chat_id)
group.set(chat_id, vote['commandArgs']['command'], vote['commandArgs']['value'])
with open('groupPolicy.ini', 'w') as configfile:
group.write(configfile)
group_vote[str(chat_id)].pop(str(message_id))
pass
else:
{
'ban': tgbot.kickChatMember,
'unban': tgbot.unbanChatMember,
'setDesc': tgbot.setChatDescription,
'setTitle': tgbot.setChatTitle
}[command](chat_id=chat_id, **vote['commandArgs'])
group_vote[str(chat_id)].pop(str(message_id))
pass
else: #投票不通過
tgbot.edit_message_text(
parse_mode='Markdown',
text='{}\n\n{}'.format(
group_vote[chat_id][message_id]['message'],
strings['Vote']["Fail"]),
chat_id=chat_id,
message_id=message_id)
tgbot.sendMessage(chat_id, quote=True, reply_to_message_id=int(message_id), text=strings['Vote']["FailMessage"])
group_vote[str(chat_id)].pop(str(message_id))
pass
elif command in ['restrict', 'admin']:
tempResult = {}
tempResultText = {}
resultToCommand = {
'restrict':{
'sendMessage': 'can_send_messages',
'sendMedia': 'can_send_media_messages',
'sendOther': 'can_send_other_messages',
'webPreview': 'can_add_web_page_previews'
},
'admin':{
'canChangeInfo': 'can_change_info',
'canDeleteMessages': 'can_delete_messages',
'canInviteUsers': 'can_invite_users',
'canRestrictMembers': 'can_restrict_members',
'canPinMessages': 'can_pin_messages',
'canPromoteMembers': 'can_promote_members'
}
}[command]
for key, value in group_vote[chat_id][message_id].items():
if isinstance(value, list):
if len(value) == 3:
if value[0] > value[1] and sum(value) >= getGroupPolicyCount(chat_id, command):
if command == 'restrict':
tempResult.update({resultToCommand[key]:False})
tempResultText.update({key:'False'})
elif command == 'admin':
tempResult.update({resultToCommand[key]:True})
tempResultText.update({key:'True'})
elif value[0] < value[1] and sum(value) >= getGroupPolicyCount(chat_id, command):
if command == 'restrict':
tempResult.update({resultToCommand[key]:True})
tempResultText.update({key:'True'})
elif command == 'admin':
tempResult.update({resultToCommand[key]:False})
tempResultText.update({key:'False'})
else:
tempResultText.update({key:'Maintain'})
if command == 'restrict':
resultText = '{}\n\n{}:\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n'.format(
group_vote[chat_id][message_id]['message'],
strings['Vote']['VoteResult'],
strings['Restriction']['SendMessage'],
strings['Boolean'][tempResultText['sendMessage']],
strings['Restriction']['SendMedia'],
strings['Boolean'][tempResultText['sendMedia']],
strings['Restriction']['SendOther'],
strings['Boolean'][tempResultText['sendOther']],
strings['Restriction']['WebPreview'],
strings['Boolean'][tempResultText['webPreview']]
)
elif command == 'admin':
resultText = '{}\n\n{}:\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}'.format(
group_vote[chat_id][message_id]['message'],
strings['Vote']['VoteResult'],
strings['Admin']['CanChangeInfo'],
strings['Boolean'][tempResultText['canChangeInfo']],
strings['Admin']['CanDeleteMessages'],
strings['Boolean'][tempResultText['canDeleteMessages']],
strings['Admin']['CanInviteUsers'],
strings['Boolean'][tempResultText['canInviteUsers']],
strings['Admin']['CanRestrictMembers'],
strings['Boolean'][tempResultText['canRestrictMembers']],
strings['Admin']['CanPinMessages'],
strings['Boolean'][tempResultText['canPinMessages']],
strings['Admin']['CanPromoteMembers'],
strings['Boolean'][tempResultText['canPromoteMembers']]
)
tgbot.edit_message_text(chat_id=chat_id, message_id=message_id, text=resultText, parse_mode='Markdown')
tgbot.sendMessage(chat_id, quote=True, reply_to_message_id=int(message_id), text=strings['Vote']["OtherMessage"])
{'restrict': tgbot.restrictChatMember,
'admin': tgbot.promoteChatMember}[command](chat_id=chat_id, **vote['commandArgs'], **tempResult)
group_vote[str(chat_id)].pop(str(message_id))
pass
else:
vote_queue.put_nowait({ "chat_id" : chat_id , "message_id" : message_id })
time.sleep(int(config['General']['checkInterval']))
def timeConvert(timeText): # timeText -> int (second)
if '/' in timeText:
return calendar.timegm(datetime.datetime.strptime(timeText, '%Y/%m/%d-%H:%M:%S').utctimetuple()) - \
3600*int(config['General']['userUTC'])
elif any(i in timeText for i in ['y', 'M', 'd', 'h', 'm', 's']):
timeArray, timeVar = ['0'], 0
for i in timeText:
if i.isdigit():
if timeArray[-1].isnumeric():
timeArray[-1] += i
else:
timeArray.append(i)
elif i in ['y', 'M', 'd', 'h', 'm', 's']:
timeArray.append(i)
for i in list(range(len(timeArray))):
if timeArray[i].isalpha():
timeVar += {'y':31556926, 'M':2592000, 'd':86400, 'h':3600, 'm':60, 's':1}[timeArray[i]][0]*int(timeArray[i-1])
return timeVar
else:
raise TypeError('{} is not a timetext.'.format(timeText))
isTimeText = lambda x: any(i in x for i in ['y', 'M', 'd', 'h', 'm', '/', 's'])
isTimeTextArray = lambda x: any(isTimeText(i) for i in x)
def getTimeText(array):
for i in array:
if isTimeText(i):
return i
return False
@run_async
def voteLoader(bot, update, args, command):
chat_id = update.message.chat_id
user_id, userName, userFirstName = None, None, None
try:
timeVar = timeConvert(getTimeText(args))
except(TypeError, IndexError):
timeVar = 0
if update.message.reply_to_message is not None: # 有回覆訊息
user_id = getUser(update.message.reply_to_message.from_user).getId()
userName = getUser(update.message.reply_to_message.from_user).getUsername()
userFirstName = getUser(update.message.reply_to_message.from_user).getFirstname()
else:
try:
if not args[0].isnumeric: # 第一個參數不是 userId 且沒有回覆訊息
update.message.reply_text(strings['Error']['ArgumentError'])
return
except IndexError: # 奇怪的錯誤之類的
update.message.reply_text(strings['Error']['ArgumentError'])
return
if not (user_id and userName):
userName = bot.getChatMember(chat_id=chat_id, user_id=int(args[0]))['user']['username']
user_id = args[0]
if not userFirstName:
userFirstName = bot.getChatMember(chat_id=chat_id, user_id=user_id)['user']['first_name']
askString = {'ban':strings['Ask']['AgreedToBan'],
'restrict':strings['Ask']['AgreedToRestrict'],
'admin':strings['Ask']['AgreedToAdmin'],
'unban':strings.get('Ask','AgreedToUnban')}[command].format(
'[{}](tg://user?id={})'.format(userFirstName, user_id))
if timeVar:
askString += strings['Ask']['until'] + datetime.datetime.fromtimestamp(untilTime).strftime('%Y/%m/%d %H:%M:%S') + '?'
vote(chat_id,
'{}{}{} ?'.format(
askString,
command,
{'user_id':user_id, 'until_date':int(time.time()+timeVar)}))
else:
askString += '?'
vote(chat_id,
askString,
command,
{'user_id':user_id})
return
@run_async
def voteban(bot, update, args=[]):
return voteLoader(bot=bot, update=update, args=args, command='ban')
@run_async
def voterest(bot, update, args=[]):
return voteLoader(bot=bot, update=update, args=args, command='restrict')
@run_async
def voteadmin(bot, update, args=[]):
return voteLoader(bot=bot, update=update, args=args, command='admin')
@run_async
def voteunban(bot, update, args=[]):
return voteLoader(bot=bot, update=update, args=args, command='unban')
@run_async
def votedesc(bot, update, args=['']):
chat_id = update.message.chat_id
if update.message.reply_to_message is not None and args != ['']: # 有回覆訊息且沒有參數
text = update.message.reply_to_message.text
else:
text = args[0]
text = text.replace('^', ' ').replace('\\n', '\n')
askString = strings['Ask']['AgreedToSetDesc'].replace('\\n','\n').format(text)
vote(chat_id,
askString,
'setDesc',
{'description':text})
return
@run_async
def votetitle(bot, update, args=['']):
chat_id = update.message.chat_id
if update.message.reply_to_message is not None and args != ['']: # 有回覆訊息且沒有參數
text = update.message.reply_to_message.text
else:
text = ''.join(i + ' ' for i in args)[:-1].replace('^', ' ')
askString = strings['Ask']['AgreedToSetTitle'].replace('\\n','\n').format(text)
vote(chat_id,
askString,
'setTitle',
{'title':text})
return
@run_async
def voteset(bot, update, args):
chat_id = update.message.chat_id
message_id = update.message.message_id
#Error
if len(args) < 2:
bot.sendMessage(chat_id, reply_to_message_id=message_id, text=strings['Error']['NotEnoughArguments'])
return
if len(args) > 2:
bot.sendMessage(chat_id, reply_to_message_id=message_id, text=strings['Error']['TooMuchArguments'])
return
if not args[0] in ['ban', 'restrict', 'admin', 'unban', 'expire']:
return
if args[0] == 'expire':
if not args[1].isnumeric():
try:
args[1] = str(timeConvert(args[1]))
except TypeError:
bot.sendMessage(chat_id, reply_to_message_id=message_id, text=strings['Error']['ArgumentError'])
return
askString = strings['Ask']['AgreedToSetExpire'].format(str(datetime.timedelta(seconds=int(args[1]))))
elif args[0] in ['ban', 'restrict', 'admin', 'unban']:
if not args[1].isnumeric():
if not args[1][-1] == '%':
bot.sendMessage(chat_id, reply_to_message_id=message_id, text=strings['Error']['ArgumentError'])
return
elif not args[1][:-1].isnumeric:
bot.sendMessage(chat_id, reply_to_message_id=message_id, text=strings['Error']['ArgumentError'])
return
elif not 0 < float(args[1][:-1]) < 100:
bot.sendMessage(chat_id, reply_to_message_id=message_id, text=strings['Error']['ArgumentError'])
return
askString = strings['Ask']['AgreedToSetMinimumCount'].format(
strings['Command'][args[0].capitalize()],
args[1])
askStrint += '?'
vote(chat_id,
askString,
'setPolicy',
{'command': args[0],
'value': args[1]
})
@run_async
def policy(bot, update, args=None):
chat_id = update.message.chat_id
message_id = update.message.message_id
text = ''
values = [i for i in group['Universal']]
if args:
for i in args:
if not i in values:
update.message.reply_text(strings['Error']['ArgumentErrorDetailed'].format(i))
return
if '%' in getGroupPolicyRaw(chat_id, i):
text += '*{}*: {} ({})\n'.format(
i.capitalize(),
str(getGroupPolicyRaw(chat_id, i)),
str(getGroupPolicyCount(chat_id, i))
)
else:
text += '*' + i.capitalize() + '*: ' + str(getGroupPolicyRaw(chat_id, i)) + '\n'
else:
for i in values:
if '%' in getGroupPolicyRaw(chat_id, i):
text += '*{}*: {} ({})\n'.format(
i.capitalize(),
str(getGroupPolicyRaw(chat_id, i)),
str(getGroupPolicyCount(chat_id, i))
)
else:
text += '*' + i.capitalize() + '*: ' + str(getGroupPolicyRaw(chat_id, i)) + '\n'
text += '\n*Chat ID*: `' + str(chat_id) + '`\n\n'
update.message.reply_text(text, parse_mode='Markdown')
@run_async
def getUserId(chat_id):
global tgbot
chatMember = tgbot.getChat(chat_id)
print(chatMember)
class User(object):
def __init__(self, name=None, first_name=None, last_name=None, username=None, id=None):
self.__name = name
self.__first_name = first_name
self.__last_name = last_name
self.__username = username
self.__id = id
def getId(self):
return self.__id
def setId(self, id=None):
self.__id=id
return self.__id
def getUsername(self):
return self.__username
def setUsername(self, username=None):
self.__username=username
return self.__username
def getLastname(self):
return self.__last_name
def setLastname(self, last_name=None):
self.__last_name = last_name
return self.__last_name
def getFirstname(self):
return self.__first_name
def setFirstname(self, first_name=None):
self.__first_name = first_name
return self.__first_name
def getName(self):
return self.__name
def setName(self, name=None):
self.__name=name
return self.__name
def getUser(from_user=None): #input update.message.from_user, return an User object.
if from_user:
item = User(name=from_user.first_name, first_name=from_user.first_name)
if not from_user.username:
item.setId(from_user.id)
else:
item.setUsername(from_user.username)
item.setId(from_user.id)
if from_user.last_name:
item.setLastname(from_user.last_name)
item.setName(item.getName() + item.getLastname())
else:
item = User(name="NoUser")
return(item)
def main():
updater = Updater(token)
global tgbot
tgbot = Bot(token)
for i in range(1,21):
t = threading.Thread(target=checkVoteExpired, daemon=True).start()
print("checkVoteExpired(" + str(i) + ") has launched !")
updater.dispatcher.add_handler(CommandHandler('voteban', voteban, pass_args=True))
updater.dispatcher.add_handler(CommandHandler('voterest', voterest, pass_args=True))
updater.dispatcher.add_handler(CommandHandler('voteadmin', voteadmin, pass_args=True))
updater.dispatcher.add_handler(CommandHandler('voteunban', voteunban, pass_args=True))
updater.dispatcher.add_handler(CommandHandler('votedesc', votedesc, pass_args=True))
updater.dispatcher.add_handler(CommandHandler('votetitle', votetitle, pass_args=True))
updater.dispatcher.add_handler(CommandHandler('voteset', voteset, pass_args=True))
updater.dispatcher.add_handler(CommandHandler('policy', policy, pass_args=True))
updater.dispatcher.add_handler(CommandHandler('help', help))
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CallbackQueryHandler(vote_callback))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()