hikka_security.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  1. # █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
  2. # █▀█ █ █ █ █▀█ █▀▄ █
  3. # © Copyright 2022
  4. # https://t.me/hikariatama
  5. #
  6. # 🔒 Licensed under the GNU AGPLv3
  7. # 🌐 https://www.gnu.org/licenses/agpl-3.0.html
  8. import time
  9. import typing
  10. from telethon.tl.types import Message, PeerUser, User
  11. from telethon.utils import get_display_name
  12. from telethon.hints import EntityLike
  13. from .. import loader, security, utils, main
  14. from ..inline.types import InlineCall, InlineMessage
  15. from ..security import (
  16. DEFAULT_PERMISSIONS,
  17. EVERYONE,
  18. GROUP_ADMIN,
  19. GROUP_ADMIN_ADD_ADMINS,
  20. GROUP_ADMIN_BAN_USERS,
  21. GROUP_ADMIN_CHANGE_INFO,
  22. GROUP_ADMIN_DELETE_MESSAGES,
  23. GROUP_ADMIN_INVITE_USERS,
  24. GROUP_ADMIN_PIN_MESSAGES,
  25. GROUP_MEMBER,
  26. GROUP_OWNER,
  27. PM,
  28. SUDO,
  29. SUPPORT,
  30. )
  31. @loader.tds
  32. class HikkaSecurityMod(loader.Module):
  33. """Control security settings"""
  34. service_strings = {
  35. "for": "for",
  36. "forever": "forever",
  37. "user": "user",
  38. "chat": "chat",
  39. "command": "command",
  40. "module": "module",
  41. "day": "day",
  42. "days": "days",
  43. "hour": "hour",
  44. "hours": "hours",
  45. "minute": "minute",
  46. "minutes": "minutes",
  47. "second": "second",
  48. "seconds": "seconds",
  49. }
  50. service_strings_ru = {
  51. "for": "на",
  52. "forever": "навсегда",
  53. "command": "команду",
  54. "module": "модуль",
  55. "chat": "чату",
  56. "user": "пользователю",
  57. "day": "день",
  58. "days": "дня(-ей)",
  59. "hour": "час",
  60. "hours": "часа(-ов)",
  61. "minute": "минута",
  62. "minutes": "минут(-ы)",
  63. "second": "секунда",
  64. "seconds": "секунд(-ы)",
  65. }
  66. strings = {
  67. "name": "HikkaSecurity",
  68. "no_command": "🚫 <b>Command </b><code>{}</code><b> not found!</b>",
  69. "permissions": (
  70. "🔐 <b>Here you can configure permissions for </b><code>{}{}</code>"
  71. ),
  72. "close_menu": "🙈 Close this menu",
  73. "global": (
  74. "🔐 <b>Here you can configure global bounding mask. If the permission is"
  75. " excluded here, it is excluded everywhere!</b>"
  76. ),
  77. "owner": "😎 Owner",
  78. "sudo": "🧐 Sudo",
  79. "support": "🤓 Support",
  80. "group_owner": "🧛‍♂️ Group owner",
  81. "group_admin_add_admins": "🧑‍⚖️ Admin (add members)",
  82. "group_admin_change_info": "🧑‍⚖️ Admin (change info)",
  83. "group_admin_ban_users": "🧑‍⚖️ Admin (ban)",
  84. "group_admin_delete_messages": "🧑‍⚖️ Admin (delete msgs)",
  85. "group_admin_pin_messages": "🧑‍⚖️ Admin (pin)",
  86. "group_admin_invite_users": "🧑‍⚖️ Admin (invite)",
  87. "group_admin": "🧑‍⚖️ Admin (any)",
  88. "group_member": "👥 In group",
  89. "pm": "🤙 In PM",
  90. "everyone": "🌍 Everyone (Inline)",
  91. "owner_list": (
  92. "<emoji document_id=5386399931378440814>😎</emoji> <b>Users in group"
  93. " </b><code>owner</code><b>:</b>\n\n{}"
  94. ),
  95. "sudo_list": (
  96. "<emoji document_id=5418133868475587618>🧐</emoji> <b>Users in group"
  97. " </b><code>sudo</code><b>:</b>\n\n{}"
  98. ),
  99. "support_list": (
  100. "<emoji document_id=5415729507128580146>🤓</emoji> <b>Users in group"
  101. " </b><code>support</code><b>:</b>\n\n{}"
  102. ),
  103. "no_owner": (
  104. "<emoji document_id=5386399931378440814>😎</emoji> <b>There is no users in"
  105. " group </b><code>owner</code>"
  106. ),
  107. "no_sudo": (
  108. "<emoji document_id=5418133868475587618>🧐</emoji> <b>There is no users in"
  109. " group </b><code>sudo</code>"
  110. ),
  111. "no_support": (
  112. "<emoji document_id=5415729507128580146>🤓</emoji> <b>There is no users in"
  113. " group </b><code>support</code>"
  114. ),
  115. "owner_added": (
  116. '<emoji document_id="5386399931378440814">😎</emoji> <b><a'
  117. ' href="tg://user?id={}">{}</a> added to group </b><code>owner</code>'
  118. ),
  119. "sudo_added": (
  120. '<emoji document_id="5418133868475587618">🧐</emoji> <b><a'
  121. ' href="tg://user?id={}">{}</a> added to group </b><code>sudo</code>'
  122. ),
  123. "support_added": (
  124. '<emoji document_id="5415729507128580146">🤓</emoji> <b><a'
  125. ' href="tg://user?id={}">{}</a> added to group </b><code>support</code>'
  126. ),
  127. "owner_removed": (
  128. '<emoji document_id="5386399931378440814">😎</emoji> <b><a'
  129. ' href="tg://user?id={}">{}</a> removed from group </b><code>owner</code>'
  130. ),
  131. "sudo_removed": (
  132. '<emoji document_id="5418133868475587618">🧐</emoji> <b><a'
  133. ' href="tg://user?id={}">{}</a> removed from group </b><code>sudo</code>'
  134. ),
  135. "support_removed": (
  136. '<emoji document_id="5415729507128580146">🤓</emoji> <b><a'
  137. ' href="tg://user?id={}">{}</a> removed from group </b><code>support</code>'
  138. ),
  139. "no_user": (
  140. "<emoji document_id=5415905755406539934>🚫</emoji> <b>Specify user to"
  141. " permit</b>"
  142. ),
  143. "not_a_user": (
  144. "<emoji document_id=5415905755406539934>🚫</emoji> <b>Specified entity is"
  145. " not a user</b>"
  146. ),
  147. "li": '⦿ <b><a href="tg://user?id={}">{}</a></b>',
  148. "warning": (
  149. "⚠️ <b>Please, confirm, that you want to add <a"
  150. ' href="tg://user?id={}">{}</a> to group </b><code>{}</code><b>!\nThis'
  151. " action may reveal personal info and grant full or partial access to"
  152. " userbot to this user</b>"
  153. ),
  154. "cancel": "🚫 Cancel",
  155. "confirm": "👑 Confirm",
  156. "enable_nonick_btn": "🔰 Enable",
  157. "self": (
  158. "<emoji document_id=5415905755406539934>🚫</emoji> <b>You can't"
  159. " promote/demote yourself!</b>"
  160. ),
  161. "suggest_nonick": "🔰 <i>Do you want to enable NoNick for this user?</i>",
  162. "user_nn": '🔰 <b>NoNick for <a href="tg://user?id={}">{}</a> enabled</b>',
  163. "what": (
  164. "<emoji document_id=6053166094816905153>🚫</emoji> <b>You need to specify"
  165. " the type of target as first argument (</b><code>user</code><b> or"
  166. " </b><code>chat</code><b>)</b>"
  167. ),
  168. "no_target": (
  169. "<emoji document_id=6053166094816905153>🚫</emoji> <b>You didn't specify"
  170. " the target of security rule</b>"
  171. ),
  172. "no_rule": (
  173. "<emoji document_id=6053166094816905153>🚫</emoji> <b>You didn't specify"
  174. " the rule (module or command)</b>"
  175. ),
  176. "confirm_rule": (
  177. "🔐 <b>Please, confirm that you want to give {} <a href='{}'>{}</a> a"
  178. " permission to use {} </b><code>{}</code><b> {}?</b>"
  179. ),
  180. "rule_added": (
  181. "🔐 <b>You gave {} <a href='{}'>{}</a> a"
  182. " permission to use {} </b><code>{}</code><b> {}</b>"
  183. ),
  184. "confirm_btn": "👑 Confirm",
  185. "cancel_btn": "🚫 Cancel",
  186. "multiple_rules": (
  187. "🔐 <b>Unable to unambiguously determine the security rule. Please, choose"
  188. " the one you meant:</b>\n\n{}"
  189. ),
  190. "rules": (
  191. "<emoji document_id=5472308992514464048>🔐</emoji> <b>Targeted security"
  192. " rules:</b>\n\n{}"
  193. ),
  194. "no_rules": (
  195. "<emoji document_id=6053166094816905153>🚫</emoji> <b>No targeted security"
  196. " rules</b>"
  197. ),
  198. "owner_target": (
  199. "<emoji document_id=6053166094816905153>🚫</emoji> <b>This user is owner"
  200. " and can't be promoted by targeted security</b>"
  201. ),
  202. "rules_removed": (
  203. "<emoji document_id=5472308992514464048>🔐</emoji> <b>Targeted security"
  204. ' rules for <a href="{}">{}</a> removed</b>'
  205. ),
  206. **service_strings,
  207. }
  208. strings_ru = {
  209. "no_command": (
  210. "<emoji document_id=5415905755406539934>🚫</emoji> <b>Команда"
  211. " </b><code>{}</code><b> не найдена!</b>"
  212. ),
  213. "permissions": (
  214. "🔐 <b>Здесь можно настроить разрешения для команды </b><code>{}{}</code>"
  215. ),
  216. "close_menu": "🙈 Закрыть это меню",
  217. "global": (
  218. "🔐 <b>Здесь можно настроить глобальную исключающую маску. Если тумблер"
  219. " выключен здесь, он выключен для всех команд</b>"
  220. ),
  221. "owner": "😎 Владелец",
  222. "sudo": "🧐 Sudo",
  223. "support": "🤓 Помощник",
  224. "group_owner": "🧛‍♂️ Влад. группы",
  225. "group_admin_add_admins": "🧑‍⚖️ Админ (добавлять участников)",
  226. "group_admin_change_info": "🧑‍⚖️ Админ (изменять инфо)",
  227. "group_admin_ban_users": "🧑‍⚖️ Админ (банить)",
  228. "group_admin_delete_messages": "🧑‍⚖️ Админ (удалять сообщения)",
  229. "group_admin_pin_messages": "🧑‍⚖️ Админ (закреплять)",
  230. "group_admin_invite_users": "🧑‍⚖️ Админ (приглашать)",
  231. "group_admin": "🧑‍⚖️ Админ (любой)",
  232. "group_member": "👥 В группе",
  233. "pm": "🤙 В лс",
  234. "owner_list": (
  235. "<emoji document_id=5386399931378440814>😎</emoji> <b>Пользователи группы"
  236. " </b><code>owner</code><b>:</b>\n\n{}"
  237. ),
  238. "sudo_list": (
  239. "<emoji document_id=5418133868475587618>🧐</emoji> <b>Пользователи группы"
  240. " </b><code>sudo</code><b>:</b>\n\n{}"
  241. ),
  242. "support_list": (
  243. "<emoji document_id=5415729507128580146>🤓</emoji> <b>Пользователи группы"
  244. " </b><code>support</code><b>:</b>\n\n{}"
  245. ),
  246. "no_owner": (
  247. "<emoji document_id=5386399931378440814>😎</emoji> <b>Нет пользователей в"
  248. " группе </b><code>owner</code>"
  249. ),
  250. "no_sudo": (
  251. "<emoji document_id=5418133868475587618>🧐</emoji> <b>Нет пользователей в"
  252. " группе </b><code>sudo</code>"
  253. ),
  254. "no_support": (
  255. "<emoji document_id=5415729507128580146>🤓</emoji> <b>Нет пользователей в"
  256. " группе </b><code>support</code>"
  257. ),
  258. "no_user": (
  259. "<emoji document_id=5415905755406539934>🚫</emoji> <b>Укажи, кому выдавать"
  260. " права</b>"
  261. ),
  262. "not_a_user": (
  263. "<emoji document_id=5415905755406539934>🚫</emoji> <b>Указанная цель - не"
  264. " пользователь</b>"
  265. ),
  266. "cancel": "🚫 Отмена",
  267. "confirm": "👑 Подтвердить",
  268. "self": (
  269. "<emoji document_id=5415905755406539934>🚫</emoji> <b>Нельзя управлять"
  270. " своими правами!</b>"
  271. ),
  272. "warning": (
  273. '⚠️ <b>Ты действительно хочешь добавить <a href="tg://user?id={}">{}</a> в'
  274. " группу </b><code>{}</code><b>!\nЭто действие может передать частичный или"
  275. " полный доступ к юзерботу этому пользователю!</b>"
  276. ),
  277. "suggest_nonick": (
  278. "🔰 <i>Хочешь ли ты включить NoNick для этого пользователя?</i>"
  279. ),
  280. "user_nn": '🔰 <b>NoNick для <a href="tg://user?id={}">{}</a> включен</b>',
  281. "enable_nonick_btn": "🔰 Включить",
  282. "owner_added": (
  283. '<emoji document_id="5386399931378440814">😎</emoji> <b><a'
  284. ' href="tg://user?id={}">{}</a> добавлен в группу </b><code>owner</code>'
  285. ),
  286. "sudo_added": (
  287. '<emoji document_id="5418133868475587618">🧐</emoji> <b><a'
  288. ' href="tg://user?id={}">{}</a> добавлен в группу </b><code>sudo</code>'
  289. ),
  290. "support_added": (
  291. '<emoji document_id="5415729507128580146">🤓</emoji> <b><a'
  292. ' href="tg://user?id={}">{}</a> добавлен в группу </b><code>support</code>'
  293. ),
  294. "owner_removed": (
  295. '<emoji document_id="5386399931378440814">😎</emoji> <b><a'
  296. ' href="tg://user?id={}">{}</a> удален из группы </b><code>owner</code>'
  297. ),
  298. "sudo_removed": (
  299. '<emoji document_id="5418133868475587618">🧐</emoji> <b><a'
  300. ' href="tg://user?id={}">{}</a> удален из группы </b><code>sudo</code>'
  301. ),
  302. "support_removed": (
  303. '<emoji document_id="5415729507128580146">🤓</emoji> <b><a'
  304. ' href="tg://user?id={}">{}</a> удален из группы </b><code>support</code>'
  305. ),
  306. "_cls_doc": "Управление настройками безопасности",
  307. "what": (
  308. "<emoji document_id=6053166094816905153>🚫</emoji> <b>Вам нужно указать"
  309. " тип цели первым аргументов (</b><code>user</code><b> or"
  310. " </b><code>chat</code><b>)</b>"
  311. ),
  312. "no_target": (
  313. "<emoji document_id=6053166094816905153>🚫</emoji> <b>Не указана цель"
  314. " правила безопасности</b>"
  315. ),
  316. "no_rule": (
  317. "<emoji document_id=6053166094816905153>🚫</emoji> <b>Не указано правило"
  318. " безопасности (модуль или команда)</b>"
  319. ),
  320. "confirm_rule": (
  321. "🔐 <b>Пожалуйста, подтвердите что хотите выдать {} <a href='{}'>{}</a>"
  322. " право использовать {} </b><code>{}</code><b> {}</b>"
  323. ),
  324. "multiple_rules": (
  325. "🔐 <b>Не получилось однозначно распознать правила безопасности. Выберите"
  326. " то, которое имели ввиду:</b>\n\n{}"
  327. ),
  328. "rule_added": (
  329. "🔐 <b>Вы выдали {} <a href='{}'>{}</a> право"
  330. " использовать {} </b><code>{}</code><b> {}</b>"
  331. ),
  332. "rules": (
  333. "<emoji document_id=5472308992514464048>🔐</emoji> <b>Таргетированные"
  334. " правила безопасности:</b>\n\n{}"
  335. ),
  336. "no_rules": (
  337. "<emoji document_id=6053166094816905153>🚫</emoji> <b>Нет таргетированных"
  338. " правил безопасности</b>"
  339. ),
  340. "owner_target": (
  341. "<emoji document_id=6053166094816905153>🚫</emoji> <b>Этот пользователь -"
  342. " владелец, его права не могут управляться таргетированной"
  343. " безопасностью</b>"
  344. ),
  345. "rules_removed": (
  346. "<emoji document_id=5472308992514464048>🔐</emoji> <b>Правила"
  347. ' таргетированной безопасности для <a href="{}">{}</a> удалены</b>'
  348. ),
  349. **service_strings_ru,
  350. }
  351. async def inline__switch_perm(
  352. self,
  353. call: InlineCall,
  354. command: str,
  355. group: str,
  356. level: bool,
  357. is_inline: bool,
  358. ):
  359. cmd = (
  360. self.allmodules.inline_handlers[command]
  361. if is_inline
  362. else self.allmodules.commands[command]
  363. )
  364. mask = self._db.get(security.__name__, "masks", {}).get(
  365. f"{cmd.__module__}.{cmd.__name__}",
  366. getattr(cmd, "security", security.DEFAULT_PERMISSIONS),
  367. )
  368. bit = security.BITMAP[group.upper()]
  369. if level:
  370. mask |= bit
  371. else:
  372. mask &= ~bit
  373. masks = self._db.get(security.__name__, "masks", {})
  374. masks[f"{cmd.__module__}.{cmd.__name__}"] = mask
  375. self._db.set(security.__name__, "masks", masks)
  376. if (
  377. not self._db.get(security.__name__, "bounding_mask", DEFAULT_PERMISSIONS)
  378. & bit
  379. and level
  380. ):
  381. await call.answer(
  382. "Security value set but not applied. Consider enabling this value in"
  383. f" .{'inlinesec' if is_inline else 'security'}",
  384. show_alert=True,
  385. )
  386. else:
  387. await call.answer("Security value set!")
  388. await call.edit(
  389. self.strings("permissions").format(
  390. f"@{self.inline.bot_username} " if is_inline else self.get_prefix(),
  391. command,
  392. ),
  393. reply_markup=self._build_markup(cmd, is_inline),
  394. )
  395. async def inline__switch_perm_bm(
  396. self,
  397. call: InlineCall,
  398. group: str,
  399. level: bool,
  400. is_inline: bool,
  401. ):
  402. mask = self._db.get(security.__name__, "bounding_mask", DEFAULT_PERMISSIONS)
  403. bit = security.BITMAP[group.upper()]
  404. if level:
  405. mask |= bit
  406. else:
  407. mask &= ~bit
  408. self._db.set(security.__name__, "bounding_mask", mask)
  409. await call.answer("Bounding mask value set!")
  410. await call.edit(
  411. self.strings("global"),
  412. reply_markup=self._build_markup_global(is_inline),
  413. )
  414. def _build_markup(
  415. self,
  416. command: callable,
  417. is_inline: bool = False,
  418. ) -> typing.List[typing.List[dict]]:
  419. perms = self._get_current_perms(command, is_inline)
  420. return (
  421. utils.chunks(
  422. [
  423. {
  424. "text": f"{'✅' if level else '🚫'} {self.strings[group]}",
  425. "callback": self.inline__switch_perm,
  426. "args": (
  427. command.__name__.rsplit("_inline_handler", maxsplit=1)[0],
  428. group,
  429. not level,
  430. is_inline,
  431. ),
  432. }
  433. for group, level in perms.items()
  434. ],
  435. 2,
  436. )
  437. + [[{"text": self.strings("close_menu"), "action": "close"}]]
  438. if is_inline
  439. else utils.chunks(
  440. [
  441. {
  442. "text": f"{'✅' if level else '🚫'} {self.strings[group]}",
  443. "callback": self.inline__switch_perm,
  444. "args": (
  445. command.__name__.rsplit("cmd", maxsplit=1)[0],
  446. group,
  447. not level,
  448. is_inline,
  449. ),
  450. }
  451. for group, level in perms.items()
  452. ],
  453. 2,
  454. )
  455. + [
  456. [
  457. {
  458. "text": self.strings("close_menu"),
  459. "action": "close",
  460. }
  461. ]
  462. ]
  463. )
  464. def _build_markup_global(
  465. self, is_inline: bool = False
  466. ) -> typing.List[typing.List[dict]]:
  467. perms = self._get_current_bm(is_inline)
  468. return utils.chunks(
  469. [
  470. {
  471. "text": f"{'✅' if level else '🚫'} {self.strings[group]}",
  472. "callback": self.inline__switch_perm_bm,
  473. "args": (group, not level, is_inline),
  474. }
  475. for group, level in perms.items()
  476. ],
  477. 2,
  478. ) + [[{"text": self.strings("close_menu"), "action": "close"}]]
  479. def _get_current_bm(self, is_inline: bool = False) -> dict:
  480. return self._perms_map(
  481. self._db.get(security.__name__, "bounding_mask", DEFAULT_PERMISSIONS),
  482. is_inline,
  483. )
  484. @staticmethod
  485. def _perms_map(perms: int, is_inline: bool) -> dict:
  486. return (
  487. {
  488. "sudo": bool(perms & SUDO),
  489. "support": bool(perms & SUPPORT),
  490. "everyone": bool(perms & EVERYONE),
  491. }
  492. if is_inline
  493. else {
  494. "sudo": bool(perms & SUDO),
  495. "support": bool(perms & SUPPORT),
  496. "group_owner": bool(perms & GROUP_OWNER),
  497. "group_admin_add_admins": bool(perms & GROUP_ADMIN_ADD_ADMINS),
  498. "group_admin_change_info": bool(perms & GROUP_ADMIN_CHANGE_INFO),
  499. "group_admin_ban_users": bool(perms & GROUP_ADMIN_BAN_USERS),
  500. "group_admin_delete_messages": bool(
  501. perms & GROUP_ADMIN_DELETE_MESSAGES
  502. ),
  503. "group_admin_pin_messages": bool(perms & GROUP_ADMIN_PIN_MESSAGES),
  504. "group_admin_invite_users": bool(perms & GROUP_ADMIN_INVITE_USERS),
  505. "group_admin": bool(perms & GROUP_ADMIN),
  506. "group_member": bool(perms & GROUP_MEMBER),
  507. "pm": bool(perms & PM),
  508. "everyone": bool(perms & EVERYONE),
  509. }
  510. )
  511. def _get_current_perms(
  512. self,
  513. command: callable,
  514. is_inline: bool = False,
  515. ) -> dict:
  516. config = self._db.get(security.__name__, "masks", {}).get(
  517. f"{command.__module__}.{command.__name__}",
  518. getattr(command, "security", self._client.dispatcher.security.default),
  519. )
  520. return self._perms_map(config, is_inline)
  521. @loader.owner
  522. @loader.command(ru_doc="[команда] - Настроить разрешения для команды")
  523. async def security(self, message: Message):
  524. """[command] - Configure command's security settings"""
  525. args = utils.get_args_raw(message).lower().strip()
  526. if args and args not in self.allmodules.commands:
  527. await utils.answer(message, self.strings("no_command").format(args))
  528. return
  529. if not args:
  530. await self.inline.form(
  531. self.strings("global"),
  532. reply_markup=self._build_markup_global(),
  533. message=message,
  534. ttl=5 * 60,
  535. )
  536. return
  537. cmd = self.allmodules.commands[args]
  538. await self.inline.form(
  539. self.strings("permissions").format(self.get_prefix(), args),
  540. reply_markup=self._build_markup(cmd),
  541. message=message,
  542. ttl=5 * 60,
  543. )
  544. @loader.owner
  545. @loader.command(ru_doc="[команда] - Настроить разрешения для инлайн команды")
  546. async def inlinesec(self, message: Message):
  547. """[command] - Configure inline command's security settings"""
  548. args = utils.get_args_raw(message).lower().strip()
  549. if not args:
  550. await self.inline.form(
  551. self.strings("global"),
  552. reply_markup=self._build_markup_global(True),
  553. message=message,
  554. ttl=5 * 60,
  555. )
  556. return
  557. if args not in self.allmodules.inline_handlers:
  558. await utils.answer(message, self.strings("no_command").format(args))
  559. return
  560. i_handler = self.allmodules.inline_handlers[args]
  561. await self.inline.form(
  562. self.strings("permissions").format(f"@{self.inline.bot_username} ", args),
  563. reply_markup=self._build_markup(i_handler, True),
  564. message=message,
  565. ttl=5 * 60,
  566. )
  567. async def _resolve_user(self, message: Message):
  568. reply = await message.get_reply_message()
  569. args = utils.get_args_raw(message)
  570. if not args and not reply:
  571. await utils.answer(message, self.strings("no_user"))
  572. return
  573. user = None
  574. if args:
  575. try:
  576. if str(args).isdigit():
  577. args = int(args)
  578. user = await self._client.get_entity(args)
  579. except Exception:
  580. pass
  581. if user is None:
  582. user = await self._client.get_entity(reply.sender_id)
  583. if not isinstance(user, (User, PeerUser)):
  584. await utils.answer(message, self.strings("not_a_user"))
  585. return
  586. if user.id == self.tg_id:
  587. await utils.answer(message, self.strings("self"))
  588. return
  589. return user
  590. async def _add_to_group(
  591. self,
  592. message: typing.Union[Message, InlineCall],
  593. group: str,
  594. confirmed: bool = False,
  595. user: int = None,
  596. ):
  597. if user is None:
  598. user = await self._resolve_user(message)
  599. if not user:
  600. return
  601. if isinstance(user, int):
  602. user = await self._client.get_entity(user)
  603. if not confirmed:
  604. await self.inline.form(
  605. self.strings("warning").format(
  606. user.id,
  607. utils.escape_html(get_display_name(user)),
  608. group,
  609. ),
  610. message=message,
  611. ttl=10 * 60,
  612. reply_markup=[
  613. {
  614. "text": self.strings("cancel"),
  615. "action": "close",
  616. },
  617. {
  618. "text": self.strings("confirm"),
  619. "callback": self._add_to_group,
  620. "args": (group, True, user.id),
  621. },
  622. ],
  623. )
  624. return
  625. if user.id not in getattr(self._client.dispatcher.security, group):
  626. getattr(self._client.dispatcher.security, group).append(user.id)
  627. m = (
  628. self.strings(f"{group}_added").format(
  629. user.id,
  630. utils.escape_html(get_display_name(user)),
  631. )
  632. + "\n\n"
  633. + self.strings("suggest_nonick")
  634. )
  635. await utils.answer(message, m)
  636. await message.edit(
  637. m,
  638. reply_markup=[
  639. {
  640. "text": self.strings("cancel"),
  641. "action": "close",
  642. },
  643. {
  644. "text": self.strings("enable_nonick_btn"),
  645. "callback": self._enable_nonick,
  646. "args": (user,),
  647. },
  648. ],
  649. )
  650. async def _enable_nonick(self, call: InlineCall, user: User):
  651. self._db.set(
  652. main.__name__,
  653. "nonickusers",
  654. list(set(self._db.get(main.__name__, "nonickusers", []) + [user.id])),
  655. )
  656. await call.edit(
  657. self.strings("user_nn").format(
  658. user.id,
  659. utils.escape_html(get_display_name(user)),
  660. )
  661. )
  662. await call.unload()
  663. async def _remove_from_group(self, message: Message, group: str):
  664. user = await self._resolve_user(message)
  665. if not user:
  666. return
  667. if user.id in getattr(self._client.dispatcher.security, group):
  668. getattr(self._client.dispatcher.security, group).remove(user.id)
  669. m = self.strings(f"{group}_removed").format(
  670. user.id,
  671. utils.escape_html(get_display_name(user)),
  672. )
  673. await utils.answer(message, m)
  674. async def _list_group(self, message: Message, group: str):
  675. _resolved_users = []
  676. for user in getattr(self._client.dispatcher.security, group) + (
  677. [self.tg_id] if group == "owner" else []
  678. ):
  679. try:
  680. _resolved_users += [await self._client.get_entity(user)]
  681. except Exception:
  682. pass
  683. if _resolved_users:
  684. await utils.answer(
  685. message,
  686. self.strings(f"{group}_list").format(
  687. "\n".join(
  688. [
  689. self.strings("li").format(
  690. i.id, utils.escape_html(get_display_name(i))
  691. )
  692. for i in _resolved_users
  693. ]
  694. )
  695. ),
  696. )
  697. else:
  698. await utils.answer(message, self.strings(f"no_{group}"))
  699. @loader.command(ru_doc="<пользователь> - Добавить пользователя в группу `sudo`")
  700. async def sudoadd(self, message: Message):
  701. """<user> - Add user to `sudo`"""
  702. await self._add_to_group(message, "sudo")
  703. @loader.command(ru_doc="<пользователь> - Добавить пользователя в группу `owner`")
  704. async def owneradd(self, message: Message):
  705. """<user> - Add user to `owner`"""
  706. await self._add_to_group(message, "owner")
  707. @loader.command(ru_doc="<пользователь> - Добавить пользователя в группу `support`")
  708. async def supportadd(self, message: Message):
  709. """<user> - Add user to `support`"""
  710. await self._add_to_group(message, "support")
  711. @loader.command(ru_doc="<пользователь> - Удалить пользователя из группы `sudo`")
  712. async def sudorm(self, message: Message):
  713. """<user> - Remove user from `sudo`"""
  714. await self._remove_from_group(message, "sudo")
  715. @loader.command(ru_doc="<пользователь> - Удалить пользователя из группы `owner`")
  716. async def ownerrm(self, message: Message):
  717. """<user> - Remove user from `owner`"""
  718. await self._remove_from_group(message, "owner")
  719. @loader.command(ru_doc="<пользователь> - Удалить пользователя из группы `support`")
  720. async def supportrm(self, message: Message):
  721. """<user> - Remove user from `support`"""
  722. await self._remove_from_group(message, "support")
  723. @loader.command(ru_doc="Показать список пользователей в группе `sudo`")
  724. async def sudolist(self, message: Message):
  725. """List users in `sudo`"""
  726. await self._list_group(message, "sudo")
  727. @loader.command(ru_doc="Показать список пользователей в группе `owner`")
  728. async def ownerlist(self, message: Message):
  729. """List users in `owner`"""
  730. await self._list_group(message, "owner")
  731. @loader.command(ru_doc="Показать список пользователей в группе `support`")
  732. async def supportlist(self, message: Message):
  733. """List users in `support`"""
  734. await self._list_group(message, "support")
  735. def _lookup(self, needle: str) -> str:
  736. return (
  737. []
  738. if needle.lower().startswith(self.get_prefix())
  739. else (
  740. [f"module/{self.lookup(needle).__class__.__name__}"]
  741. if self.lookup(needle)
  742. else []
  743. )
  744. ) + (
  745. [f"command/{needle.lower().strip(self.get_prefix())}"]
  746. if needle.lower().strip(self.get_prefix()) in self.allmodules.commands
  747. else []
  748. )
  749. @staticmethod
  750. def _extract_time(args: list) -> int:
  751. suffixes = {
  752. "d": 24 * 60 * 60,
  753. "h": 60 * 60,
  754. "m": 60,
  755. "s": 1,
  756. }
  757. for suffix, quantifier in suffixes.items():
  758. duration = next(
  759. (
  760. int(arg.rsplit(suffix, maxsplit=1)[0])
  761. for arg in args
  762. if arg.endswith(suffix)
  763. and arg.rsplit(suffix, maxsplit=1)[0].isdigit()
  764. ),
  765. None,
  766. )
  767. if duration is not None:
  768. return duration * quantifier
  769. return 0
  770. def _convert_time(self, duration: int) -> str:
  771. return (
  772. self.strings("forever")
  773. if not duration or duration < 0
  774. else (
  775. (
  776. f"{duration // (24 * 60 * 60)} "
  777. + self.strings(
  778. f"day{'s' if duration // (24 * 60 * 60) > 1 else ''}"
  779. )
  780. )
  781. if duration >= 24 * 60 * 60
  782. else (
  783. (
  784. f"{duration // (60 * 60)} "
  785. + self.strings(
  786. f"hour{'s' if duration // (60 * 60) > 1 else ''}"
  787. )
  788. )
  789. if duration >= 60 * 60
  790. else (
  791. (
  792. f"{duration // 60} "
  793. + self.strings(f"minute{'s' if duration // 60 > 1 else ''}")
  794. )
  795. if duration >= 60
  796. else (
  797. f"{duration} "
  798. + self.strings(f"second{'s' if duration > 1 else ''}")
  799. )
  800. )
  801. )
  802. )
  803. )
  804. async def _add_rule(
  805. self,
  806. call: InlineCall,
  807. target_type: str,
  808. target: EntityLike,
  809. rule: str,
  810. duration: int,
  811. ):
  812. self._client.dispatcher.security.add_rule(
  813. target_type,
  814. target,
  815. rule,
  816. duration,
  817. )
  818. await call.edit(
  819. self.strings("rule_added").format(
  820. self.strings(target_type),
  821. utils.get_entity_url(target),
  822. utils.escape_html(get_display_name(target)),
  823. self.strings(rule.split("/", maxsplit=1)[0]),
  824. rule.split("/", maxsplit=1)[1],
  825. (self.strings("for") + " " + self._convert_time(duration))
  826. if duration
  827. else self.strings("forever"),
  828. )
  829. )
  830. async def _confirm(
  831. self,
  832. obj: typing.Union[Message, InlineMessage],
  833. target_type: str,
  834. target: EntityLike,
  835. rule: str,
  836. duration: int,
  837. ):
  838. await utils.answer(
  839. obj,
  840. self.strings("confirm_rule").format(
  841. self.strings(target_type),
  842. utils.get_entity_url(target),
  843. utils.escape_html(get_display_name(target)),
  844. self.strings(rule.split("/", maxsplit=1)[0]),
  845. rule.split("/", maxsplit=1)[1],
  846. (self.strings("for") + " " + self._convert_time(duration))
  847. if duration
  848. else self.strings("forever"),
  849. ),
  850. reply_markup=[
  851. {
  852. "text": self.strings("confirm_btn"),
  853. "callback": self._add_rule,
  854. "args": (target_type, target, rule, duration),
  855. },
  856. {"text": self.strings("cancel_btn"), "action": "close"},
  857. ],
  858. )
  859. async def _tsec_chat(self, message: Message, args: list):
  860. if len(args) == 1 and message.is_private:
  861. await utils.answer(message, self.strings("no_target"))
  862. return
  863. if len(args) >= 2:
  864. try:
  865. if not args[1].isdigit() and not args[1].startswith("@"):
  866. raise ValueError
  867. target = await self._client.get_entity(
  868. int(args[1]) if args[1].isdigit() else args[1]
  869. )
  870. except (ValueError, TypeError):
  871. if not message.is_private:
  872. target = await self._client.get_entity(message.peer_id)
  873. else:
  874. await utils.answer(message, self.strings("no_target"))
  875. return
  876. duration = self._extract_time(args)
  877. possible_rules = utils.array_sum([self._lookup(arg) for arg in args])
  878. if not possible_rules:
  879. await utils.answer(message, self.strings("no_rule"))
  880. return
  881. if len(possible_rules) > 1:
  882. def case(text: str) -> str:
  883. return text.upper()[0] + text[1:]
  884. await self.inline.form(
  885. message=message,
  886. text=self.strings("multiple_rules").format(
  887. "\n".join(
  888. "🛡 <b>{} </b><code>{}</code>".format(
  889. case(self.strings(rule.split("/")[0])),
  890. rule.split("/", maxsplit=1)[1],
  891. )
  892. for rule in possible_rules
  893. )
  894. ),
  895. reply_markup=utils.chunks(
  896. [
  897. {
  898. "text": "🛡 {} {}".format(
  899. case(self.strings(rule.split("/")[0])),
  900. rule.split("/", maxsplit=1)[1],
  901. ),
  902. "callback": self._confirm,
  903. "args": ("chat", target, rule, duration),
  904. }
  905. for rule in possible_rules
  906. ],
  907. 3,
  908. ),
  909. )
  910. return
  911. await self._confirm(message, "chat", target, possible_rules[0], duration)
  912. async def _tsec_user(self, message: Message, args: list):
  913. if len(args) == 1 and not message.is_private and not message.is_reply:
  914. await utils.answer(message, self.strings("no_target"))
  915. return
  916. if len(args) >= 2:
  917. try:
  918. if not args[1].isdigit() and not args[1].startswith("@"):
  919. raise ValueError
  920. target = await self._client.get_entity(
  921. int(args[1]) if args[1].isdigit() else args[1]
  922. )
  923. except (ValueError, TypeError):
  924. if message.is_private:
  925. target = await self._client.get_entity(message.peer_id)
  926. elif message.is_reply:
  927. target = await self._client.get_entity(
  928. (await message.get_reply_message()).sender_id
  929. )
  930. else:
  931. await utils.answer(message, self.strings("no_target"))
  932. return
  933. if target.id in self._client.dispatcher.security.owner:
  934. await utils.answer(message, self.strings("owner_target"))
  935. return
  936. duration = self._extract_time(args)
  937. possible_rules = utils.array_sum([self._lookup(arg) for arg in args])
  938. if not possible_rules:
  939. await utils.answer(message, self.strings("no_rule"))
  940. return
  941. if len(possible_rules) > 1:
  942. def case(text: str) -> str:
  943. return text.upper()[0] + text[1:]
  944. await self.inline.form(
  945. message=message,
  946. text=self.strings("multiple_rules").format(
  947. "\n".join(
  948. "🛡 <b>{} </b><code>{}</code>".format(
  949. case(self.strings(rule.split("/")[0])),
  950. rule.split("/", maxsplit=1)[1],
  951. )
  952. for rule in possible_rules
  953. )
  954. ),
  955. reply_markup=utils.chunks(
  956. [
  957. {
  958. "text": "🛡 {} {}".format(
  959. case(self.strings(rule.split("/")[0])),
  960. rule.split("/", maxsplit=1)[1],
  961. ),
  962. "callback": self._confirm,
  963. "args": ("user", target, rule, duration),
  964. }
  965. for rule in possible_rules
  966. ],
  967. 3,
  968. ),
  969. )
  970. return
  971. await self._confirm(message, "user", target, possible_rules[0], duration)
  972. @loader.command(
  973. ru_doc='<"user"/"chat"> - Удалить правило таргетированной безопасности'
  974. )
  975. async def tsecrm(self, message: Message):
  976. """<"user"/"chat"> - Remove targeted security rule"""
  977. if (
  978. not self._client.dispatcher.security.tsec_chat
  979. and not self._client.dispatcher.security.tsec_user
  980. ):
  981. await utils.answer(message, self.strings("no_rules"))
  982. return
  983. args = utils.get_args_raw(message)
  984. if not args or args not in {"user", "chat"}:
  985. await utils.answer(message, self.strings("no_target"))
  986. return
  987. if args == "user":
  988. if not message.is_private and not message.is_reply:
  989. await utils.answer(message, self.strings("no_target"))
  990. return
  991. if message.is_private:
  992. target = await self._client.get_entity(message.peer_id)
  993. elif message.is_reply:
  994. target = await self._client.get_entity(
  995. (await message.get_reply_message()).sender_id
  996. )
  997. if not self._client.dispatcher.security.remove_rules("user", target.id):
  998. await utils.answer(message, self.strings("no_rules"))
  999. return
  1000. await utils.answer(
  1001. message,
  1002. self.strings("rules_removed").format(
  1003. utils.get_entity_url(target),
  1004. utils.escape_html(get_display_name(target)),
  1005. ),
  1006. )
  1007. return
  1008. if message.is_private:
  1009. await utils.answer(message, self.strings("no_target"))
  1010. return
  1011. target = await self._client.get_entity(message.peer_id)
  1012. if not self._client.dispatcher.security.remove_rules("chat", target.id):
  1013. await utils.answer(message, self.strings("no_rules"))
  1014. return
  1015. await utils.answer(
  1016. message,
  1017. self.strings("rules_removed").format(
  1018. utils.get_entity_url(target),
  1019. utils.escape_html(get_display_name(target)),
  1020. ),
  1021. )
  1022. @loader.command(
  1023. ru_doc=(
  1024. '<"user"/"chat"> [цель - пользователь или чат] [правило - команда или'
  1025. " модуль] [время] - Настроить таргетированную безопасность"
  1026. )
  1027. )
  1028. async def tsec(self, message: Message):
  1029. """<"user"/"chat"> [target user or chat] [rule (command/module)] [time] - Add new targeted security rule
  1030. """
  1031. args = utils.get_args(message)
  1032. if not args:
  1033. if (
  1034. not self._client.dispatcher.security.tsec_chat
  1035. and not self._client.dispatcher.security.tsec_user
  1036. ):
  1037. await utils.answer(message, self.strings("no_rules"))
  1038. return
  1039. await utils.answer(
  1040. message,
  1041. self.strings("rules").format(
  1042. "\n".join(
  1043. [
  1044. "<emoji document_id=6037355667365300960>👥</emoji> <b><a"
  1045. " href='{}'>{}</a> {} {} {}</b> <code>{}</code>".format(
  1046. rule["entity_url"],
  1047. utils.escape_html(rule["entity_name"]),
  1048. self._convert_time(int(rule["expires"] - time.time())),
  1049. self.strings("for"),
  1050. self.strings(rule["rule_type"]),
  1051. rule["rule"],
  1052. )
  1053. for rule in self._client.dispatcher.security.tsec_chat
  1054. ]
  1055. + [
  1056. "<emoji document_id=6037122016849432064>👤</emoji> <b><a"
  1057. " href='{}'>{}</a> {} {} {}</b> <code>{}</code>".format(
  1058. rule["entity_url"],
  1059. utils.escape_html(rule["entity_name"]),
  1060. self._convert_time(int(rule["expires"] - time.time())),
  1061. self.strings("for"),
  1062. self.strings(rule["rule_type"]),
  1063. rule["rule"],
  1064. )
  1065. for rule in self._client.dispatcher.security.tsec_user
  1066. ]
  1067. )
  1068. ),
  1069. )
  1070. return
  1071. if args[0] not in {"user", "chat"}:
  1072. await utils.answer(message, self.strings("what"))
  1073. return
  1074. await getattr(self, f"_tsec_{args[0]}")(message, args)