feds.py 37 KB

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