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 
 
 
1
+ # <============================================== IMPORTS =========================================================>
2
+ import ast
3
+ import csv
4
+ import json
5
+ import os
6
+ import re
7
+ import time
8
+ import uuid
9
+ from io import BytesIO
10
+
11
+ from telegram import (
12
+ ChatMember,
13
+ InlineKeyboardButton,
14
+ InlineKeyboardMarkup,
15
+ MessageEntity,
16
+ Update,
17
+ )
18
+ from telegram.constants import ParseMode
19
+ from telegram.error import BadRequest, Forbidden, TelegramError
20
+ from telegram.ext import CallbackQueryHandler, CommandHandler, ContextTypes
21
+ from telegram.helpers import mention_html, mention_markdown
22
+
23
+ import Database.sql.feds_sql as sql
24
+ from Mikobot import (
25
+ DRAGONS,
26
+ EVENT_LOGS,
27
+ LOGGER,
28
+ OWNER_ID,
29
+ SUPPORT_CHAT,
30
+ dispatcher,
31
+ function,
32
+ )
33
+ from Mikobot.plugins.disable import DisableAbleCommandHandler
34
+ from Mikobot.plugins.helper_funcs.alternate import send_message
35
+ from Mikobot.plugins.helper_funcs.chat_status import is_user_admin
36
+ from Mikobot.plugins.helper_funcs.extraction import (
37
+ extract_unt_fedban,
38
+ extract_user,
39
+ extract_user_fban,
40
+ )
41
+ from Mikobot.plugins.helper_funcs.string_handling import markdown_parser
42
+
43
+ # <=======================================================================================================>
44
+
45
+ FBAN_ERRORS = {
46
+ "User is an administrator of the chat",
47
+ "Chat not found",
48
+ "Not enough rights to restrict/unrestrict chat member",
49
+ "User_not_participant",
50
+ "Peer_id_invalid",
51
+ "Group chat was deactivated",
52
+ "Need to be inviter of a user to kick it from a basic group",
53
+ "Chat_admin_required",
54
+ "Only the creator of a basic group can kick group administrators",
55
+ "Channel_private",
56
+ "Not in the chat",
57
+ "Have no rights to send a message",
58
+ }
59
+
60
+ UNFBAN_ERRORS = {
61
+ "User is an administrator of the chat",
62
+ "Chat not found",
63
+ "Not enough rights to restrict/unrestrict chat member",
64
+ "User_not_participant",
65
+ "Method is available for supergroup and channel chats only",
66
+ "Not in the chat",
67
+ "Channel_private",
68
+ "Chat_admin_required",
69
+ "Have no rights to send a message",
70
+ }
71
+
72
+
73
+ # <================================================ FUNCTION =======================================================>
74
+ async def new_fed(update: Update, context: ContextTypes.DEFAULT_TYPE):
75
+ chat = update.effective_chat
76
+ user = update.effective_user
77
+ message = update.effective_message
78
+ bot = context.bot
79
+ if chat.type != "private":
80
+ await update.effective_message.reply_text(
81
+ "Federations can only be created by privately messaging me.",
82
+ )
83
+ return
84
+ if len(message.text) == 1:
85
+ await send_message(
86
+ update.effective_message,
87
+ "Please write the name of the federation!",
88
+ )
89
+ return
90
+ fednam = message.text.split(None, 1)[1]
91
+ if not fednam == "":
92
+ fed_id = str(uuid.uuid4())
93
+ fed_name = fednam
94
+ LOGGER.info(fed_id)
95
+
96
+ x = sql.new_fed(user.id, fed_name, fed_id)
97
+ if not x:
98
+ await update.effective_message.reply_text(
99
+ f"Can't federate! Please contact @{SUPPORT_CHAT} if the problem persist.",
100
+ )
101
+ return
102
+
103
+ await update.effective_message.reply_text(
104
+ "*You have succeeded in creating a new federation!*"
105
+ "\nName: `{}`"
106
+ "\nID: `{}`"
107
+ "\n\nUse the command below to join the federation:"
108
+ "\n`/joinfed {}`".format(fed_name, fed_id, fed_id),
109
+ parse_mode=ParseMode.MARKDOWN,
110
+ )
111
+ try:
112
+ await bot.send_message(
113
+ EVENT_LOGS,
114
+ "New Federation: <b>{}</b>\nID: <pre>{}</pre>".format(fed_name, fed_id),
115
+ parse_mode=ParseMode.HTML,
116
+ )
117
+ except:
118
+ LOGGER.warning("Cannot send a message to EVENT_LOGS")
119
+ else:
120
+ await update.effective_message.reply_text(
121
+ "Please write down the name of the federation",
122
+ )
123
+
124
+
125
+ async def del_fed(update: Update, context: ContextTypes.DEFAULT_TYPE):
126
+ bot, args = context.bot, context.args
127
+ chat = update.effective_chat
128
+ user = update.effective_user
129
+ if chat.type != "private":
130
+ await update.effective_message.reply_text(
131
+ "Federations can only be deleted by privately messaging me.",
132
+ )
133
+ return
134
+ if args:
135
+ is_fed_id = args[0]
136
+ getinfo = sql.get_fed_info(is_fed_id)
137
+ if getinfo is False:
138
+ await update.effective_message.reply_text("This federation does not exist.")
139
+ return
140
+ if int(getinfo["owner"]) == int(user.id) or int(user.id) == OWNER_ID:
141
+ fed_id = is_fed_id
142
+ else:
143
+ await update.effective_message.reply_text(
144
+ "Only federation owners can do this!"
145
+ )
146
+ return
147
+ else:
148
+ await update.effective_message.reply_text("What should I delete?")
149
+ return
150
+
151
+ if is_user_fed_owner(fed_id, user.id) is False:
152
+ await update.effective_message.reply_text("Only federation owners can do this!")
153
+ return
154
+
155
+ await update.effective_message.reply_text(
156
+ "You sure you want to delete your federation? This cannot be reverted, you will lose your entire ban list, and '{}' will be permanently lost.".format(
157
+ getinfo["fname"],
158
+ ),
159
+ reply_markup=InlineKeyboardMarkup(
160
+ [
161
+ [
162
+ InlineKeyboardButton(
163
+ text="⚠️ Delete Federation ⚠️",
164
+ callback_data="rmfed_{}".format(fed_id),
165
+ ),
166
+ ],
167
+ [InlineKeyboardButton(text="Cancel", callback_data="rmfed_cancel")],
168
+ ],
169
+ ),
170
+ )
171
+
172
+
173
+ async def rename_fed(update: Update, context: ContextTypes.DEFAULT_TYPE):
174
+ user = update.effective_user
175
+ msg = update.effective_message
176
+ args = msg.text.split(None, 2)
177
+
178
+ if len(args) < 3:
179
+ return await msg.reply_text("usage: /renamefed <fed_id> <newname>")
180
+
181
+ fed_id, newname = args[1], args[2]
182
+ verify_fed = sql.get_fed_info(fed_id)
183
+
184
+ if not verify_fed:
185
+ return await msg.reply_text("This fed not exist in my database!")
186
+
187
+ if is_user_fed_owner(fed_id, user.id):
188
+ sql.rename_fed(fed_id, user.id, newname)
189
+ await msg.reply_text(f"Successfully renamed your fed name to {newname}!")
190
+ else:
191
+ await msg.reply_text("Only federation owner can do this!")
192
+
193
+
194
+ async def fed_chat(update: Update, context: ContextTypes.DEFAULT_TYPE):
195
+ bot, args = context.bot, context.args
196
+ chat = update.effective_chat
197
+ user = update.effective_user
198
+ fed_id = sql.get_fed_id(chat.id)
199
+
200
+ user_id = update.effective_message.from_user.id
201
+ if not await is_user_admin(update.effective_chat, user_id):
202
+ await update.effective_message.reply_text(
203
+ "You must be an admin to execute this command",
204
+ )
205
+ return
206
+
207
+ if not fed_id:
208
+ await update.effective_message.reply_text(
209
+ "This group is not in any federation!"
210
+ )
211
+ return
212
+
213
+ user = update.effective_user
214
+ chat = update.effective_chat
215
+ info = sql.get_fed_info(fed_id)
216
+
217
+ text = "This group is part of the following federation:"
218
+ text += "\n{} (ID: <code>{}</code>)".format(info["fname"], fed_id)
219
+
220
+ await update.effective_message.reply_text(text, parse_mode=ParseMode.HTML)
221
+
222
+
223
+ async def join_fed(update: Update, context: ContextTypes.DEFAULT_TYPE):
224
+ bot, args = context.bot, context.args
225
+ chat = update.effective_chat
226
+ user = update.effective_user
227
+
228
+ if chat.type == "private":
229
+ await send_message(
230
+ update.effective_message,
231
+ "This command is specific to the group, not to our pm!",
232
+ )
233
+ return
234
+
235
+ message = update.effective_message
236
+ administrators = await chat.get_administrators()
237
+ fed_id = sql.get_fed_id(chat.id)
238
+
239
+ if user.id in DRAGONS:
240
+ pass
241
+ else:
242
+ for admin in administrators:
243
+ status = admin.status
244
+ if status == "creator":
245
+ if str(admin.user.id) == str(user.id):
246
+ pass
247
+ else:
248
+ await update.effective_message.reply_text(
249
+ "Only group creators can use this command!",
250
+ )
251
+ return
252
+ if fed_id:
253
+ await message.reply_text("You cannot join two federations from one chat")
254
+ return
255
+
256
+ if len(args) >= 1:
257
+ getfed = sql.search_fed_by_id(args[0])
258
+ if getfed is False:
259
+ await message.reply_text("Please enter a valid federation ID")
260
+ return
261
+
262
+ x = sql.chat_join_fed(args[0], chat.title, chat.id)
263
+ if not x:
264
+ await message.reply_text(
265
+ f"Failed to join federation! Please contact @{SUPPORT_CHAT} should this problem persist!",
266
+ )
267
+ return
268
+
269
+ get_fedlog = await sql.get_fed_log(args[0])
270
+ if get_fedlog:
271
+ if ast.literal_eval(get_fedlog):
272
+ await bot.send_message(
273
+ get_fedlog,
274
+ "Chat *{}* has joined the federation *{}*".format(
275
+ chat.title,
276
+ getfed["fname"],
277
+ ),
278
+ parse_mode="markdown",
279
+ message_thread_id=message.message_thread_id
280
+ if chat.is_forum
281
+ else None,
282
+ )
283
+
284
+ await message.reply_text(
285
+ "This group has joined the federation: {}!".format(getfed["fname"]),
286
+ )
287
+
288
+
289
+ async def leave_fed(update: Update, context: ContextTypes.DEFAULT_TYPE):
290
+ bot, args = context.bot, context.args
291
+ chat = update.effective_chat
292
+ user = update.effective_user
293
+
294
+ if chat.type == "private":
295
+ await send_message(
296
+ update.effective_message,
297
+ "This command is specific to the group, not to our PM!",
298
+ )
299
+ return
300
+
301
+ fed_id = sql.get_fed_id(chat.id)
302
+ fed_info = sql.get_fed_info(fed_id)
303
+
304
+ # administrators = await chat.get_administrators().status
305
+ getuser = await bot.get_chat_member(chat.id, user.id).status
306
+ if getuser in "creator" or user.id in DRAGONS:
307
+ if sql.chat_leave_fed(chat.id) is True:
308
+ get_fedlog = await sql.get_fed_log(fed_id)
309
+ if get_fedlog:
310
+ if ast.literal_eval(get_fedlog):
311
+ await bot.send_message(
312
+ get_fedlog,
313
+ "Chat *{}* has left the federation *{}*".format(
314
+ chat.title,
315
+ fed_info["fname"],
316
+ ),
317
+ parse_mode="markdown",
318
+ message_thread_id=update.effective_message.message_thread_id
319
+ if chat.is_forum
320
+ else None,
321
+ )
322
+ await send_message(
323
+ update.effective_message,
324
+ "This group has left the federation {}!".format(fed_info["fname"]),
325
+ )
326
+ else:
327
+ await update.effective_message.reply_text(
328
+ "How can you leave a federation that you never joined?!",
329
+ )
330
+ else:
331
+ await update.effective_message.reply_text(
332
+ "Only group creators can use this command!"
333
+ )
334
+
335
+
336
+ async def user_join_fed(update: Update, context: ContextTypes.DEFAULT_TYPE):
337
+ bot, args = context.bot, context.args
338
+ chat = update.effective_chat
339
+ user = update.effective_user
340
+ msg = update.effective_message
341
+
342
+ if chat.type == "private":
343
+ await send_message(
344
+ update.effective_message,
345
+ "This command is specific to the group, not to our pm!",
346
+ )
347
+ return
348
+
349
+ fed_id = sql.get_fed_id(chat.id)
350
+
351
+ if is_user_fed_owner(fed_id, user.id) or user.id in DRAGONS:
352
+ user_id = await extract_user(msg, context, args)
353
+ if user_id:
354
+ user = await bot.get_chat(user_id)
355
+ elif not msg.reply_to_message and not args:
356
+ user = msg.from_user
357
+ elif not msg.reply_to_message and (
358
+ not args
359
+ or (
360
+ len(args) >= 1
361
+ and not args[0].startswith("@")
362
+ and not args[0].isdigit()
363
+ and not msg.parse_entities([MessageEntity.TEXT_MENTION])
364
+ )
365
+ ):
366
+ await msg.reply_text("I cannot extract user from this message")
367
+ return
368
+ else:
369
+ LOGGER.warning("error")
370
+ getuser = sql.search_user_in_fed(fed_id, user_id)
371
+ fed_id = sql.get_fed_id(chat.id)
372
+ info = sql.get_fed_info(fed_id)
373
+ get_owner = ast.literal_eval(info["fusers"])["owner"]
374
+ get_owner = await bot.get_chat(get_owner)
375
+ if isinstance(get_owner, ChatMember):
376
+ if user_id == get_owner.id:
377
+ await update.effective_message.reply_text(
378
+ "You do know that the user is the federation owner, right? RIGHT?",
379
+ )
380
+ return
381
+ if getuser:
382
+ await update.effective_message.reply_text(
383
+ "I cannot promote users who are already federation admins! Can remove them if you want!",
384
+ )
385
+ return
386
+ if user_id == bot.id:
387
+ await update.effective_message.reply_text(
388
+ "I already am a federation admin in all federations!",
389
+ )
390
+ return
391
+ res = sql.user_join_fed(fed_id, user_id)
392
+ if res:
393
+ await update.effective_message.reply_text("Successfully Promoted!")
394
+ else:
395
+ await update.effective_message.reply_text("Failed to promote!")
396
+ else:
397
+ await update.effective_message.reply_text("Only federation owners can do this!")
398
+
399
+
400
+ async def user_demote_fed(update: Update, context: ContextTypes.DEFAULT_TYPE):
401
+ bot, args = context.bot, context.args
402
+ chat = update.effective_chat
403
+ user = update.effective_user
404
+
405
+ if chat.type == "private":
406
+ await send_message(
407
+ update.effective_message,
408
+ "This command is specific to the group, not to our pm!",
409
+ )
410
+ return
411
+
412
+ fed_id = sql.get_fed_id(chat.id)
413
+
414
+ if is_user_fed_owner(fed_id, user.id):
415
+ msg = update.effective_message
416
+ user_id = await extract_user(msg, context, args)
417
+ if user_id:
418
+ user = await bot.get_chat(user_id)
419
+
420
+ elif not msg.reply_to_message and not args:
421
+ user = msg.from_user
422
+
423
+ elif not msg.reply_to_message and (
424
+ not args
425
+ or (
426
+ len(args) >= 1
427
+ and not args[0].startswith("@")
428
+ and not args[0].isdigit()
429
+ and not msg.parse_entities([MessageEntity.TEXT_MENTION])
430
+ )
431
+ ):
432
+ await msg.reply_text("I cannot extract user from this message")
433
+ return
434
+ else:
435
+ LOGGER.warning("error")
436
+
437
+ if user_id == bot.id:
438
+ await update.effective_message.reply_text(
439
+ "The thing you are trying to demote me from will fail to work without me! Just saying.",
440
+ )
441
+ return
442
+
443
+ if sql.search_user_in_fed(fed_id, user_id) is False:
444
+ await update.effective_message.reply_text(
445
+ "I cannot demote people who are not federation admins!",
446
+ )
447
+ return
448
+
449
+ res = sql.user_demote_fed(fed_id, user_id)
450
+ if res is True:
451
+ await update.effective_message.reply_text("Demoted from a Fed Admin!")
452
+ else:
453
+ await update.effective_message.reply_text("Demotion failed!")
454
+ else:
455
+ await update.effective_message.reply_text("Only federation owners can do this!")
456
+ return
457
+
458
+
459
+ async def fed_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
460
+ bot, args = context.bot, context.args
461
+ chat = update.effective_chat
462
+ user = update.effective_user
463
+ if args:
464
+ fed_id = args[0]
465
+ info = sql.get_fed_info(fed_id)
466
+ else:
467
+ if chat.type == "private":
468
+ await send_message(
469
+ update.effective_message,
470
+ "You need to provide me a fedid to check fedinfo in my pm.",
471
+ )
472
+ return
473
+ fed_id = sql.get_fed_id(chat.id)
474
+ if not fed_id:
475
+ await send_message(
476
+ update.effective_message,
477
+ "This group is not in any federation!",
478
+ )
479
+ return
480
+ info = sql.get_fed_info(fed_id)
481
+
482
+ if is_user_fed_admin(fed_id, user.id) is False:
483
+ await update.effective_message.reply_text(
484
+ "Only a federation admin can do this!"
485
+ )
486
+ return
487
+
488
+ owner = await bot.get_chat(info["owner"])
489
+ try:
490
+ owner_name = owner.first_name + " " + owner.last_name
491
+ except:
492
+ owner_name = owner.first_name
493
+ FEDADMIN = sql.all_fed_users(fed_id)
494
+ TotalAdminFed = len(FEDADMIN)
495
+
496
+ user = update.effective_user
497
+ chat = update.effective_chat
498
+ info = sql.get_fed_info(fed_id)
499
+
500
+ text = "<b>ℹ️ Federation Information:</b>"
501
+ text += "\nFedID: <code>{}</code>".format(fed_id)
502
+ text += "\nName: {}".format(info["fname"])
503
+ text += "\nCreator: {}".format(mention_html(owner.id, owner_name))
504
+ text += "\nAll Admins: <code>{}</code>".format(TotalAdminFed)
505
+ getfban = sql.get_all_fban_users(fed_id)
506
+ text += "\nTotal banned users: <code>{}</code>".format(len(getfban))
507
+ getfchat = sql.all_fed_chats(fed_id)
508
+ text += "\nNumber of groups in this federation: <code>{}</code>".format(
509
+ len(getfchat),
510
+ )
511
+
512
+ await update.effective_message.reply_text(text, parse_mode=ParseMode.HTML)
513
+
514
+
515
+ async def fed_admin(update: Update, context: ContextTypes.DEFAULT_TYPE):
516
+ bot, args = context.bot, context.args
517
+ chat = update.effective_chat
518
+ user = update.effective_user
519
+
520
+ if chat.type == "private":
521
+ await send_message(
522
+ update.effective_message,
523
+ "This command is specific to the group, not to our pm!",
524
+ )
525
+ return
526
+
527
+ fed_id = sql.get_fed_id(chat.id)
528
+
529
+ if not fed_id:
530
+ await update.effective_message.reply_text(
531
+ "This group is not in any federation!"
532
+ )
533
+ return
534
+
535
+ if is_user_fed_admin(fed_id, user.id) is False:
536
+ await update.effective_message.reply_text("Only federation admins can do this!")
537
+ return
538
+
539
+ user = update.effective_user
540
+ chat = update.effective_chat
541
+ info = sql.get_fed_info(fed_id)
542
+
543
+ text = "<b>Federation Admin {}:</b>\n\n".format(info["fname"])
544
+ text += "👑 Owner:\n"
545
+ owner = await bot.get_chat(info["owner"])
546
+ try:
547
+ owner_name = owner.first_name + " " + owner.last_name
548
+ except:
549
+ owner_name = owner.first_name
550
+ text += " • {}\n".format(mention_html(owner.id, owner_name))
551
+
552
+ members = sql.all_fed_members(fed_id)
553
+ if len(members) == 0:
554
+ text += "\n🔱 There are no admins in this federation"
555
+ else:
556
+ text += "\n🔱 Admin:\n"
557
+ for x in members:
558
+ user = await bot.get_chat(x)
559
+ text += " • {}\n".format(mention_html(user.id, user.first_name))
560
+
561
+ await update.effective_message.reply_text(text, parse_mode=ParseMode.HTML)
562
+
563
+
564
+ async def fed_ban(update: Update, context: ContextTypes.DEFAULT_TYPE):
565
+ bot, args = context.bot, context.args
566
+ chat = update.effective_chat
567
+ user = update.effective_user
568
+
569
+ if chat.type == "private":
570
+ await send_message(
571
+ update.effective_message,
572
+ "This command is specific to the group, not to our pm!",
573
+ )
574
+ return
575
+
576
+ fed_id = sql.get_fed_id(chat.id)
577
+
578
+ if not fed_id:
579
+ await update.effective_message.reply_text(
580
+ "This group is not a part of any federation!",
581
+ )
582
+ return
583
+
584
+ info = sql.get_fed_info(fed_id)
585
+ getfednotif = sql.user_feds_report(info["owner"])
586
+
587
+ if is_user_fed_admin(fed_id, user.id) is False:
588
+ await update.effective_message.reply_text("Only federation admins can do this!")
589
+ return
590
+
591
+ message = update.effective_message
592
+
593
+ user_id, reason = extract_unt_fedban(message, context, args)
594
+
595
+ fban, fbanreason, fbantime = sql.get_fban_user(fed_id, user_id)
596
+
597
+ if not user_id:
598
+ await message.reply_text("You don't seem to be referring to a user")
599
+ return
600
+
601
+ if user_id == bot.id:
602
+ await message.reply_text(
603
+ "What is funnier than kicking the group creator? Self sacrifice.",
604
+ )
605
+ return
606
+
607
+ if is_user_fed_owner(fed_id, user_id) is True:
608
+ await message.reply_text("Why did you try the federation fban?")
609
+ return
610
+
611
+ if is_user_fed_admin(fed_id, user_id) is True:
612
+ await message.reply_text("He is a federation admin, I can't fban him.")
613
+ return
614
+
615
+ if user_id == OWNER_ID:
616
+ await message.reply_text("Disaster level God cannot be fed banned!")
617
+ return
618
+
619
+ if int(user_id) in DRAGONS:
620
+ await message.reply_text("Dragons cannot be fed banned!")
621
+ return
622
+
623
+ if user_id in [777000, 1087968824]:
624
+ await message.reply_text("Fool! You can't attack Telegram's native tech!")
625
+ return
626
+
627
+ try:
628
+ user_chat = await bot.get_chat(user_id)
629
+ isvalid = True
630
+ fban_user_id = user_chat.id
631
+ fban_user_name = user_chat.first_name
632
+ fban_user_lname = user_chat.last_name
633
+ fban_user_uname = user_chat.username
634
+ except BadRequest as excp:
635
+ if not str(user_id).isdigit():
636
+ await send_message(update.effective_message, excp.message)
637
+ return
638
+ elif len(str(user_id)) != 9:
639
+ await send_message(update.effective_message, "That's so not a user!")
640
+ return
641
+ isvalid = False
642
+ fban_user_id = int(user_id)
643
+ fban_user_name = "user({})".format(user_id)
644
+ fban_user_lname = None
645
+ fban_user_uname = None
646
+
647
+ if isvalid and user_chat.type != "private":
648
+ await send_message(update.effective_message, "That's so not a user!")
649
+ return
650
+
651
+ if isvalid:
652
+ user_target = mention_html(fban_user_id, fban_user_name)
653
+ else:
654
+ user_target = fban_user_name
655
+
656
+ if fban:
657
+ fed_name = info["fname"]
658
+ # https://t.me/OnePunchSupport/41606 // https://t.me/OnePunchSupport/41619
659
+ # starting = "The reason fban is replaced for {} in the Federation <b>{}</b>.".format(user_target, fed_name)
660
+ # await send_message(update.effective_message, starting, parse_mode=ParseMode.HTML)
661
+
662
+ # if reason == "":
663
+ # reason = "No reason given."
664
+
665
+ temp = sql.un_fban_user(fed_id, fban_user_id)
666
+ if not temp:
667
+ await message.reply_text("Failed to update the reason for fedban!")
668
+ return
669
+ x = sql.fban_user(
670
+ fed_id,
671
+ fban_user_id,
672
+ fban_user_name,
673
+ fban_user_lname,
674
+ fban_user_uname,
675
+ reason,
676
+ int(time.time()),
677
+ )
678
+ if not x:
679
+ await message.reply_text(
680
+ f"Failed to ban from the federation! If this problem continues, contact @{SUPPORT_CHAT}.",
681
+ )
682
+ return
683
+
684
+ fed_chats = sql.all_fed_chats(fed_id)
685
+ # Will send to current chat
686
+ await bot.send_message(
687
+ chat.id,
688
+ "<b>FedBan reason updated</b>"
689
+ "\n<b>Federation:</b> {}"
690
+ "\n<b>Federation Admin:</b> {}"
691
+ "\n<b>User:</b> {}"
692
+ "\n<b>User ID:</b> <code>{}</code>"
693
+ "\n<b>Reason:</b> {}".format(
694
+ fed_name,
695
+ mention_html(user.id, user.first_name),
696
+ user_target,
697
+ fban_user_id,
698
+ reason,
699
+ ),
700
+ parse_mode="HTML",
701
+ )
702
+ # Send message to owner if fednotif is enabled
703
+ if getfednotif:
704
+ await bot.send_message(
705
+ info["owner"],
706
+ "<b>FedBan reason updated</b>"
707
+ "\n<b>Federation:</b> {}"
708
+ "\n<b>Federation Admin:</b> {}"
709
+ "\n<b>User:</b> {}"
710
+ "\n<b>User ID:</b> <code>{}</code>"
711
+ "\n<b>Reason:</b> {}".format(
712
+ fed_name,
713
+ mention_html(user.id, user.first_name),
714
+ user_target,
715
+ fban_user_id,
716
+ reason,
717
+ ),
718
+ parse_mode="HTML",
719
+ )
720
+ # If fedlog is set, then send message, except fedlog is current chat
721
+ get_fedlog = await sql.get_fed_log(fed_id)
722
+ if get_fedlog:
723
+ if int(get_fedlog) != int(chat.id):
724
+ await bot.send_message(
725
+ get_fedlog,
726
+ "<b>FedBan reason updated</b>"
727
+ "\n<b>Federation:</b> {}"
728
+ "\n<b>Federation Admin:</b> {}"
729
+ "\n<b>User:</b> {}"
730
+ "\n<b>User ID:</b> <code>{}</code>"
731
+ "\n<b>Reason:</b> {}".format(
732
+ fed_name,
733
+ mention_html(user.id, user.first_name),
734
+ user_target,
735
+ fban_user_id,
736
+ reason,
737
+ ),
738
+ parse_mode="HTML",
739
+ )
740
+ for fedschat in fed_chats:
741
+ try:
742
+ # Do not spam all fed chats
743
+ """
744
+ bot.send_message(chat, "<b>FedBan reason updated</b>" \
745
+ "\n<b>Federation:</b> {}" \
746
+ "\n<b>Federation Admin:</b> {}" \
747
+ "\n<b>User:</b> {}" \
748
+ "\n<b>User ID:</b> <code>{}</code>" \
749
+ "\n<b>Reason:</b> {}".format(fed_name, mention_html(user.id, user.first_name), user_target, fban_user_id, reason), parse_mode="HTML")
750
+ """
751
+ await bot.ban_chat_member(fedschat, fban_user_id)
752
+ except BadRequest as excp:
753
+ if excp.message in FBAN_ERRORS:
754
+ try:
755
+ await dispatcher.bot.getChat(fedschat)
756
+ except Forbidden:
757
+ sql.chat_leave_fed(fedschat)
758
+ LOGGER.info(
759
+ "Chat {} has leave fed {} because I was kicked".format(
760
+ fedschat,
761
+ info["fname"],
762
+ ),
763
+ )
764
+ continue
765
+ elif excp.message == "User_id_invalid":
766
+ break
767
+ else:
768
+ LOGGER.warning(
769
+ "Could not fban on {} because: {}".format(chat, excp.message),
770
+ )
771
+ except TelegramError:
772
+ pass
773
+ # Also do not spam all fed admins
774
+ """
775
+ send_to_list(bot, FEDADMIN,
776
+ "<b>FedBan reason updated</b>" \
777
+ "\n<b>Federation:</b> {}" \
778
+ "\n<b>Federation Admin:</b> {}" \
779
+ "\n<b>User:</b> {}" \
780
+ "\n<b>User ID:</b> <code>{}</code>" \
781
+ "\n<b>Reason:</b> {}".format(fed_name, mention_html(user.id, user.first_name), user_target, fban_user_id, reason),
782
+ html=True)
783
+ """
784
+
785
+ # Fban for fed subscriber
786
+ subscriber = list(sql.get_subscriber(fed_id))
787
+ if len(subscriber) != 0:
788
+ for fedsid in subscriber:
789
+ all_fedschat = sql.all_fed_chats(fedsid)
790
+ for fedschat in all_fedschat:
791
+ try:
792
+ await bot.ban_chat_member(fedschat, fban_user_id)
793
+ except BadRequest as excp:
794
+ if excp.message in FBAN_ERRORS:
795
+ try:
796
+ await dispatcher.bot.getChat(fedschat)
797
+ except Forbidden:
798
+ targetfed_id = sql.get_fed_id(fedschat)
799
+ sql.unsubs_fed(fed_id, targetfed_id)
800
+ LOGGER.info(
801
+ "Chat {} has unsub fed {} because I was kicked".format(
802
+ fedschat,
803
+ info["fname"],
804
+ ),
805
+ )
806
+ continue
807
+ elif excp.message == "User_id_invalid":
808
+ break
809
+ else:
810
+ LOGGER.warning(
811
+ "Unable to fban on {} because: {}".format(
812
+ fedschat,
813
+ excp.message,
814
+ ),
815
+ )
816
+ except TelegramError:
817
+ pass
818
+ # await send_message(update.effective_message, "Fedban Reason has been updated.")
819
+ return
820
+
821
+ fed_name = info["fname"]
822
+
823
+ # starting = "Starting a federation ban for {} in the Federation <b>{}</b>.".format(
824
+ # user_target, fed_name)
825
+ # await update.effective_message.reply_text(starting, parse_mode=ParseMode.HTML)
826
+
827
+ # if reason == "":
828
+ # reason = "No reason given."
829
+
830
+ x = sql.fban_user(
831
+ fed_id,
832
+ fban_user_id,
833
+ fban_user_name,
834
+ fban_user_lname,
835
+ fban_user_uname,
836
+ reason,
837
+ int(time.time()),
838
+ )
839
+ if not x:
840
+ await message.reply_text(
841
+ f"Failed to ban from the federation! If this problem continues, contact @{SUPPORT_CHAT}.",
842
+ )
843
+ return
844
+
845
+ fed_chats = sql.all_fed_chats(fed_id)
846
+ # Will send to current chat
847
+ await bot.send_message(
848
+ chat.id,
849
+ "<b>New FedBan</b>"
850
+ "\n<b>Federation:</b> {}"
851
+ "\n<b>Federation Admin:</b> {}"
852
+ "\n<b>User:</b> {}"
853
+ "\n<b>User ID:</b> <code>{}</code>"
854
+ "\n<b>Reason:</b> {}".format(
855
+ fed_name,
856
+ mention_html(user.id, user.first_name),
857
+ user_target,
858
+ fban_user_id,
859
+ reason,
860
+ ),
861
+ parse_mode="HTML",
862
+ )
863
+ # Send message to owner if fednotif is enabled
864
+ if getfednotif:
865
+ await bot.send_message(
866
+ info["owner"],
867
+ "<b>New FedBan</b>"
868
+ "\n<b>Federation:</b> {}"
869
+ "\n<b>Federation Admin:</b> {}"
870
+ "\n<b>User:</b> {}"
871
+ "\n<b>User ID:</b> <code>{}</code>"
872
+ "\n<b>Reason:</b> {}".format(
873
+ fed_name,
874
+ mention_html(user.id, user.first_name),
875
+ user_target,
876
+ fban_user_id,
877
+ reason,
878
+ ),
879
+ parse_mode="HTML",
880
+ )
881
+ # If fedlog is set, then send message, except fedlog is current chat
882
+ get_fedlog = await sql.get_fed_log(fed_id)
883
+ if get_fedlog:
884
+ if int(get_fedlog) != int(chat.id):
885
+ await bot.send_message(
886
+ get_fedlog,
887
+ "<b>New FedBan</b>"
888
+ "\n<b>Federation:</b> {}"
889
+ "\n<b>Federation Admin:</b> {}"
890
+ "\n<b>User:</b> {}"
891
+ "\n<b>User ID:</b> <code>{}</code>"
892
+ "\n<b>Reason:</b> {}".format(
893
+ fed_name,
894
+ mention_html(user.id, user.first_name),
895
+ user_target,
896
+ fban_user_id,
897
+ reason,
898
+ ),
899
+ parse_mode="HTML",
900
+ )
901
+ chats_in_fed = 0
902
+ for fedschat in fed_chats:
903
+ chats_in_fed += 1
904
+ try:
905
+ # Do not spamming all fed chats
906
+ """
907
+ bot.send_message(chat, "<b>FedBan reason updated</b>" \
908
+ "\n<b>Federation:</b> {}" \
909
+ "\n<b>Federation Admin:</b> {}" \
910
+ "\n<b>User:</b> {}" \
911
+ "\n<b>User ID:</b> <code>{}</code>" \
912
+ "\n<b>Reason:</b> {}".format(fed_name, mention_html(user.id, user.first_name), user_target, fban_user_id, reason), parse_mode="HTML")
913
+ """
914
+ await bot.ban_chat_member(fedschat, fban_user_id)
915
+ except BadRequest as excp:
916
+ if excp.message in FBAN_ERRORS:
917
+ pass
918
+ elif excp.message == "User_id_invalid":
919
+ break
920
+ else:
921
+ LOGGER.warning(
922
+ "Could not fban on {} because: {}".format(chat, excp.message),
923
+ )
924
+ except TelegramError:
925
+ pass
926
+
927
+ # Also do not spamming all fed admins
928
+ """
929
+ send_to_list(bot, FEDADMIN,
930
+ "<b>FedBan reason updated</b>" \
931
+ "\n<b>Federation:</b> {}" \
932
+ "\n<b>Federation Admin:</b> {}" \
933
+ "\n<b>User:</b> {}" \
934
+ "\n<b>User ID:</b> <code>{}</code>" \
935
+ "\n<b>Reason:</b> {}".format(fed_name, mention_html(user.id, user.first_name), user_target, fban_user_id, reason),
936
+ html=True)
937
+ """
938
+
939
+ # Fban for fed subscriber
940
+ subscriber = list(sql.get_subscriber(fed_id))
941
+ if len(subscriber) != 0:
942
+ for fedsid in subscriber:
943
+ all_fedschat = sql.all_fed_chats(fedsid)
944
+ for fedschat in all_fedschat:
945
+ try:
946
+ await bot.ban_chat_member(fedschat, fban_user_id)
947
+ except BadRequest as excp:
948
+ if excp.message in FBAN_ERRORS:
949
+ try:
950
+ await dispatcher.bot.getChat(fedschat)
951
+ except Forbidden:
952
+ targetfed_id = sql.get_fed_id(fedschat)
953
+ sql.unsubs_fed(fed_id, targetfed_id)
954
+ LOGGER.info(
955
+ "Chat {} has unsub fed {} because I was kicked".format(
956
+ fedschat,
957
+ info["fname"],
958
+ ),
959
+ )
960
+ continue
961
+ elif excp.message == "User_id_invalid":
962
+ break
963
+ else:
964
+ LOGGER.warning(
965
+ "Unable to fban on {} because: {}".format(
966
+ fedschat,
967
+ excp.message,
968
+ ),
969
+ )
970
+ except TelegramError:
971
+ pass
972
+
973
+
974
+ async def unfban(update: Update, context: ContextTypes.DEFAULT_TYPE):
975
+ bot, args = context.bot, context.args
976
+ chat = update.effective_chat
977
+ user = update.effective_user
978
+ message = update.effective_message
979
+
980
+ if chat.type == "private":
981
+ await send_message(
982
+ update.effective_message,
983
+ "This command is specific to the group, not to our pm!",
984
+ )
985
+ return
986
+
987
+ fed_id = sql.get_fed_id(chat.id)
988
+
989
+ if not fed_id:
990
+ await update.effective_message.reply_text(
991
+ "This group is not a part of any federation!",
992
+ )
993
+ return
994
+
995
+ info = sql.get_fed_info(fed_id)
996
+ getfednotif = sql.user_feds_report(info["owner"])
997
+
998
+ if is_user_fed_admin(fed_id, user.id) is False:
999
+ await update.effective_message.reply_text("Only federation admins can do this!")
1000
+ return
1001
+
1002
+ user_id = extract_user_fban(message, context, args)
1003
+ if not user_id:
1004
+ await message.reply_text("You do not seem to be referring to a user.")
1005
+ return
1006
+
1007
+ try:
1008
+ user_chat = await bot.get_chat(user_id)
1009
+ isvalid = True
1010
+ fban_user_id = user_chat.id
1011
+ fban_user_name = user_chat.first_name
1012
+ fban_user_lname = user_chat.last_name
1013
+ fban_user_uname = user_chat.username
1014
+ except BadRequest as excp:
1015
+ if not str(user_id).isdigit():
1016
+ await send_message(update.effective_message, excp.message)
1017
+ return
1018
+ elif len(str(user_id)) != 9:
1019
+ await send_message(update.effective_message, "That's so not a user!")
1020
+ return
1021
+ isvalid = False
1022
+ fban_user_id = int(user_id)
1023
+ fban_user_name = "user({})".format(user_id)
1024
+ fban_user_lname = None
1025
+ fban_user_uname = None
1026
+
1027
+ if isvalid and user_chat.type != "private":
1028
+ await message.reply_text("That's so not a user!")
1029
+ return
1030
+
1031
+ if isvalid:
1032
+ user_target = mention_html(fban_user_id, fban_user_name)
1033
+ else:
1034
+ user_target = fban_user_name
1035
+
1036
+ fban, fbanreason, fbantime = sql.get_fban_user(fed_id, fban_user_id)
1037
+ if fban is False:
1038
+ await message.reply_text("This user is not fbanned!")
1039
+ return
1040
+
1041
+ banner = update.effective_user
1042
+
1043
+ chat_list = sql.all_fed_chats(fed_id)
1044
+ # Will send to current chat
1045
+ await bot.send_message(
1046
+ chat.id,
1047
+ "<b>Un-FedBan</b>"
1048
+ "\n<b>Federation:</b> {}"
1049
+ "\n<b>Federation Admin:</b> {}"
1050
+ "\n<b>User:</b> {}"
1051
+ "\n<b>User ID:</b> <code>{}</code>".format(
1052
+ info["fname"],
1053
+ mention_html(user.id, user.first_name),
1054
+ user_target,
1055
+ fban_user_id,
1056
+ ),
1057
+ parse_mode="HTML",
1058
+ )
1059
+ # Send message to owner if fednotif is enabled
1060
+ if getfednotif:
1061
+ await bot.send_message(
1062
+ info["owner"],
1063
+ "<b>Un-FedBan</b>"
1064
+ "\n<b>Federation:</b> {}"
1065
+ "\n<b>Federation Admin:</b> {}"
1066
+ "\n<b>User:</b> {}"
1067
+ "\n<b>User ID:</b> <code>{}</code>".format(
1068
+ info["fname"],
1069
+ mention_html(user.id, user.first_name),
1070
+ user_target,
1071
+ fban_user_id,
1072
+ ),
1073
+ parse_mode="HTML",
1074
+ )
1075
+ # If fedlog is set, then send message, except fedlog is current chat
1076
+ get_fedlog = await sql.get_fed_log(fed_id)
1077
+ if get_fedlog:
1078
+ if int(get_fedlog) != int(chat.id):
1079
+ await bot.send_message(
1080
+ get_fedlog,
1081
+ "<b>Un-FedBan</b>"
1082
+ "\n<b>Federation:</b> {}"
1083
+ "\n<b>Federation Admin:</b> {}"
1084
+ "\n<b>User:</b> {}"
1085
+ "\n<b>User ID:</b> <code>{}</code>".format(
1086
+ info["fname"],
1087
+ mention_html(user.id, user.first_name),
1088
+ user_target,
1089
+ fban_user_id,
1090
+ ),
1091
+ parse_mode="HTML",
1092
+ )
1093
+ unfbanned_in_chats = 0
1094
+ for fedchats in chat_list:
1095
+ unfbanned_in_chats += 1
1096
+ try:
1097
+ member = await bot.get_chat_member(fedchats, user_id)
1098
+ if member.status == "kicked":
1099
+ await bot.unban_chat_member(fedchats, user_id)
1100
+ # Do not spamming all fed chats
1101
+ """
1102
+ bot.send_message(chat, "<b>Un-FedBan</b>" \
1103
+ "\n<b>Federation:</b> {}" \
1104
+ "\n<b>Federation Admin:</b> {}" \
1105
+ "\n<b>User:</b> {}" \
1106
+ "\n<b>User ID:</b> <code>{}</code>".format(info['fname'], mention_html(user.id, user.first_name), user_target, fban_user_id), parse_mode="HTML")
1107
+ """
1108
+ except BadRequest as excp:
1109
+ if excp.message in UNFBAN_ERRORS:
1110
+ pass
1111
+ elif excp.message == "User_id_invalid":
1112
+ break
1113
+ else:
1114
+ LOGGER.warning(
1115
+ "Could not fban on {} because: {}".format(chat, excp.message),
1116
+ )
1117
+ except TelegramError:
1118
+ pass
1119
+
1120
+ try:
1121
+ x = sql.un_fban_user(fed_id, user_id)
1122
+ if not x:
1123
+ await send_message(
1124
+ update.effective_message,
1125
+ "Un-fban failed, this user may already be un-fedbanned!",
1126
+ )
1127
+ return
1128
+ except:
1129
+ pass
1130
+
1131
+ # UnFban for fed subscriber
1132
+ subscriber = list(sql.get_subscriber(fed_id))
1133
+ if len(subscriber) != 0:
1134
+ for fedsid in subscriber:
1135
+ all_fedschat = sql.all_fed_chats(fedsid)
1136
+ for fedschat in all_fedschat:
1137
+ try:
1138
+ await bot.unban_chat_member(fedchats, user_id)
1139
+ except BadRequest as excp:
1140
+ if excp.message in FBAN_ERRORS:
1141
+ try:
1142
+ await dispatcher.bot.getChat(fedschat)
1143
+ except Forbidden:
1144
+ targetfed_id = sql.get_fed_id(fedschat)
1145
+ sql.unsubs_fed(fed_id, targetfed_id)
1146
+ LOGGER.info(
1147
+ "Chat {} has unsub fed {} because I was kicked".format(
1148
+ fedschat,
1149
+ info["fname"],
1150
+ ),
1151
+ )
1152
+ continue
1153
+ elif excp.message == "User_id_invalid":
1154
+ break
1155
+ else:
1156
+ LOGGER.warning(
1157
+ "Unable to fban on {} because: {}".format(
1158
+ fedschat,
1159
+ excp.message,
1160
+ ),
1161
+ )
1162
+ except TelegramError:
1163
+ pass
1164
+
1165
+ if unfbanned_in_chats == 0:
1166
+ await send_message(
1167
+ update.effective_message,
1168
+ "This person has been un-fbanned in 0 chats.",
1169
+ )
1170
+ if unfbanned_in_chats > 0:
1171
+ await send_message(
1172
+ update.effective_message,
1173
+ "This person has been un-fbanned in {} chats.".format(unfbanned_in_chats),
1174
+ )
1175
+ # Also do not spamming all fed admins
1176
+ """
1177
+ FEDADMIN = sql.all_fed_users(fed_id)
1178
+ for x in FEDADMIN:
1179
+ getreport = sql.user_feds_report(x)
1180
+ if getreport is False:
1181
+ FEDADMIN.remove(x)
1182
+ send_to_list(bot, FEDADMIN,
1183
+ "<b>Un-FedBan</b>" \
1184
+ "\n<b>Federation:</b> {}" \
1185
+ "\n<b>Federation Admin:</b> {}" \
1186
+ "\n<b>User:</b> {}" \
1187
+ "\n<b>User ID:</b> <code>{}</code>".format(info['fname'], mention_html(user.id, user.first_name),
1188
+ mention_html(user_chat.id, user_chat.first_name),
1189
+ user_chat.id),
1190
+ html=True)
1191
+ """
1192
+
1193
+
1194
+ async def set_frules(update: Update, context: ContextTypes.DEFAULT_TYPE):
1195
+ bot, args = context.bot, context.args
1196
+ chat = update.effective_chat
1197
+ user = update.effective_user
1198
+
1199
+ if chat.type == "private":
1200
+ await send_message(
1201
+ update.effective_message,
1202
+ "This command is specific to the group, not to our pm!",
1203
+ )
1204
+ return
1205
+
1206
+ fed_id = sql.get_fed_id(chat.id)
1207
+
1208
+ if not fed_id:
1209
+ await update.effective_message.reply_text(
1210
+ "This group is not in any federation!"
1211
+ )
1212
+ return
1213
+
1214
+ if is_user_fed_admin(fed_id, user.id) is False:
1215
+ await update.effective_message.reply_text("Only fed admins can do this!")
1216
+ return
1217
+
1218
+ if len(args) >= 1:
1219
+ msg = update.effective_message
1220
+ raw_text = msg.text
1221
+ args = raw_text.split(None, 1) # use python's maxsplit to separate cmd and args
1222
+ if len(args) == 2:
1223
+ txt = args[1]
1224
+ offset = len(txt) - len(raw_text) # set correct offset relative to command
1225
+ markdown_rules = markdown_parser(
1226
+ txt,
1227
+ entities=msg.parse_entities(),
1228
+ offset=offset,
1229
+ )
1230
+ x = sql.set_frules(fed_id, markdown_rules)
1231
+ if not x:
1232
+ await update.effective_message.reply_text(
1233
+ f"Whoa! There was an error while setting federation rules! If you wondered why please ask it in @{SUPPORT_CHAT}!",
1234
+ )
1235
+ return
1236
+
1237
+ rules = sql.get_fed_info(fed_id)["frules"]
1238
+ getfed = sql.get_fed_info(fed_id)
1239
+ get_fedlog = await sql.get_fed_log(fed_id)
1240
+ if get_fedlog:
1241
+ if ast.literal_eval(get_fedlog):
1242
+ await bot.send_message(
1243
+ get_fedlog,
1244
+ "*{}* has updated federation rules for fed *{}*".format(
1245
+ user.first_name,
1246
+ getfed["fname"],
1247
+ ),
1248
+ parse_mode="markdown",
1249
+ message_thread_id=update.effective_message.message_thread_id
1250
+ if chat.is_forum
1251
+ else None,
1252
+ )
1253
+ await update.effective_message.reply_text(
1254
+ f"Rules have been changed to :\n{rules}!"
1255
+ )
1256
+ else:
1257
+ await update.effective_message.reply_text("Please write rules to set this up!")
1258
+
1259
+
1260
+ async def get_frules(update: Update, context: ContextTypes.DEFAULT_TYPE):
1261
+ bot, args = context.bot, context.args
1262
+ chat = update.effective_chat
1263
+
1264
+ if chat.type == "private":
1265
+ await send_message(
1266
+ update.effective_message,
1267
+ "This command is specific to the group, not to our pm!",
1268
+ )
1269
+ return
1270
+
1271
+ fed_id = sql.get_fed_id(chat.id)
1272
+ if not fed_id:
1273
+ await update.effective_message.reply_text(
1274
+ "This group is not in any federation!"
1275
+ )
1276
+ return
1277
+
1278
+ rules = sql.get_frules(fed_id)
1279
+ text = "*Rules in this fed:*\n"
1280
+ text += rules
1281
+ await update.effective_message.reply_text(text, parse_mode=ParseMode.MARKDOWN)
1282
+
1283
+
1284
+ async def fed_broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
1285
+ bot, args = context.bot, context.args
1286
+ msg = update.effective_message
1287
+ user = update.effective_user
1288
+ chat = update.effective_chat
1289
+
1290
+ if chat.type == "private":
1291
+ await send_message(
1292
+ update.effective_message,
1293
+ "This command is specific to the group, not to our pm!",
1294
+ )
1295
+ return
1296
+
1297
+ if args:
1298
+ chat = update.effective_chat
1299
+ fed_id = sql.get_fed_id(chat.id)
1300
+ fedinfo = sql.get_fed_info(fed_id)
1301
+ if is_user_fed_owner(fed_id, user.id) is False:
1302
+ await update.effective_message.reply_text(
1303
+ "Only federation owners can do this!"
1304
+ )
1305
+ return
1306
+ # Parsing md
1307
+ raw_text = msg.text
1308
+ args = raw_text.split(None, 1) # use python's maxsplit to separate cmd and args
1309
+ txt = args[1]
1310
+ offset = len(txt) - len(raw_text) # set correct offset relative to command
1311
+ text_parser = markdown_parser(txt, entities=msg.parse_entities(), offset=offset)
1312
+ text = text_parser
1313
+ try:
1314
+ broadcaster = user.first_name
1315
+ except:
1316
+ broadcaster = user.first_name + " " + user.last_name
1317
+ text += "\n\n- {}".format(mention_markdown(user.id, broadcaster))
1318
+ chat_list = sql.all_fed_chats(fed_id)
1319
+ failed = 0
1320
+ for chat in chat_list:
1321
+ title = "*New broadcast from Fed {}*\n".format(fedinfo["fname"])
1322
+ try:
1323
+ await bot.sendMessage(
1324
+ chat,
1325
+ title + text,
1326
+ parse_mode="markdown",
1327
+ message_thread_id=msg.message_thread_id if chat.is_forum else None,
1328
+ )
1329
+ except TelegramError:
1330
+ try:
1331
+ await dispatcher.bot.getChat(chat)
1332
+ except Forbidden:
1333
+ failed += 1
1334
+ sql.chat_leave_fed(chat)
1335
+ LOGGER.info(
1336
+ "Chat {} has left fed {} because I was kicked".format(
1337
+ chat,
1338
+ fedinfo["fname"],
1339
+ ),
1340
+ )
1341
+ continue
1342
+ failed += 1
1343
+ LOGGER.warning("Couldn't send broadcast to {}".format(str(chat)))
1344
+
1345
+ send_text = "The federation broadcast is complete"
1346
+ if failed >= 1:
1347
+ send_text += "{} the group failed to receive the message, probably because it left the Federation.".format(
1348
+ failed,
1349
+ )
1350
+ await update.effective_message.reply_text(send_text)
1351
+
1352
+
1353
+ async def fed_ban_list(update: Update, context: ContextTypes.DEFAULT_TYPE):
1354
+ bot, args, chat_data = context.bot, context.args, context.chat_data
1355
+ chat = update.effective_chat
1356
+ user = update.effective_user
1357
+
1358
+ if chat.type == "private":
1359
+ await send_message(
1360
+ update.effective_message,
1361
+ "This command is specific to the group, not to our pm!",
1362
+ )
1363
+ return
1364
+
1365
+ fed_id = sql.get_fed_id(chat.id)
1366
+ info = sql.get_fed_info(fed_id)
1367
+
1368
+ if not fed_id:
1369
+ await update.effective_message.reply_text(
1370
+ "This group is not a part of any federation!",
1371
+ )
1372
+ return
1373
+
1374
+ if is_user_fed_owner(fed_id, user.id) is False:
1375
+ await update.effective_message.reply_text("Only Federation owners can do this!")
1376
+ return
1377
+
1378
+ user = update.effective_user
1379
+ chat = update.effective_chat
1380
+ getfban = sql.get_all_fban_users(fed_id)
1381
+ if len(getfban) == 0:
1382
+ await update.effective_message.reply_text(
1383
+ "The federation ban list of {} is empty".format(info["fname"]),
1384
+ parse_mode=ParseMode.HTML,
1385
+ )
1386
+ return
1387
+
1388
+ if args:
1389
+ if args[0] == "json":
1390
+ jam = time.time()
1391
+ new_jam = jam + 1800
1392
+ cek = get_chat(chat.id, chat_data)
1393
+ if cek.get("status"):
1394
+ if jam <= int(cek.get("value")):
1395
+ waktu = time.strftime(
1396
+ "%H:%M:%S %d/%m/%Y",
1397
+ time.localtime(cek.get("value")),
1398
+ )
1399
+ await update.effective_message.reply_text(
1400
+ "You can backup your data once every 30 minutes!\nYou can back up data again at `{}`".format(
1401
+ waktu,
1402
+ ),
1403
+ parse_mode=ParseMode.MARKDOWN,
1404
+ )
1405
+ return
1406
+ else:
1407
+ if user.id not in DRAGONS:
1408
+ put_chat(chat.id, new_jam, chat_data)
1409
+ else:
1410
+ if user.id not in DRAGONS:
1411
+ put_chat(chat.id, new_jam, chat_data)
1412
+ backups = ""
1413
+ for users in getfban:
1414
+ getuserinfo = sql.get_all_fban_users_target(fed_id, users)
1415
+ json_parser = {
1416
+ "user_id": users,
1417
+ "first_name": getuserinfo["first_name"],
1418
+ "last_name": getuserinfo["last_name"],
1419
+ "user_name": getuserinfo["user_name"],
1420
+ "reason": getuserinfo["reason"],
1421
+ }
1422
+ backups += json.dumps(json_parser)
1423
+ backups += "\n"
1424
+ with BytesIO(str.encode(backups)) as output:
1425
+ output.name = "mikobot_fbanned_users.json"
1426
+ await update.effective_message.reply_document(
1427
+ document=output,
1428
+ filename="mikobot_fbanned_users.json",
1429
+ caption="Total {} User are blocked by the Federation {}.".format(
1430
+ len(getfban),
1431
+ info["fname"],
1432
+ ),
1433
+ )
1434
+ return
1435
+ elif args[0] == "csv":
1436
+ jam = time.time()
1437
+ new_jam = jam + 1800
1438
+ cek = get_chat(chat.id, chat_data)
1439
+ if cek.get("status"):
1440
+ if jam <= int(cek.get("value")):
1441
+ waktu = time.strftime(
1442
+ "%H:%M:%S %d/%m/%Y",
1443
+ time.localtime(cek.get("value")),
1444
+ )
1445
+ await update.effective_message.reply_text(
1446
+ "You can back up data once every 30 minutes!\nYou can back up data again at `{}`".format(
1447
+ waktu,
1448
+ ),
1449
+ parse_mode=ParseMode.MARKDOWN,
1450
+ )
1451
+ return
1452
+ else:
1453
+ if user.id not in DRAGONS:
1454
+ put_chat(chat.id, new_jam, chat_data)
1455
+ else:
1456
+ if user.id not in DRAGONS:
1457
+ put_chat(chat.id, new_jam, chat_data)
1458
+ backups = "id,firstname,lastname,username,reason\n"
1459
+ for users in getfban:
1460
+ getuserinfo = sql.get_all_fban_users_target(fed_id, users)
1461
+ backups += (
1462
+ "{user_id},{first_name},{last_name},{user_name},{reason}".format(
1463
+ user_id=users,
1464
+ first_name=getuserinfo["first_name"],
1465
+ last_name=getuserinfo["last_name"],
1466
+ user_name=getuserinfo["user_name"],
1467
+ reason=getuserinfo["reason"],
1468
+ )
1469
+ )
1470
+ backups += "\n"
1471
+ with BytesIO(str.encode(backups)) as output:
1472
+ output.name = "mikobot_fbanned_users.csv"
1473
+ await update.effective_message.reply_document(
1474
+ document=output,
1475
+ filename="mikobot_fbanned_users.csv",
1476
+ caption="Total {} User are blocked by Federation {}.".format(
1477
+ len(getfban),
1478
+ info["fname"],
1479
+ ),
1480
+ )
1481
+ return
1482
+
1483
+ text = "<b>{} users have been banned from the federation {}:</b>\n".format(
1484
+ len(getfban),
1485
+ info["fname"],
1486
+ )
1487
+ for users in getfban:
1488
+ getuserinfo = sql.get_all_fban_users_target(fed_id, users)
1489
+ if getuserinfo is False:
1490
+ text = "There are no users banned from the federation {}".format(
1491
+ info["fname"],
1492
+ )
1493
+ break
1494
+ user_name = getuserinfo["first_name"]
1495
+ if getuserinfo["last_name"]:
1496
+ user_name += " " + getuserinfo["last_name"]
1497
+ text += " • {} (<code>{}</code>)\n".format(
1498
+ mention_html(users, user_name),
1499
+ users,
1500
+ )
1501
+
1502
+ try:
1503
+ await update.effective_message.reply_text(text, parse_mode=ParseMode.HTML)
1504
+ except:
1505
+ jam = time.time()
1506
+ new_jam = jam + 1800
1507
+ cek = get_chat(chat.id, chat_data)
1508
+ if cek.get("status"):
1509
+ if jam <= int(cek.get("value")):
1510
+ waktu = time.strftime(
1511
+ "%H:%M:%S %d/%m/%Y",
1512
+ time.localtime(cek.get("value")),
1513
+ )
1514
+ await update.effective_message.reply_text(
1515
+ "You can back up data once every 30 minutes!\nYou can back up data again at `{}`".format(
1516
+ waktu,
1517
+ ),
1518
+ parse_mode=ParseMode.MARKDOWN,
1519
+ )
1520
+ return
1521
+ else:
1522
+ if user.id not in DRAGONS:
1523
+ put_chat(chat.id, new_jam, chat_data)
1524
+ else:
1525
+ if user.id not in DRAGONS:
1526
+ put_chat(chat.id, new_jam, chat_data)
1527
+ cleanr = re.compile("<.*?>")
1528
+ cleantext = re.sub(cleanr, "", text)
1529
+ with BytesIO(str.encode(cleantext)) as output:
1530
+ output.name = "fbanlist.txt"
1531
+ await update.effective_message.reply_document(
1532
+ document=output,
1533
+ filename="fbanlist.txt",
1534
+ caption="The following is a list of users who are currently fbanned in the Federation {}.".format(
1535
+ info["fname"],
1536
+ ),
1537
+ )
1538
+
1539
+
1540
+ async def fed_notif(update: Update, context: ContextTypes.DEFAULT_TYPE):
1541
+ bot, args = context.bot, context.args
1542
+ chat = update.effective_chat
1543
+ user = update.effective_user
1544
+ msg = update.effective_message
1545
+ fed_id = sql.get_fed_id(chat.id)
1546
+
1547
+ if not fed_id:
1548
+ await update.effective_message.reply_text(
1549
+ "This group is not a part of any federation!",
1550
+ )
1551
+ return
1552
+
1553
+ if args:
1554
+ if args[0] in ("yes", "on"):
1555
+ sql.set_feds_setting(user.id, True)
1556
+ await msg.reply_text(
1557
+ "Reporting Federation back up! Every user who is fban / unfban you will be notified via PM.",
1558
+ )
1559
+ elif args[0] in ("no", "off"):
1560
+ sql.set_feds_setting(user.id, False)
1561
+ await msg.reply_text(
1562
+ "Reporting Federation has stopped! Every user who is fban / unfban you will not be notified via PM.",
1563
+ )
1564
+ else:
1565
+ await msg.reply_text("Please enter `on`/`off`", parse_mode="markdown")
1566
+ else:
1567
+ getreport = sql.user_feds_report(user.id)
1568
+ await msg.reply_text(
1569
+ "Your current Federation report preferences: `{}`".format(getreport),
1570
+ parse_mode="markdown",
1571
+ )
1572
+
1573
+
1574
+ async def fed_chats(update: Update, context: ContextTypes.DEFAULT_TYPE):
1575
+ bot, args = context.bot, context.args
1576
+ chat = update.effective_chat
1577
+ user = update.effective_user
1578
+
1579
+ if chat.type == "private":
1580
+ await send_message(
1581
+ update.effective_message,
1582
+ "This command is specific to the group, not to our pm!",
1583
+ )
1584
+ return
1585
+
1586
+ fed_id = sql.get_fed_id(chat.id)
1587
+ info = sql.get_fed_info(fed_id)
1588
+
1589
+ if not fed_id:
1590
+ await update.effective_message.reply_text(
1591
+ "This group is not a part of any federation!",
1592
+ )
1593
+ return
1594
+
1595
+ if is_user_fed_admin(fed_id, user.id) is False:
1596
+ await update.effective_message.reply_text("Only federation admins can do this!")
1597
+ return
1598
+
1599
+ getlist = sql.all_fed_chats(fed_id)
1600
+ if len(getlist) == 0:
1601
+ await update.effective_message.reply_text(
1602
+ "No users are fbanned from the federation {}".format(info["fname"]),
1603
+ parse_mode=ParseMode.HTML,
1604
+ )
1605
+ return
1606
+
1607
+ text = "<b>New chat joined the federation {}:</b>\n".format(info["fname"])
1608
+ for chats in getlist:
1609
+ try:
1610
+ chat_obj = await dispatcher.bot.getChat(chats)
1611
+ chat_name = chat_obj.title
1612
+ except Forbidden:
1613
+ sql.chat_leave_fed(chats)
1614
+ LOGGER.info(
1615
+ "Chat {} has leave fed {} because I was kicked".format(
1616
+ chats,
1617
+ info["fname"],
1618
+ ),
1619
+ )
1620
+ continue
1621
+ text += " • {} (<code>{}</code>)\n".format(chat_name, chats)
1622
+
1623
+ try:
1624
+ await update.effective_message.reply_text(text, parse_mode=ParseMode.HTML)
1625
+ except:
1626
+ cleanr = re.compile("<.*?>")
1627
+ cleantext = re.sub(cleanr, "", text)
1628
+ with BytesIO(str.encode(cleantext)) as output:
1629
+ output.name = "fedchats.txt"
1630
+ await update.effective_message.reply_document(
1631
+ document=output,
1632
+ filename="fedchats.txt",
1633
+ caption="Here is a list of all the chats that joined the federation {}.".format(
1634
+ info["fname"],
1635
+ ),
1636
+ )
1637
+
1638
+
1639
+ async def fed_import_bans(update: Update, context: ContextTypes.DEFAULT_TYPE):
1640
+ bot, chat_data = context.bot, context.chat_data
1641
+ chat = update.effective_chat
1642
+ user = update.effective_user
1643
+ msg = update.effective_message
1644
+
1645
+ if chat.type == "private":
1646
+ await send_message(
1647
+ update.effective_message,
1648
+ "This command is specific to the group, not to our pm!",
1649
+ )
1650
+ return
1651
+
1652
+ fed_id = sql.get_fed_id(chat.id)
1653
+ info = sql.get_fed_info(fed_id)
1654
+ getfed = sql.get_fed_info(fed_id)
1655
+
1656
+ if not fed_id:
1657
+ await update.effective_message.reply_text(
1658
+ "This group is not a part of any federation!",
1659
+ )
1660
+ return
1661
+
1662
+ if is_user_fed_owner(fed_id, user.id) is False:
1663
+ await update.effective_message.reply_text("Only Federation owners can do this!")
1664
+ return
1665
+
1666
+ if msg.reply_to_message and msg.reply_to_message.document:
1667
+ jam = time.time()
1668
+ new_jam = jam + 1800
1669
+ cek = get_chat(chat.id, chat_data)
1670
+ if cek.get("status"):
1671
+ if jam <= int(cek.get("value")):
1672
+ waktu = time.strftime(
1673
+ "%H:%M:%S %d/%m/%Y",
1674
+ time.localtime(cek.get("value")),
1675
+ )
1676
+ await update.effective_message.reply_text(
1677
+ "You can get your data once every 30 minutes!\nYou can get data again at `{}`".format(
1678
+ waktu,
1679
+ ),
1680
+ parse_mode=ParseMode.MARKDOWN,
1681
+ )
1682
+ return
1683
+ else:
1684
+ if user.id not in DRAGONS:
1685
+ put_chat(chat.id, new_jam, chat_data)
1686
+ else:
1687
+ if user.id not in DRAGONS:
1688
+ put_chat(chat.id, new_jam, chat_data)
1689
+ # if int(int(msg.reply_to_message.document.file_size)/1024) >= 200:
1690
+ # msg.reply_text("This file is too big!")
1691
+ # return
1692
+ success = 0
1693
+ failed = 0
1694
+ try:
1695
+ file_info = await bot.get_file(msg.reply_to_message.document.file_id)
1696
+ except BadRequest:
1697
+ await msg.reply_text(
1698
+ "Try downloading and re-uploading the file, this one seems broken!",
1699
+ )
1700
+ return
1701
+ fileformat = msg.reply_to_message.document.file_name.split(".")[-1]
1702
+ if fileformat == "json":
1703
+ multi_fed_id = []
1704
+ multi_import_userid = []
1705
+ multi_import_firstname = []
1706
+ multi_import_lastname = []
1707
+ multi_import_username = []
1708
+ multi_import_reason = []
1709
+ with BytesIO() as file:
1710
+ file_info.download_to_object(out=file)
1711
+ file.seek(0)
1712
+ reading = file.read().decode("UTF-8")
1713
+ splitting = reading.split("\n")
1714
+ for x in splitting:
1715
+ if x == "":
1716
+ continue
1717
+ try:
1718
+ data = json.loads(x)
1719
+ except json.decoder.JSONDecodeError as err:
1720
+ failed += 1
1721
+ continue
1722
+ try:
1723
+ import_userid = int(data["user_id"]) # Make sure it int
1724
+ import_firstname = str(data["first_name"])
1725
+ import_lastname = str(data["last_name"])
1726
+ import_username = str(data["user_name"])
1727
+ import_reason = str(data["reason"])
1728
+ except ValueError:
1729
+ failed += 1
1730
+ continue
1731
+ # Checking user
1732
+ if int(import_userid) == bot.id:
1733
+ failed += 1
1734
+ continue
1735
+ if is_user_fed_owner(fed_id, import_userid) is True:
1736
+ failed += 1
1737
+ continue
1738
+ if is_user_fed_admin(fed_id, import_userid) is True:
1739
+ failed += 1
1740
+ continue
1741
+ if str(import_userid) == str(OWNER_ID):
1742
+ failed += 1
1743
+ continue
1744
+ if int(import_userid) in DRAGONS:
1745
+ failed += 1
1746
+ continue
1747
+ multi_fed_id.append(fed_id)
1748
+ multi_import_userid.append(str(import_userid))
1749
+ multi_import_firstname.append(import_firstname)
1750
+ multi_import_lastname.append(import_lastname)
1751
+ multi_import_username.append(import_username)
1752
+ multi_import_reason.append(import_reason)
1753
+ success += 1
1754
+ sql.multi_fban_user(
1755
+ multi_fed_id,
1756
+ multi_import_userid,
1757
+ multi_import_firstname,
1758
+ multi_import_lastname,
1759
+ multi_import_username,
1760
+ multi_import_reason,
1761
+ )
1762
+ text = "Blocks were successfully imported. {} people are blocked.".format(
1763
+ success,
1764
+ )
1765
+ if failed >= 1:
1766
+ text += " {} Failed to import.".format(failed)
1767
+ get_fedlog = await sql.get_fed_log(fed_id)
1768
+ if get_fedlog:
1769
+ if ast.literal_eval(get_fedlog):
1770
+ teks = "Fed *{}* has successfully imported data. {} banned.".format(
1771
+ getfed["fname"],
1772
+ success,
1773
+ )
1774
+ if failed >= 1:
1775
+ teks += " {} Failed to import.".format(failed)
1776
+ await bot.send_message(
1777
+ get_fedlog,
1778
+ teks,
1779
+ parse_mode="markdown",
1780
+ message_thread_id=update.effective_message.message_thread_id
1781
+ if chat.is_forum
1782
+ else None,
1783
+ )
1784
+ elif fileformat == "csv":
1785
+ multi_fed_id = []
1786
+ multi_import_userid = []
1787
+ multi_import_firstname = []
1788
+ multi_import_lastname = []
1789
+ multi_import_username = []
1790
+ multi_import_reason = []
1791
+ file_info.download_to_drive(
1792
+ "fban_{}.csv".format(msg.reply_to_message.document.file_id),
1793
+ )
1794
+ with open(
1795
+ "fban_{}.csv".format(msg.reply_to_message.document.file_id),
1796
+ "r",
1797
+ encoding="utf8",
1798
+ ) as csvFile:
1799
+ reader = csv.reader(csvFile)
1800
+ for data in reader:
1801
+ try:
1802
+ import_userid = int(data[0]) # Make sure it int
1803
+ import_firstname = str(data[1])
1804
+ import_lastname = str(data[2])
1805
+ import_username = str(data[3])
1806
+ import_reason = str(data[4])
1807
+ except ValueError:
1808
+ failed += 1
1809
+ continue
1810
+ # Checking user
1811
+ if int(import_userid) == bot.id:
1812
+ failed += 1
1813
+ continue
1814
+ if is_user_fed_owner(fed_id, import_userid) is True:
1815
+ failed += 1
1816
+ continue
1817
+ if is_user_fed_admin(fed_id, import_userid) is True:
1818
+ failed += 1
1819
+ continue
1820
+ if str(import_userid) == str(OWNER_ID):
1821
+ failed += 1
1822
+ continue
1823
+ if int(import_userid) in DRAGONS:
1824
+ failed += 1
1825
+ continue
1826
+
1827
+ multi_fed_id.append(fed_id)
1828
+ multi_import_userid.append(str(import_userid))
1829
+ multi_import_firstname.append(import_firstname)
1830
+ multi_import_lastname.append(import_lastname)
1831
+ multi_import_username.append(import_username)
1832
+ multi_import_reason.append(import_reason)
1833
+ success += 1
1834
+ # t = ThreadWithReturnValue(target=sql.fban_user, args=(fed_id, str(import_userid), import_firstname, import_lastname, import_username, import_reason,))
1835
+ # t.start()
1836
+ sql.multi_fban_user(
1837
+ multi_fed_id,
1838
+ multi_import_userid,
1839
+ multi_import_firstname,
1840
+ multi_import_lastname,
1841
+ multi_import_username,
1842
+ multi_import_reason,
1843
+ )
1844
+ csvFile.close()
1845
+ os.remove("fban_{}.csv".format(msg.reply_to_message.document.file_id))
1846
+ text = "Files were imported successfully. {} people banned.".format(success)
1847
+ if failed >= 1:
1848
+ text += " {} Failed to import.".format(failed)
1849
+ get_fedlog = await sql.get_fed_log(fed_id)
1850
+ if get_fedlog:
1851
+ if ast.literal_eval(get_fedlog):
1852
+ teks = "Fed *{}* has successfully imported data. {} banned.".format(
1853
+ getfed["fname"],
1854
+ success,
1855
+ )
1856
+ if failed >= 1:
1857
+ teks += " {} Failed to import.".format(failed)
1858
+ await bot.send_message(
1859
+ get_fedlog,
1860
+ teks,
1861
+ parse_mode="markdown",
1862
+ message_thread_id=update.effective_message.message_thread_id
1863
+ if chat.is_forum
1864
+ else None,
1865
+ )
1866
+ else:
1867
+ await send_message(update.effective_message, "This file is not supported.")
1868
+ return
1869
+ await send_message(update.effective_message, text)
1870
+
1871
+
1872
+ async def del_fed_button(update: Update, context: ContextTypes.DEFAULT_TYPE):
1873
+ query = update.callback_query
1874
+ userid = query.message.chat.id
1875
+ fed_id = query.data.split("_")[1]
1876
+
1877
+ if fed_id == "cancel":
1878
+ await query.message.edit_text("Federation deletion cancelled")
1879
+ return
1880
+
1881
+ getfed = sql.get_fed_info(fed_id)
1882
+ if getfed:
1883
+ delete = sql.del_fed(fed_id)
1884
+ if delete:
1885
+ await query.message.edit_text(
1886
+ "You have removed your Federation! Now all the Groups that are connected with `{}` do not have a Federation.".format(
1887
+ getfed["fname"],
1888
+ ),
1889
+ parse_mode="markdown",
1890
+ )
1891
+
1892
+
1893
+ async def fed_stat_user(update: Update, context: ContextTypes.DEFAULT_TYPE):
1894
+ bot, args = context.bot, context.args
1895
+ chat = update.effective_chat
1896
+ user = update.effective_user
1897
+ msg = update.effective_message
1898
+
1899
+ if args:
1900
+ if args[0].isdigit():
1901
+ user_id = args[0]
1902
+ else:
1903
+ user_id = await extract_user(msg, context, args)
1904
+ else:
1905
+ user_id = await extract_user(msg, context, args)
1906
+
1907
+ if user_id:
1908
+ if len(args) == 2 and args[0].isdigit():
1909
+ fed_id = args[1]
1910
+ user_name, reason, fbantime = sql.get_user_fban(fed_id, str(user_id))
1911
+ if fbantime:
1912
+ fbantime = time.strftime("%d/%m/%Y", time.localtime(fbantime))
1913
+ else:
1914
+ fbantime = "Unavaiable"
1915
+ if user_name is False:
1916
+ await send_message(
1917
+ update.effective_message,
1918
+ "Fed {} not found!".format(fed_id),
1919
+ parse_mode="markdown",
1920
+ )
1921
+ return
1922
+ if user_name == "" or user_name is None:
1923
+ user_name = "He/she"
1924
+ if not reason:
1925
+ await send_message(
1926
+ update.effective_message,
1927
+ "{} is not banned in this federation!".format(user_name),
1928
+ )
1929
+ else:
1930
+ teks = "{} banned in this federation because:\n`{}`\n*Banned at:* `{}`".format(
1931
+ user_name,
1932
+ reason,
1933
+ fbantime,
1934
+ )
1935
+ await send_message(
1936
+ update.effective_message, teks, parse_mode="markdown"
1937
+ )
1938
+ return
1939
+ user_name, fbanlist = sql.get_user_fbanlist(str(user_id))
1940
+ if user_name == "":
1941
+ try:
1942
+ user_first = await bot.get_chat(user_id)
1943
+ if isinstance(user_first, ChatMember):
1944
+ user_name = user_id.first_name
1945
+ except BadRequest:
1946
+ user_name = "He/she"
1947
+ if user_name == "" or user_name is None:
1948
+ user_name = "He/she"
1949
+ if len(fbanlist) == 0:
1950
+ await send_message(
1951
+ update.effective_message,
1952
+ "{} is not banned in any federation!".format(user_name),
1953
+ )
1954
+ return
1955
+ else:
1956
+ teks = "{} has been banned in this federation:\n".format(user_name)
1957
+ for x in fbanlist:
1958
+ teks += "- `{}`: {}\n".format(x[0], x[1][:20])
1959
+ teks += "\nIf you want to find out more about the reasons for Fedban specifically, use /fbanstat <FedID>"
1960
+ await send_message(update.effective_message, teks, parse_mode="markdown")
1961
+
1962
+ elif not msg.reply_to_message and not args:
1963
+ user_id = msg.from_user.id
1964
+ user_name, fbanlist = sql.get_user_fbanlist(user_id)
1965
+ if user_name == "":
1966
+ user_name = msg.from_user.first_name
1967
+ if len(fbanlist) == 0:
1968
+ await send_message(
1969
+ update.effective_message,
1970
+ "{} is not banned in any federation!".format(user_name),
1971
+ )
1972
+ else:
1973
+ teks = "{} has been banned in this federation:\n".format(user_name)
1974
+ for x in fbanlist:
1975
+ teks += "- `{}`: {}\n".format(x[0], x[1][:20])
1976
+ teks += "\nIf you want to find out more about the reasons for Fedban specifically, use /fbanstat <FedID>"
1977
+ await send_message(update.effective_message, teks, parse_mode="markdown")
1978
+
1979
+ else:
1980
+ fed_id = args[0]
1981
+ fedinfo = sql.get_fed_info(fed_id)
1982
+ if not fedinfo:
1983
+ await send_message(
1984
+ update.effective_message, "Fed {} not found!".format(fed_id)
1985
+ )
1986
+ return
1987
+ name, reason, fbantime = sql.get_user_fban(fed_id, msg.from_user.id)
1988
+ if fbantime:
1989
+ fbantime = time.strftime("%d/%m/%Y", time.localtime(fbantime))
1990
+ else:
1991
+ fbantime = "Unavaiable"
1992
+ if not name:
1993
+ name = msg.from_user.first_name
1994
+ if not reason:
1995
+ await send_message(
1996
+ update.effective_message,
1997
+ "{} is not banned in this federation".format(name),
1998
+ )
1999
+ return
2000
+ await send_message(
2001
+ update.effective_message,
2002
+ "{} banned in this federation because:\n`{}`\n*Banned at:* `{}`".format(
2003
+ name,
2004
+ reason,
2005
+ fbantime,
2006
+ ),
2007
+ parse_mode="markdown",
2008
+ )
2009
+
2010
+
2011
+ async def set_fed_log(update: Update, context: ContextTypes.DEFAULT_TYPE):
2012
+ args = context.args
2013
+ chat = update.effective_chat
2014
+ user = update.effective_user
2015
+ msg = update.effective_message
2016
+
2017
+ if chat.type == "private":
2018
+ await send_message(
2019
+ update.effective_message,
2020
+ "This command is specific to the group, not to our pm!",
2021
+ )
2022
+ return
2023
+
2024
+ if args:
2025
+ fedinfo = sql.get_fed_info(args[0])
2026
+ if not fedinfo:
2027
+ await send_message(
2028
+ update.effective_message, "This Federation does not exist!"
2029
+ )
2030
+ return
2031
+ isowner = is_user_fed_owner(args[0], user.id)
2032
+ if not isowner:
2033
+ await send_message(
2034
+ update.effective_message,
2035
+ "Only federation creator can set federation logs.",
2036
+ )
2037
+ return
2038
+ setlog = sql.set_fed_log(args[0], chat.id)
2039
+ if setlog:
2040
+ await send_message(
2041
+ update.effective_message,
2042
+ "Federation log `{}` has been set to {}".format(
2043
+ fedinfo["fname"],
2044
+ chat.title,
2045
+ ),
2046
+ parse_mode="markdown",
2047
+ )
2048
+ else:
2049
+ await send_message(
2050
+ update.effective_message,
2051
+ "You have not provided your federated ID!",
2052
+ )
2053
+
2054
+
2055
+ async def unset_fed_log(update: Update, context: ContextTypes.DEFAULT_TYPE):
2056
+ args = context.args
2057
+ chat = update.effective_chat
2058
+ user = update.effective_user
2059
+ msg = update.effective_message
2060
+
2061
+ if chat.type == "private":
2062
+ await send_message(
2063
+ update.effective_message,
2064
+ "This command is specific to the group, not to our pm!",
2065
+ )
2066
+ return
2067
+
2068
+ if args:
2069
+ fedinfo = sql.get_fed_info(args[0])
2070
+ if not fedinfo:
2071
+ await send_message(
2072
+ update.effective_message, "This Federation does not exist!"
2073
+ )
2074
+ return
2075
+ isowner = is_user_fed_owner(args[0], user.id)
2076
+ if not isowner:
2077
+ await send_message(
2078
+ update.effective_message,
2079
+ "Only federation creator can set federation logs.",
2080
+ )
2081
+ return
2082
+ setlog = sql.set_fed_log(args[0], None)
2083
+ if setlog:
2084
+ await send_message(
2085
+ update.effective_message,
2086
+ "Federation log `{}` has been revoked on {}".format(
2087
+ fedinfo["fname"],
2088
+ chat.title,
2089
+ ),
2090
+ parse_mode="markdown",
2091
+ )
2092
+ else:
2093
+ await send_message(
2094
+ update.effective_message,
2095
+ "You have not provided your federated ID!",
2096
+ )
2097
+
2098
+
2099
+ async def subs_feds(update: Update, context: ContextTypes.DEFAULT_TYPE):
2100
+ bot, args = context.bot, context.args
2101
+ chat = update.effective_chat
2102
+ user = update.effective_user
2103
+ msg = update.effective_message
2104
+
2105
+ if chat.type == "private":
2106
+ await send_message(
2107
+ update.effective_message,
2108
+ "This command is specific to the group, not to our pm!",
2109
+ )
2110
+ return
2111
+
2112
+ fed_id = sql.get_fed_id(chat.id)
2113
+ fedinfo = sql.get_fed_info(fed_id)
2114
+
2115
+ if not fed_id:
2116
+ await send_message(
2117
+ update.effective_message, "This group is not in any federation!"
2118
+ )
2119
+ return
2120
+
2121
+ if is_user_fed_owner(fed_id, user.id) is False:
2122
+ await send_message(update.effective_message, "Only fed owner can do this!")
2123
+ return
2124
+
2125
+ if args:
2126
+ getfed = sql.search_fed_by_id(args[0])
2127
+ if getfed is False:
2128
+ await send_message(
2129
+ update.effective_message,
2130
+ "Please enter a valid federation id.",
2131
+ )
2132
+ return
2133
+ subfed = sql.subs_fed(args[0], fed_id)
2134
+ if subfed:
2135
+ await send_message(
2136
+ update.effective_message,
2137
+ "Federation `{}` has subscribe the federation `{}`. Every time there is a Fedban from that federation, this federation will also banned that user.".format(
2138
+ fedinfo["fname"],
2139
+ getfed["fname"],
2140
+ ),
2141
+ parse_mode="markdown",
2142
+ )
2143
+ get_fedlog = await sql.get_fed_log(args[0])
2144
+ if get_fedlog:
2145
+ if int(get_fedlog) != int(chat.id):
2146
+ await bot.send_message(
2147
+ get_fedlog,
2148
+ "Federation `{}` has subscribe the federation `{}`".format(
2149
+ fedinfo["fname"],
2150
+ getfed["fname"],
2151
+ ),
2152
+ parse_mode="markdown",
2153
+ message_thread_id=update.effective_message.message_thread_id
2154
+ if chat.is_forum
2155
+ else None,
2156
+ )
2157
+ else:
2158
+ await send_message(
2159
+ update.effective_message,
2160
+ "Federation `{}` already subscribe the federation `{}`.".format(
2161
+ fedinfo["fname"],
2162
+ getfed["fname"],
2163
+ ),
2164
+ parse_mode="markdown",
2165
+ )
2166
+ else:
2167
+ await send_message(
2168
+ update.effective_message,
2169
+ "You have not provided your federated ID!",
2170
+ )
2171
+
2172
+
2173
+ async def unsubs_feds(update: Update, context: ContextTypes.DEFAULT_TYPE):
2174
+ bot, args = context.bot, context.args
2175
+ chat = update.effective_chat
2176
+ user = update.effective_user
2177
+ msg = update.effective_message
2178
+
2179
+ if chat.type == "private":
2180
+ await send_message(
2181
+ update.effective_message,
2182
+ "This command is specific to the group, not to our pm!",
2183
+ )
2184
+ return
2185
+
2186
+ fed_id = sql.get_fed_id(chat.id)
2187
+ fedinfo = sql.get_fed_info(fed_id)
2188
+
2189
+ if not fed_id:
2190
+ await send_message(
2191
+ update.effective_message, "This group is not in any federation!"
2192
+ )
2193
+ return
2194
+
2195
+ if is_user_fed_owner(fed_id, user.id) is False:
2196
+ await send_message(update.effective_message, "Only fed owner can do this!")
2197
+ return
2198
+
2199
+ if args:
2200
+ getfed = sql.search_fed_by_id(args[0])
2201
+ if getfed is False:
2202
+ await send_message(
2203
+ update.effective_message,
2204
+ "Please enter a valid federation id.",
2205
+ )
2206
+ return
2207
+ subfed = sql.unsubs_fed(args[0], fed_id)
2208
+ if subfed:
2209
+ await send_message(
2210
+ update.effective_message,
2211
+ "Federation `{}` now unsubscribe fed `{}`.".format(
2212
+ fedinfo["fname"],
2213
+ getfed["fname"],
2214
+ ),
2215
+ parse_mode="markdown",
2216
+ )
2217
+ get_fedlog = await sql.get_fed_log(args[0])
2218
+ if get_fedlog:
2219
+ if int(get_fedlog) != int(chat.id):
2220
+ await bot.send_message(
2221
+ get_fedlog,
2222
+ "Federation `{}` has unsubscribe fed `{}`.".format(
2223
+ fedinfo["fname"],
2224
+ getfed["fname"],
2225
+ ),
2226
+ parse_mode="markdown",
2227
+ message_thread_id=update.effective_message.message_thread_id
2228
+ if chat.is_forum
2229
+ else None,
2230
+ )
2231
+ else:
2232
+ await send_message(
2233
+ update.effective_message,
2234
+ "Federation `{}` is not subscribing `{}`.".format(
2235
+ fedinfo["fname"],
2236
+ getfed["fname"],
2237
+ ),
2238
+ parse_mode="markdown",
2239
+ )
2240
+ else:
2241
+ await send_message(
2242
+ update.effective_message,
2243
+ "You have not provided your federated ID!",
2244
+ )
2245
+
2246
+
2247
+ async def get_myfedsubs(update: Update, context: ContextTypes.DEFAULT_TYPE):
2248
+ args = context.args
2249
+ chat = update.effective_chat
2250
+ user = update.effective_user
2251
+ msg = update.effective_message
2252
+
2253
+ if chat.type == "private":
2254
+ await send_message(
2255
+ update.effective_message,
2256
+ "This command is specific to the group, not to our pm!",
2257
+ )
2258
+ return
2259
+
2260
+ fed_id = sql.get_fed_id(chat.id)
2261
+ fedinfo = sql.get_fed_info(fed_id)
2262
+
2263
+ if not fed_id:
2264
+ await send_message(
2265
+ update.effective_message, "This group is not in any federation!"
2266
+ )
2267
+ return
2268
+
2269
+ if is_user_fed_owner(fed_id, user.id) is False:
2270
+ await send_message(update.effective_message, "Only fed owner can do this!")
2271
+ return
2272
+
2273
+ try:
2274
+ getmy = sql.get_mysubs(fed_id)
2275
+ except:
2276
+ getmy = []
2277
+
2278
+ if len(getmy) == 0:
2279
+ await send_message(
2280
+ update.effective_message,
2281
+ "Federation `{}` is not subscribing any federation.".format(
2282
+ fedinfo["fname"],
2283
+ ),
2284
+ parse_mode="markdown",
2285
+ )
2286
+ return
2287
+ else:
2288
+ listfed = "Federation `{}` is subscribing federation:\n".format(
2289
+ fedinfo["fname"],
2290
+ )
2291
+ for x in getmy:
2292
+ listfed += "- `{}`\n".format(x)
2293
+ listfed += (
2294
+ "\nTo get fed info `/fedinfo <fedid>`. To unsubscribe `/unsubfed <fedid>`."
2295
+ )
2296
+ await send_message(update.effective_message, listfed, parse_mode="markdown")
2297
+
2298
+
2299
+ async def get_myfeds_list(update: Update, context: ContextTypes.DEFAULT_TYPE):
2300
+ chat = update.effective_chat
2301
+ user = update.effective_user
2302
+ msg = update.effective_message
2303
+
2304
+ fedowner = sql.get_user_owner_fed_full(user.id)
2305
+ if fedowner:
2306
+ text = "*You are owner of feds:\n*"
2307
+ for f in fedowner:
2308
+ text += "- `{}`: *{}*\n".format(f["fed_id"], f["fed"]["fname"])
2309
+ else:
2310
+ text = "*You are not have any feds!*"
2311
+ await send_message(update.effective_message, text, parse_mode="markdown")
2312
+
2313
+
2314
+ def is_user_fed_admin(fed_id, user_id):
2315
+ fed_admins = sql.all_fed_users(fed_id)
2316
+ if fed_admins is False:
2317
+ return False
2318
+ if int(user_id) in fed_admins or int(user_id) == OWNER_ID:
2319
+ return True
2320
+ else:
2321
+ return False
2322
+
2323
+
2324
+ def is_user_fed_owner(fed_id, user_id):
2325
+ getsql = sql.get_fed_info(fed_id)
2326
+ if getsql is False:
2327
+ return False
2328
+ getfedowner = ast.literal_eval(getsql["fusers"])
2329
+ if getfedowner is None or getfedowner is False:
2330
+ return False
2331
+ getfedowner = getfedowner["owner"]
2332
+ if str(user_id) == getfedowner or int(user_id) == OWNER_ID:
2333
+ return True
2334
+ else:
2335
+ return False
2336
+
2337
+
2338
+ # There's no handler for this yet, but updating for v12 in case its used
2339
+
2340
+
2341
+ async def welcome_fed(update: Update, context: ContextTypes.DEFAULT_TYPE):
2342
+ bot, args = context.bot, context.args
2343
+ chat = update.effective_chat
2344
+ user = update.effective_user
2345
+ fed_id = sql.get_fed_id(chat.id)
2346
+ fban, fbanreason, fbantime = sql.get_fban_user(fed_id, user.id)
2347
+ if fban:
2348
+ await update.effective_message.reply_text(
2349
+ "This user is banned in current federation! I will remove him.",
2350
+ )
2351
+ await bot.ban_chat_member(chat.id, user.id)
2352
+ return True
2353
+ else:
2354
+ return False
2355
+
2356
+
2357
+ def __stats__():
2358
+ all_fbanned = sql.get_all_fban_users_global()
2359
+ all_feds = sql.get_all_feds_users_global()
2360
+ return "• {} banned users across {} Federations".format(
2361
+ len(all_fbanned),
2362
+ len(all_feds),
2363
+ )
2364
+
2365
+
2366
+ def __user_info__(user_id, chat_id):
2367
+ fed_id = sql.get_fed_id(chat_id)
2368
+ if fed_id:
2369
+ fban, fbanreason, fbantime = sql.get_fban_user(fed_id, user_id)
2370
+ info = sql.get_fed_info(fed_id)
2371
+ infoname = info["fname"]
2372
+
2373
+ if int(info["owner"]) == user_id:
2374
+ text = "Federation owner of: <b>{}</b>.".format(infoname)
2375
+ elif is_user_fed_admin(fed_id, user_id):
2376
+ text = "Federation admin of: <b>{}</b>.".format(infoname)
2377
+
2378
+ elif fban:
2379
+ text = "Federation banned: <b>Yes</b>"
2380
+ text += "\n<b>Reason:</b> {}".format(fbanreason)
2381
+ else:
2382
+ text = "Federation banned: <b>No</b>"
2383
+ else:
2384
+ text = ""
2385
+ return text
2386
+
2387
+
2388
+ # Temporary data
2389
+ def put_chat(chat_id, value, chat_data):
2390
+ # print(chat_data)
2391
+ if value is False:
2392
+ status = False
2393
+ else:
2394
+ status = True
2395
+ chat_data[chat_id] = {"federation": {"status": status, "value": value}}
2396
+
2397
+
2398
+ def get_chat(chat_id, chat_data):
2399
+ # print(chat_data)
2400
+ try:
2401
+ value = chat_data[chat_id]["federation"]
2402
+ return value
2403
+ except KeyError:
2404
+ return {"status": False, "value": False}
2405
+
2406
+
2407
+ async def fed_owner_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
2408
+ await update.effective_message.reply_text(
2409
+ """*👑 Fed Owner Only:*
2410
+ » `/newfed <fed_name>`*:* Creates a Federation, One allowed per user
2411
+ » `/renamefed <fed_id> <new_fed_name>`*:* Renames the fed id to a new name
2412
+ » `/delfed <fed_id>`*:* Delete a Federation, and any information related to it. Will not cancel blocked users
2413
+ » `/fpromote <user>`*:* Assigns the user as a federation admin. Enables all commands for the user under `Fed Admins`
2414
+ » `/fdemote <user>`*:* Drops the User from the admin Federation to a normal User
2415
+ » `/subfed <fed_id>`*:* Subscribes to a given fed ID, bans from that subscribed fed will also happen in your fed
2416
+ » `/unsubfed <fed_id>`*:* Unsubscribes to a given fed ID
2417
+ » `/setfedlog <fed_id>`*:* Sets the group as a fed log report base for the federation
2418
+ » `/unsetfedlog <fed_id>`*:* Removed the group as a fed log report base for the federation
2419
+ » `/fbroadcast <message>`*:* Broadcasts a messages to all groups that have joined your fed
2420
+ » `/fedsubs`*:* Shows the feds your group is subscribed to `(broken rn)`""",
2421
+ parse_mode=ParseMode.MARKDOWN,
2422
+ )
2423
+
2424
+
2425
+ async def fed_admin_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
2426
+ await update.effective_message.reply_text(
2427
+ """*🔱 Fed Admins:*
2428
+ » `/fban <user> <reason>`*:* Fed bans a user
2429
+ » `/unfban <user> <reason>`*:* Removes a user from a fed ban
2430
+ » `/fedinfo <fed_id>`*:* Information about the specified Federation
2431
+ » `/joinfed <fed_id>`*:* Join the current chat to the Federation. Only chat owners can do this. Every chat can only be in one Federation
2432
+ » `/leavefed <fed_id>`*:* Leave the Federation given. Only chat owners can do this
2433
+ » `/setfrules <rules>`*:* Arrange Federation rules
2434
+ » `/fedadmins`*:* Show Federation admin
2435
+ » `/fbanlist`*:* Displays all users who are victimized at the Federation at this time
2436
+ » `/fedchats`*:* Get all the chats that are connected in the Federation
2437
+ » `/chatfed `*:* See the Federation in the current chat\n""",
2438
+ parse_mode=ParseMode.MARKDOWN,
2439
+ )
2440
+
2441
+
2442
+ async def fed_user_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
2443
+ await update.effective_message.reply_text(
2444
+ """*🎩 Any user:*
2445
+ » `/fbanstat`*:* Shows if you/or the user you are replying to or their username is fbanned somewhere or not
2446
+ » `/fednotif <on/off>`*:* Federation settings not in PM when there are users who are fbaned/unfbanned
2447
+ » `/frules`*:* See Federation regulations\n""",
2448
+ parse_mode=ParseMode.MARKDOWN,
2449
+ )
2450
+
2451
+
2452
+ # <=================================================== HELP ====================================================>
2453
+
2454
+
2455
+ __mod_name__ = "FEDS"
2456
+
2457
+ __help__ = """
2458
+ ➠ *Everything is fun, until a spammer starts entering your group, and you have to block it. Then you need to start banning more, and more, and it hurts*.
2459
+ *But then you have many groups, and you don't want this spammer to be in one of your groups - how can you deal? Do you have to manually block it, in all your groups*?\n
2460
+ *No longer!* *With Federation, you can make a ban in one chat overlap with all other chats*.\n
2461
+ *You can even designate federation admins, so your trusted admin can ban all the spammers from chats you want to protect*.\n
2462
+
2463
+ ➠ *Commands:*
2464
+ ➠ Feds are now divided into 3 sections for your ease.
2465
+
2466
+ » /fedownerhelp: Provides help for fed creation and owner only commands.
2467
+
2468
+ » /fedadminhelp: Provides help for fed administration commands.
2469
+
2470
+ » /feduserhelp: Provides help for commands anyone can use.
2471
+
2472
+ """
2473
+
2474
+ # <================================================ HANDLER =======================================================>
2475
+ function(CommandHandler("newfed", new_fed, block=False))
2476
+ function(CommandHandler("delfed", del_fed, block=False))
2477
+ function(CommandHandler("renamefed", rename_fed, block=False))
2478
+ function(CommandHandler("joinfed", join_fed, block=False))
2479
+ function(CommandHandler("leavefed", leave_fed, block=False))
2480
+ function(CommandHandler("fpromote", user_join_fed, block=False))
2481
+ function(CommandHandler("fdemote", user_demote_fed, block=False))
2482
+ function(CommandHandler("fedinfo", fed_info, block=False))
2483
+ function(DisableAbleCommandHandler("fban", fed_ban, block=False))
2484
+ function(CommandHandler("unfban", unfban, block=False))
2485
+ function(CommandHandler("fbroadcast", fed_broadcast, block=False))
2486
+ function(CommandHandler("setfrules", set_frules, block=False))
2487
+ function(CommandHandler("frules", get_frules, block=False))
2488
+ function(CommandHandler("chatfed", fed_chat, block=False))
2489
+ function(CommandHandler("fedadmins", fed_admin, block=False))
2490
+ function(CommandHandler("fbanlist", fed_ban_list, block=False))
2491
+ function(CommandHandler("fednotif", fed_notif, block=False))
2492
+ function(CommandHandler("fedchats", fed_chats, block=False))
2493
+ function(CommandHandler("importfbans", fed_import_bans, block=False))
2494
+ function(DisableAbleCommandHandler(["fedstat", "fbanstat"], fed_stat_user, block=False))
2495
+ function(CommandHandler("setfedlog", set_fed_log, block=False))
2496
+ function(CommandHandler("unsetfedlog", unset_fed_log, block=False))
2497
+ function(CommandHandler("subfed", subs_feds, block=False))
2498
+ function(CommandHandler("unsubfed", unsubs_feds, block=False))
2499
+ function(CommandHandler("fedsubs", get_myfedsubs, block=False))
2500
+ function(CommandHandler("myfeds", get_myfeds_list, block=False))
2501
+ function(CallbackQueryHandler(del_fed_button, pattern=r"rmfed_", block=False))
2502
+ function(CommandHandler("fedownerhelp", fed_owner_help, block=False))
2503
+ function(CommandHandler("fedadminhelp", fed_admin_help, block=False))
2504
+ function(CommandHandler("feduserhelp", fed_user_help, block=False))
2505
+ # <================================================ END =======================================================>