feds.py 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. """
  2. MIT License
  3. Copyright (c) 2023 SI_NN_ER_LS
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. """
  20. import asyncio
  21. import uuid
  22. from pyrogram import filters
  23. from pyrogram.enums import ChatMemberStatus, ChatType, ParseMode
  24. from pyrogram.errors import FloodWait
  25. from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
  26. from wbb import BOT_ID, LOG_GROUP_ID, SUDOERS, app
  27. from wbb.core.decorators.errors import capture_err
  28. from wbb.utils.dbfeds import *
  29. from wbb.utils.functions import extract_user, extract_user_and_reason
  30. __MODULE__ = "Federation"
  31. __HELP__ = """
  32. 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.
  33. 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
  34. **No longer!** With Federation, you can make a ban in one chat overlap with all other chats.\n
  35. You can even designate federation admins, so your trusted admin can ban all the spammers from chats you want to protect.\n\n
  36. """
  37. SUPPORT_CHAT = "@WBBSupport"
  38. @app.on_message(filters.command("newfed"))
  39. @capture_err
  40. async def new_fed(client, message):
  41. chat = message.chat
  42. user = message.from_user
  43. if message.chat.type != ChatType.PRIVATE:
  44. await message.reply_text(
  45. "Federations can only be created by privately messaging me."
  46. )
  47. return
  48. if len(message.command) < 2:
  49. await message.reply_text("Please write the name of the federation!")
  50. return
  51. fednam = message.text.split(None, 1)[1]
  52. if not fednam == "":
  53. fed_id = str(uuid.uuid4())
  54. fed_name = fednam
  55. x = await fedsdb.update_one(
  56. {"fed_id": str(fed_id)},
  57. {
  58. "$set": {
  59. "fed_name": str(fed_name),
  60. "owner_id": int(user.id),
  61. "fadmins": [],
  62. "owner_mention": user.mention,
  63. "banned_users": [],
  64. "chat_ids": [],
  65. "log_group_id": LOG_GROUP_ID,
  66. }
  67. },
  68. upsert=True,
  69. )
  70. if not x:
  71. await message.reply_text(
  72. f"Can't federate! Please contact {SUPPORT_CHAT} if the problem persist."
  73. )
  74. return
  75. await message.reply_text(
  76. "**You have succeeded in creating a new federation!**"
  77. "\nName: `{}`"
  78. "\nID: `{}`"
  79. "\n\nUse the command below to join the federation:"
  80. "\n`/joinfed {}`".format(fed_name, fed_id, fed_id),
  81. parse_mode=ParseMode.MARKDOWN,
  82. )
  83. try:
  84. await app.send_message(
  85. LOG_GROUP_ID,
  86. "New Federation: <b>{}</b>\nID: <pre>{}</pre>".format(
  87. fed_name, fed_id
  88. ),
  89. parse_mode=ParseMode.HTML,
  90. )
  91. except:
  92. log.info("Cannot send a message to EVENT_LOGS")
  93. else:
  94. await message.reply_text(
  95. "Please write down the name of the federation"
  96. )
  97. @app.on_message(filters.command("delfed"))
  98. @capture_err
  99. async def del_fed(client, message):
  100. chat = message.chat
  101. user = message.from_user
  102. if message.chat.type != ChatType.PRIVATE:
  103. await message.reply_text(
  104. "Federations can only be deleted by privately messaging me."
  105. )
  106. return
  107. args = message.text.split(" ", 1)
  108. if len(args) > 1:
  109. is_fed_id = args[1].strip()
  110. getinfo = await get_fed_info(is_fed_id)
  111. if getinfo is False:
  112. await message.reply_text("This federation does not exist.")
  113. return
  114. if getinfo["owner_id"] == user.id or user.id == SUDOERS:
  115. fed_id = is_fed_id
  116. else:
  117. await message.reply_text("Only federation owners can do this!")
  118. return
  119. else:
  120. await message.reply_text("What should I delete?")
  121. return
  122. is_owner = await is_user_fed_owner(fed_id, user.id)
  123. if is_owner is False:
  124. await message.reply_text("Only federation owners can do this!")
  125. return
  126. await message.reply_text(
  127. "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(
  128. getinfo["fed_name"]
  129. ),
  130. reply_markup=InlineKeyboardMarkup(
  131. [
  132. [
  133. InlineKeyboardButton(
  134. "⚠️ Delete Federation ⚠️",
  135. callback_data=f"rmfed_{fed_id}",
  136. )
  137. ],
  138. [InlineKeyboardButton("Cancel", callback_data="rmfed_cancel")],
  139. ]
  140. ),
  141. )
  142. @app.on_message(filters.command("fedtransfer"))
  143. @capture_err
  144. async def fedtransfer(client, message):
  145. chat = message.chat
  146. user = message.from_user
  147. if message.chat.type != ChatType.PRIVATE:
  148. await message.reply_text(
  149. "Federations can only be transferred by privately messaging me."
  150. )
  151. return
  152. is_feds = await get_feds_by_owner(int(user.id))
  153. if not is_feds:
  154. return await message.reply_text(
  155. "**You haven't created any federations.**"
  156. )
  157. if len(message.command) < 2:
  158. return await message.reply_text(
  159. "**You needed to specify a user or reply to their message!**"
  160. )
  161. user_id, fed_id = await extract_user_and_reason(message)
  162. if not user_id:
  163. return await message.reply_text("I can't find that user.")
  164. if not fed_id:
  165. return await message.reply(
  166. "you need to provide a Fed Id.\n\nUsage:\n/fedtransfer @usename Fed_Id."
  167. )
  168. is_owner = await is_user_fed_owner(fed_id, user.id)
  169. if is_owner is False:
  170. await message.reply_text("Only federation owners can do this!")
  171. return
  172. await message.reply_text(
  173. "**You sure you want to transfer your federation? This cannot be reverted.**",
  174. reply_markup=InlineKeyboardMarkup(
  175. [
  176. [
  177. InlineKeyboardButton(
  178. "⚠️ Transfer Federation ⚠️",
  179. callback_data=f"trfed_{user_id}|{fed_id}",
  180. )
  181. ],
  182. [InlineKeyboardButton("Cancel", callback_data="trfed_cancel")],
  183. ]
  184. ),
  185. )
  186. @app.on_message(filters.command("myfeds"))
  187. @capture_err
  188. async def myfeds(client, message):
  189. user = message.from_user
  190. is_feds = await get_feds_by_owner(int(user.id))
  191. if is_feds:
  192. response_text = "\n\n".join(
  193. [
  194. f"{i + 1}.\n**Fed Name:** {fed['fed_name']}\n**Fed Id:** `{fed['fed_id']}`"
  195. for i, fed in enumerate(is_feds)
  196. ]
  197. )
  198. await message.reply_text(
  199. f"**Here are the federations you have created:**\n\n{response_text}"
  200. )
  201. else:
  202. await message.reply_text("**You haven't created any federations.**")
  203. @app.on_message(filters.command("renamefed"))
  204. @capture_err
  205. async def rename_fed(client, message):
  206. user = message.from_user
  207. msg = message
  208. args = msg.text.split(None, 2)
  209. if len(args) < 3:
  210. return await msg.reply_text("usage: /renamefed <fed_id> <newname>")
  211. fed_id, newname = args[1], args[2]
  212. verify_fed = await get_fed_info(fed_id)
  213. if not verify_fed:
  214. return await msg.reply_text("This fed does not exist in my database!")
  215. if await is_user_fed_owner(fed_id, user.id):
  216. fedsdb.update_one(
  217. {"fed_id": str(fed_id)},
  218. {"$set": {"fed_name": str(newname), "owner_id": int(user.id)}},
  219. upsert=True,
  220. )
  221. await msg.reply_text(
  222. f"Successfully renamed your fed name to {newname}!"
  223. )
  224. else:
  225. await msg.reply_text("Only federation owner can do this!")
  226. @app.on_message(filters.command(["setfedlog", "unsetfedlog"]))
  227. @capture_err
  228. async def fed_log(client, message):
  229. chat = message.chat
  230. user = message.from_user
  231. if message.chat.type == ChatType.PRIVATE:
  232. await message.reply_text(
  233. "Send this command on the chat which you need to set as fed log channel."
  234. )
  235. return
  236. member = await app.get_chat_member(chat.id, user.id)
  237. if (
  238. member.status == ChatMemberStatus.OWNER
  239. or member.status == ChatMemberStatus.ADMINISTRATOR
  240. ):
  241. if len(message.command) < 2:
  242. return await message.reply_text(
  243. "Please provide the Id of the federation with the command!"
  244. )
  245. fed_id = message.text.split(" ", 1)[1].strip()
  246. info = await get_fed_info(fed_id)
  247. if info is False:
  248. await message.reply_text("This federation does not exist.")
  249. return
  250. if await is_user_fed_owner(fed_id, user.id):
  251. if "/unsetfedlog" in message.text:
  252. log_group_id = LOG_GROUP_ID
  253. else:
  254. log_group_id = chat.id
  255. loged = await set_log_chat(fed_id, log_group_id)
  256. if "/unsetfedlog" in message.text:
  257. return await message.reply_text(
  258. "log channel removed successfully."
  259. )
  260. else:
  261. await message.reply_text("log channel set successfully.")
  262. else:
  263. await message.reply_text(
  264. "You need to be the chat owner or admin to use this command."
  265. )
  266. @app.on_message(filters.command("chatfed"))
  267. @capture_err
  268. async def fed_chat(client, message):
  269. chat = message.chat
  270. user = message.from_user
  271. fed_id = await get_fed_id(chat.id)
  272. member = await app.get_chat_member(chat.id, user.id)
  273. if (
  274. member.status == ChatMemberStatus.OWNER
  275. or member.status == ChatMemberStatus.ADMINISTRATOR
  276. ):
  277. pass
  278. else:
  279. await message.reply_text(
  280. "You must be an admin to execute this command"
  281. )
  282. return
  283. if not fed_id:
  284. await message.reply_text("This group is not in any federation!")
  285. return
  286. info = await get_fed_info(fed_id)
  287. text = "This group is part of the following federation:"
  288. text += "\n{} (ID: <code>{}</code>)".format(info["fed_name"], fed_id)
  289. await message.reply_text(text, parse_mode=ParseMode.HTML)
  290. @app.on_message(filters.command("joinfed"))
  291. @capture_err
  292. async def join_fed(client, message):
  293. chat = message.chat
  294. user = message.from_user
  295. if message.chat.type == ChatType.PRIVATE:
  296. await message.reply_text(
  297. "This command is specific to groups, not our pm!",
  298. )
  299. return
  300. member = await app.get_chat_member(chat.id, user.id)
  301. fed_id = await get_fed_id(int(chat.id))
  302. if user.id in SUDOERS:
  303. pass
  304. else:
  305. if member.status == ChatMemberStatus.OWNER:
  306. pass
  307. else:
  308. await message.reply_text(
  309. "Only group creators can use this command!"
  310. )
  311. return
  312. if fed_id:
  313. await message.reply_text(
  314. "You cannot join two federations from one chat"
  315. )
  316. return
  317. args = message.text.split(" ", 1)
  318. if len(args) > 1:
  319. fed_id = args[1].strip()
  320. getfed = await search_fed_by_id(fed_id)
  321. if getfed is False:
  322. await message.reply_text("Please enter a valid federation ID")
  323. return
  324. x = await chat_join_fed(fed_id, chat.title, chat.id)
  325. if not x:
  326. await message.reply_text(
  327. f"Failed to join federation! Please contact {SUPPORT_CHAT} if this problem persists!"
  328. )
  329. return
  330. get_fedlog = getfed["log_group_id"]
  331. if get_fedlog:
  332. await app.send_message(
  333. get_fedlog,
  334. "Chat **{}** has joined the federation **{}**".format(
  335. chat.title, getfed["fed_name"]
  336. ),
  337. parse_mode=ParseMode.MARKDOWN,
  338. )
  339. await message.reply_text(
  340. "This group has joined the federation: {}!".format(
  341. getfed["fed_name"]
  342. )
  343. )
  344. else:
  345. await message.reply_text(
  346. "You need to specify which federation you're asking about by giving me a FedID!"
  347. )
  348. @app.on_message(filters.command("leavefed"))
  349. @capture_err
  350. async def leave_fed(client, message):
  351. chat = message.chat
  352. user = message.from_user
  353. if message.chat.type == ChatType.PRIVATE:
  354. await message.reply_text(
  355. "This command is specific to groups, not our pm!",
  356. )
  357. return
  358. fed_id = await get_fed_id(int(chat.id))
  359. fed_info = await get_fed_info(fed_id)
  360. member = await app.get_chat_member(chat.id, user.id)
  361. if member.status == ChatMemberStatus.OWNER or user.id in SUDOERS:
  362. if await chat_leave_fed(int(chat.id)) is True:
  363. get_fedlog = fed_info["log_group_id"]
  364. if get_fedlog:
  365. await app.send_message(
  366. get_fedlog,
  367. "Chat **{}** has left the federation **{}**".format(
  368. chat.title, fed_info["fed_name"]
  369. ),
  370. parse_mode=ParseMode.MARKDOWN,
  371. )
  372. await message.reply_text(
  373. "This group has left the federation {}!".format(
  374. fed_info["fed_name"]
  375. ),
  376. )
  377. else:
  378. await message.reply_text(
  379. "How can you leave a federation that you never joined?!"
  380. )
  381. else:
  382. await message.reply_text("Only group creators can use this command!")
  383. @app.on_message(filters.command("fedchats"))
  384. @capture_err
  385. async def fed_chat(client, message):
  386. chat = message.chat
  387. user = message.from_user
  388. if message.chat.type != ChatType.PRIVATE:
  389. return await message.reply_text(
  390. "Fedchats can only be checked by privately messaging me."
  391. )
  392. if len(message.command) < 2:
  393. return await message.reply_text(
  394. "Please write the Id of the federation!\n\nUsage:\n/fedchats fed_id"
  395. )
  396. args = message.text.split(" ", 1)
  397. if len(args) > 1:
  398. fed_id = args[1].strip()
  399. info = await get_fed_info(fed_id)
  400. if info is False:
  401. return await message.reply_text("This federation does not exist.")
  402. fed_owner = info["owner_id"]
  403. fed_admins = info["fadmins"]
  404. all_admins = [fed_owner] + fed_admins + [int(BOT_ID)]
  405. if user.id in all_admins or user.id in SUDOERS:
  406. pass
  407. else:
  408. return await message.reply_text(
  409. "You need to be a Fed Admin to use this command"
  410. )
  411. chat_ids, chat_names = await chat_id_and_names_in_fed(fed_id)
  412. if not chat_ids:
  413. return await message.reply_text(
  414. "There are no chats in this federation!"
  415. )
  416. text = "\n".join(
  417. [
  418. f"${chat_name} [`{chat_id}`]"
  419. for chat_id, chat_name in zip(chat_ids, chat_names)
  420. ]
  421. )
  422. await message.reply_text(
  423. f"**Here are the list of chats connected to this federation:**\n\n{text}"
  424. )
  425. @app.on_message(filters.command("fedinfo"))
  426. @capture_err
  427. async def fed_info(client, message):
  428. if len(message.command) < 2:
  429. return await message.reply_text(
  430. "Please provide the Fed Id to get information!"
  431. )
  432. fed_id = message.text.split(" ", 1)[1].strip()
  433. fed_info = await get_fed_info(fed_id)
  434. if not fed_info:
  435. return await message.reply_text("Federation not found.")
  436. fed_name = fed_info.get("fed_name")
  437. owner_mention = fed_info.get("owner_mention")
  438. fadmin_count = len(fed_info.get("fadmins", []))
  439. banned_users_count = len(fed_info.get("banned_users", []))
  440. chat_ids_count = len(fed_info.get("chat_ids", []))
  441. reply_text = (
  442. f"**Federation Information:**\n\n"
  443. f"**Fed Name:** {fed_name}\n"
  444. f"**Owner:** {owner_mention}\n"
  445. f"**Number of Fed Admins:** {fadmin_count}\n"
  446. f"**Number of Banned Users:** {banned_users_count}\n"
  447. f"**Number of Chats:** {chat_ids_count}"
  448. )
  449. await message.reply_text(reply_text)
  450. @app.on_message(filters.command("fedadmins"))
  451. @capture_err
  452. async def get_all_fadmins_mentions(client, message):
  453. if len(message.command) < 2:
  454. await message.reply_text("Please provide me the Fed Id to search!")
  455. return
  456. fed_id = message.text.split(" ", 1)[1].strip()
  457. fed_info = await get_fed_info(fed_id)
  458. if not fed_info:
  459. return await message.reply_text("Federation not found.")
  460. fadmin_ids = fed_info.get("fadmins", [])
  461. if not fadmin_ids:
  462. return await message.reply_text(
  463. f"**Owner: {fed_info['owner_mention']}\n\nNo fadmins found in the federation."
  464. )
  465. user_mentions = []
  466. for user_id in fadmin_ids:
  467. try:
  468. user = await app.get_users(int(user_id))
  469. user_mentions.append(f"● {user.mention}[`{user.id}`]")
  470. except Exception:
  471. user_mentions.append(f"● `Admin🥷`[`{user_id}`]")
  472. reply_text = (
  473. f"**Owner: {fed_info['owner_mention']}\n\nList of fadmins:**\n"
  474. + "\n".join(user_mentions)
  475. )
  476. await message.reply_text(reply_text)
  477. @app.on_message(filters.command("fpromote"))
  478. @capture_err
  479. async def fpromote(client, message):
  480. chat = message.chat
  481. user = message.from_user
  482. msg = message
  483. if message.chat.type == ChatType.PRIVATE:
  484. await message.reply_text(
  485. "This command is specific to groups, not our pm!",
  486. )
  487. return
  488. fed_id = await get_fed_id(chat.id)
  489. if not fed_id:
  490. return await message.reply_text(
  491. "You need to add a federation to this chat first!"
  492. )
  493. if await is_user_fed_owner(fed_id, user.id) or user.id in SUDOERS:
  494. user_id = await extract_user(msg)
  495. if user_id is None:
  496. await message.reply_text(
  497. "Failed to extract user from the message."
  498. )
  499. return
  500. check_user = await check_banned_user(fed_id, user_id)
  501. if check_user:
  502. user = await app.get_users(user_id)
  503. reason = check_user["reason"]
  504. date = check_user["date"]
  505. return await message.reply_text(
  506. f"**User {user.mention} was Fed Banned.\nyou can unban the user and promote.\n\nReason: {reason}.\nDate: {date}.**"
  507. )
  508. getuser = await search_user_in_fed(fed_id, user_id)
  509. info = await get_fed_info(fed_id)
  510. get_owner = info["owner_id"]
  511. if user_id == get_owner:
  512. await message.reply_text(
  513. "You do know that the user is the federation owner, right? RIGHT?"
  514. )
  515. return
  516. if getuser:
  517. await message.reply_text(
  518. "I cannot promote users who are already federation admins! Can remove them if you want!"
  519. )
  520. return
  521. if user_id == BOT_ID:
  522. await message.reply_text(
  523. "I already am a federation admin in all federations!"
  524. )
  525. return
  526. res = await user_join_fed(str(fed_id), user_id)
  527. if res:
  528. await message.reply_text("Successfully Promoted!")
  529. else:
  530. await message.reply_text("Failed to promote!")
  531. else:
  532. await message.reply_text("Only federation owners can do this!")
  533. @app.on_message(filters.command("fdemote"))
  534. @capture_err
  535. async def fdemote(client, message):
  536. chat = message.chat
  537. user = message.from_user
  538. msg = message
  539. if message.chat.type == ChatType.PRIVATE:
  540. await message.reply_text(
  541. "This command is specific to groups, not our pm!",
  542. )
  543. return
  544. fed_id = await get_fed_id(chat.id)
  545. if not fed_id:
  546. return await message.reply_text(
  547. "You need to add a federation to this chat first!"
  548. )
  549. if await is_user_fed_owner(fed_id, user.id) or user.id in SUDOERS:
  550. user_id = await extract_user(msg)
  551. if user_id is None:
  552. await message.reply_text(
  553. "Failed to extract user from the message."
  554. )
  555. return
  556. if user_id == BOT_ID:
  557. update.effective_message.reply_text(
  558. "The thing you are trying to demote me from will fail to work without me! Just saying."
  559. )
  560. return
  561. if await search_user_in_fed(fed_id, user_id) is False:
  562. await message.reply_text(
  563. "I cannot demote people who are not federation admins!"
  564. )
  565. return
  566. res = await user_demote_fed(fed_id, user_id)
  567. if res is True:
  568. await message.reply_text("Demoted from a Fed Admin!")
  569. else:
  570. await message.reply_text("Demotion failed!")
  571. else:
  572. await message.reply_text("Only federation owners can do this!")
  573. return
  574. @app.on_message(filters.command(["fban", "sfban"]))
  575. @capture_err
  576. async def fban_user(client, message):
  577. chat = message.chat
  578. from_user = message.from_user
  579. if message.chat.type == ChatType.PRIVATE:
  580. await message.reply_text(
  581. "This command is specific to groups, not our pm!."
  582. )
  583. return
  584. fed_id = await get_fed_id(chat.id)
  585. if not fed_id:
  586. return await message.reply_text(
  587. "**This chat is not a part of any federation."
  588. )
  589. info = await get_fed_info(fed_id)
  590. fed_owner = info["owner_id"]
  591. fed_admins = info["fadmins"]
  592. all_admins = [fed_owner] + fed_admins + [int(BOT_ID)]
  593. if from_user.id in all_admins or from_user.id in SUDOERS:
  594. pass
  595. else:
  596. return await message.reply_text(
  597. "You need to be a Fed Admin to use this command"
  598. )
  599. if len(message.command) < 2:
  600. return await message.reply_text(
  601. "**You needed to specify a user or reply to their message!**"
  602. )
  603. user_id, reason = await extract_user_and_reason(message)
  604. user = await app.get_users(user_id)
  605. if not user_id:
  606. return await message.reply_text("I can't find that user.")
  607. if user_id in all_admins or user_id in SUDOERS:
  608. return await message.reply_text("I can't ban that user.")
  609. check_user = await check_banned_user(fed_id, user_id)
  610. if check_user:
  611. reason = check_user["reason"]
  612. date = check_user["date"]
  613. return await message.reply_text(
  614. f"**User {user.mention} was already Fed Banned.\n\nReason: {reason}.\nDate: {date}.**"
  615. )
  616. if not reason:
  617. return await message.reply("No reason provided.")
  618. served_chats, _ = await chat_id_and_names_in_fed(fed_id)
  619. m = await message.reply_text(
  620. f"**Fed Banning {user.mention}!**"
  621. + f" **This Action Should Take About {len(served_chats)} Seconds.**"
  622. )
  623. await add_fban_user(fed_id, user_id, reason)
  624. number_of_chats = 0
  625. for served_chat in served_chats:
  626. try:
  627. chat_member = await app.get_chat_member(served_chat, user.id)
  628. if chat_member.status == ChatMemberStatus.MEMBER:
  629. await app.ban_chat_member(served_chat, user.id)
  630. if served_chat != chat.id:
  631. if not message.text.startswith("/s"):
  632. await app.send_message(
  633. served_chat, f"**Fed Banned {user.mention} !**"
  634. )
  635. number_of_chats += 1
  636. await asyncio.sleep(1)
  637. except FloodWait as e:
  638. await asyncio.sleep(int(e.value))
  639. except Exception:
  640. pass
  641. try:
  642. await app.send_message(
  643. user.id,
  644. f"Hello, You have been fed banned by {from_user.mention},"
  645. + " You can appeal for this ban by talking to him.",
  646. )
  647. except Exception:
  648. pass
  649. await m.edit(f"Fed Banned {user.mention} !")
  650. ban_text = f"""
  651. __**New Federation Ban**__
  652. **Origin:** {message.chat.title} [`{message.chat.id}`]
  653. **Admin:** {from_user.mention}
  654. **Banned User:** {user.mention}
  655. **Banned User ID:** `{user_id}`
  656. **Reason:** __{reason}__
  657. **Chats:** `{number_of_chats}`"""
  658. try:
  659. m2 = await app.send_message(
  660. info["log_group_id"],
  661. text=ban_text,
  662. disable_web_page_preview=True,
  663. )
  664. await m.edit(
  665. f"Fed Banned {user.mention} !\nAction Log: {m2.link}",
  666. disable_web_page_preview=True,
  667. )
  668. except Exception:
  669. await message.reply_text(
  670. "User Fbanned, But This Fban Action Wasn't Logged, Add Me In LOG_GROUP"
  671. )
  672. @app.on_message(filters.command(["unfban", "sunfban"]))
  673. @capture_err
  674. async def funban_user(client, message):
  675. chat = message.chat
  676. from_user = message.from_user
  677. if message.chat.type == ChatType.PRIVATE:
  678. await message.reply_text(
  679. "This command is specific to groups, not our pm!."
  680. )
  681. return
  682. fed_id = await get_fed_id(chat.id)
  683. if not fed_id:
  684. return await message.reply_text(
  685. "**This chat is not a part of any federation."
  686. )
  687. info = await get_fed_info(fed_id)
  688. fed_owner = info["owner_id"]
  689. fed_admins = info["fadmins"]
  690. all_admins = [fed_owner] + fed_admins + [int(BOT_ID)]
  691. if from_user.id in all_admins or from_user.id in SUDOERS:
  692. pass
  693. else:
  694. return await message.reply_text(
  695. "You need to be a Fed Admin to use this command"
  696. )
  697. if len(message.command) < 2:
  698. return await message.reply_text(
  699. "**You needed to specify a user or reply to their message!**"
  700. )
  701. user_id, reason = await extract_user_and_reason(message)
  702. user = await app.get_users(user_id)
  703. if not user_id:
  704. return await message.reply_text("I can't find that user.")
  705. if user_id in all_admins or user_id in SUDOERS:
  706. return await message.reply_text(
  707. "**How can an admin ever be banned!.**"
  708. )
  709. check_user = await check_banned_user(fed_id, user_id)
  710. if not check_user:
  711. return await message.reply_text(
  712. "**I can't unban a user who was never fedbanned.**"
  713. )
  714. if not reason:
  715. return await message.reply("No reason provided.")
  716. served_chats, _ = await chat_id_and_names_in_fed(fed_id)
  717. m = await message.reply_text(
  718. f"**Fed UnBanning {user.mention}!**"
  719. + f" **This Action Should Take About {len(served_chats)} Seconds.**"
  720. )
  721. await remove_fban_user(fed_id, user_id)
  722. number_of_chats = 0
  723. for served_chat in served_chats:
  724. try:
  725. chat_member = await app.get_chat_member(served_chat, user.id)
  726. if chat_member.status == ChatMemberStatus.BANNED:
  727. await app.unban_chat_member(served_chat, user.id)
  728. if served_chat != chat.id:
  729. if not message.text.startswith("/s"):
  730. await app.send_message(
  731. served_chat, f"**Fed UnBanned {user.mention} !**"
  732. )
  733. number_of_chats += 1
  734. await asyncio.sleep(1)
  735. except FloodWait as e:
  736. await asyncio.sleep(int(e.value))
  737. except Exception:
  738. pass
  739. try:
  740. await app.send_message(
  741. user.id,
  742. f"Hello, You have been fed unbanned by {from_user.mention},"
  743. + " You can thank him for his action.",
  744. )
  745. except Exception:
  746. pass
  747. await m.edit(f"Fed UnBanned {user.mention} !")
  748. ban_text = f"""
  749. __**New Federation UnBan**__
  750. **Origin:** {message.chat.title} [`{message.chat.id}`]
  751. **Admin:** {from_user.mention}
  752. **UnBanned User:** {user.mention}
  753. **UnBanned User ID:** `{user_id}`
  754. **Reason:** __{reason}__
  755. **Chats:** `{number_of_chats}`"""
  756. try:
  757. m2 = await app.send_message(
  758. info["log_group_id"],
  759. text=ban_text,
  760. disable_web_page_preview=True,
  761. )
  762. await m.edit(
  763. f"Fed UnBanned {user.mention} !\nAction Log: {m2.link}",
  764. disable_web_page_preview=True,
  765. )
  766. except Exception:
  767. await message.reply_text(
  768. "User FUnbanned, But This Fban Action Wasn't Logged, Add Me In LOG_GROUP"
  769. )
  770. @app.on_message(filters.command("fedstat"))
  771. async def fedstat(client, message):
  772. user = message.from_user
  773. if message.chat.type != ChatType.PRIVATE:
  774. await message.reply_text(
  775. "Federation Ban status can only be checked by privately messaging me."
  776. )
  777. return
  778. if len(message.command) < 2:
  779. await message.reply_text("Please provide me the user name and Fed Id!")
  780. return
  781. user_id, fed_id = await extract_user_and_reason(message)
  782. if not user_id:
  783. user_id = message.from_user.id
  784. fed_id = message.text.split(" ", 1)[1].strip()
  785. if not fed_id:
  786. return await message.reply_text(
  787. "provide me a Fed Id along with the command to search for."
  788. )
  789. info = await get_fed_info(fed_id)
  790. if not info:
  791. await message.reply_text("Please enter a valid fed id")
  792. else:
  793. check_user = await check_banned_user(fed_id, user_id)
  794. if check_user:
  795. user = await app.get_users(user_id)
  796. reason = check_user["reason"]
  797. date = check_user["date"]
  798. return await message.reply_text(
  799. f"**User {user.mention} was Fed Banned for:\n\nReason: {reason}.\nDate: {date}.**"
  800. )
  801. else:
  802. await message.reply_text(
  803. f"**User {user.mention} is not Fed Banned in this federation.**"
  804. )
  805. @app.on_message(filters.command("fbroadcast"))
  806. @capture_err
  807. async def fbroadcast_message(client, message):
  808. chat = message.chat
  809. from_user = message.from_user
  810. reply_message = message.reply_to_message
  811. if message.chat.type == ChatType.PRIVATE:
  812. await message.reply_text(
  813. "This command is specific to groups, not our pm!."
  814. )
  815. return
  816. fed_id = await get_fed_id(chat.id)
  817. if not fed_id:
  818. return await message.reply_text(
  819. "**This chat is not a part of any federation."
  820. )
  821. info = await get_fed_info(fed_id)
  822. fed_owner = info["owner_id"]
  823. fed_admins = info["fadmins"]
  824. all_admins = [fed_owner] + fed_admins + [int(BOT_ID)]
  825. if from_user.id in all_admins or from_user.id in SUDOERS:
  826. pass
  827. else:
  828. return await message.reply_text(
  829. "You need to be a Fed Admin to use this command"
  830. )
  831. if not reply_message:
  832. return await message.reply_text(
  833. "**You need to reply to a text message to Broadcasted it.**"
  834. )
  835. sleep_time = 0.1
  836. if reply_message.text:
  837. text = reply_message.text.markdown
  838. else:
  839. return await message.reply_text(
  840. "You can only Broadcast text messages."
  841. )
  842. reply_markup = None
  843. if reply_message.reply_markup:
  844. reply_markup = InlineKeyboardMarkup(
  845. reply_message.reply_markup.inline_keyboard
  846. )
  847. sent = 0
  848. chats, _ = await chat_id_and_names_in_fed(fed_id)
  849. m = await message.reply_text(
  850. f"Broadcast in progress, will take {len(chats) * sleep_time} seconds."
  851. )
  852. for i in chats:
  853. try:
  854. await app.send_message(
  855. i,
  856. text=text,
  857. reply_markup=reply_markup,
  858. )
  859. sent += 1
  860. await asyncio.sleep(sleep_time)
  861. except FloodWait as e:
  862. await asyncio.sleep(int(e.value))
  863. except Exception:
  864. pass
  865. await m.edit(f"**Broadcasted Message In {sent} Chats.**")
  866. @app.on_callback_query(filters.regex("rmfed_(.*)"))
  867. async def del_fed_button(client, cb):
  868. query = cb.data
  869. userid = cb.message.chat.id
  870. fed_id = query.split("_")[1]
  871. if fed_id == "cancel":
  872. await cb.message.edit_text("Federation deletion cancelled")
  873. return
  874. getfed = await get_fed_info(fed_id)
  875. if getfed:
  876. delete = fedsdb.delete_one({"fed_id": str(fed_id)})
  877. if delete:
  878. await cb.message.edit_text(
  879. "You have removed your Federation! Now all the Groups that are connected with `{}` do not have a Federation.".format(
  880. getfed["fed_name"]
  881. ),
  882. parse_mode=ParseMode.MARKDOWN,
  883. )
  884. @app.on_callback_query(filters.regex("trfed_(.*)"))
  885. async def fedtransfer_button(client, cb):
  886. query = cb.data
  887. userid = cb.message.chat.id
  888. data = query.split("_")[1]
  889. if data == "cancel":
  890. await cb.message.edit_text("Federation deletion cancelled")
  891. return
  892. data2 = data.split("|", 1)
  893. new_owner_id = int(data2[0])
  894. fed_id = data2[1]
  895. transferred = await transfer_owner(fed_id, userid, new_owner_id)
  896. if transferred:
  897. await cb.message.edit_text(
  898. "**Successfully transferred ownership to new owner.**"
  899. )
  900. @app.on_callback_query(filters.regex("fed_(.*)"))
  901. async def fed_owner_help(client, cb):
  902. query = cb.data
  903. userid = cb.message.chat.id
  904. data = query.split("_")[1]
  905. if data == "owner":
  906. text = """**👑 Fed Owner Only:**
  907. • /newfed <fed_name>**:** Creates a Federation, One allowed per user
  908. • /renamefed <fed_id> <new_fed_name>**:** Renames the fed id to a new name
  909. • /delfed <fed_id>**:** Delete a Federation, and any information related to it. Will not cancel blocked users
  910. • /myfeds**:** To list the federations that you have created
  911. • /fedtransfer <new_owner> <fed_id>**:**To transfer fed ownership to another person
  912. • /fpromote <user>**:** Assigns the user as a federation admin. Enables all commands for the user under `Fed Admins`
  913. • /fdemote <user>**:** Drops the User from the admin Federation to a normal User
  914. • /setfedlog <fed_id>**:** Sets the group as a fed log report base for the federation
  915. • /unsetfedlog <fed_id>**:** Removed the group as a fed log report base for the federation
  916. • /fbroadcast **:** Broadcasts a messages to all groups that have joined your fed """
  917. elif data == "admin":
  918. text = """**🔱 Fed Admins:**
  919. • /fban <user> <reason>**:** Fed bans a user
  920. • /sfban**:** Fban a user without sending notification to chats
  921. • /unfban <user> <reason>**:** Removes a user from a fed ban
  922. • /sunfban**:** Unfban a user without sending a notification
  923. • /fedadmins**:** Show Federation admin
  924. • /fedchats <FedID>**:** Get all the chats that are connected in the Federation
  925. • /fbroadcast **:** Broadcasts a messages to all groups that have joined your fed
  926. """
  927. else:
  928. text = """**User Commands:**
  929. • /fedinfo <FedID>: Information about a federation.
  930. • /fedadmins <FedID>: List the admins in a federation.
  931. • /joinfed <FedID>: Join the current chat to a federation. A chat can only join one federation. Chat owners only.
  932. • /leavefed: Leave the current federation. Only chat owners can do this.
  933. • /fedstat <FedID>: Gives information about your ban in a federation.
  934. • /fedstat <user ID> <FedID>: Gives information about a user's ban in a federation.
  935. • /chatfed: Information about the federation the current chat is in.
  936. """
  937. await cb.message.edit(
  938. text,
  939. reply_markup=InlineKeyboardMarkup(
  940. [
  941. [
  942. InlineKeyboardButton(
  943. "Back", callback_data="help_module(federation)"
  944. ),
  945. ]
  946. ]
  947. ),
  948. parse_mode=ParseMode.MARKDOWN,
  949. )