greetings.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. """
  2. MIT License
  3. Copyright (c) 2023 TheHamkerCat
  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 os
  22. from datetime import datetime
  23. from random import shuffle
  24. from pyrogram import filters
  25. from pyrogram.errors.exceptions.bad_request_400 import (
  26. ChatAdminRequired,
  27. UserNotParticipant,
  28. )
  29. from pyrogram.types import (
  30. Chat,
  31. ChatPermissions,
  32. InlineKeyboardButton,
  33. InlineKeyboardMarkup,
  34. Message,
  35. User,
  36. )
  37. from wbb import SUDOERS, WELCOME_DELAY_KICK_SEC, app
  38. from wbb.core.decorators.errors import capture_err
  39. from wbb.core.decorators.permissions import adminsOnly
  40. from wbb.core.keyboard import ikb
  41. from wbb.utils.dbfunctions import (
  42. captcha_off,
  43. captcha_on,
  44. del_welcome,
  45. get_captcha_cache,
  46. get_welcome,
  47. has_solved_captcha_once,
  48. is_captcha_on,
  49. is_gbanned_user,
  50. save_captcha_solved,
  51. set_welcome,
  52. update_captcha_cache,
  53. )
  54. from wbb.utils.filter_groups import welcome_captcha_group
  55. from wbb.utils.functions import extract_text_and_keyb, generate_captcha
  56. __MODULE__ = "Greetings"
  57. __HELP__ = """
  58. /captcha [ENABLE|DISABLE] - Enable/Disable captcha.
  59. /set_welcome - Reply this to a message containing correct
  60. format for a welcome message, check end of this message.
  61. /del_welcome - Delete the welcome message.
  62. /get_welcome - Get the welcome message.
  63. **SET_WELCOME ->**
  64. The format should be something like below.
  65. ```
  66. **Hi** {name} Welcome to {chat}
  67. ~ #This separater (~) should be there between text and buttons, remove this comment also
  68. button=[Duck, https://duckduckgo.com]
  69. button2=[Github, https://github.com]
  70. ```
  71. **NOTES ->**
  72. for /rules, you can do /filter rules to a message
  73. containing rules of your groups whenever a user
  74. sends /rules, he'll get the message
  75. Checkout /markdownhelp to know more about formattings and other syntax.
  76. """
  77. answers_dicc = []
  78. loop = asyncio.get_running_loop()
  79. async def get_initial_captcha_cache():
  80. global answers_dicc
  81. answers_dicc = await get_captcha_cache()
  82. return answers_dicc
  83. loop.create_task(get_initial_captcha_cache())
  84. @app.on_message(filters.new_chat_members, group=welcome_captcha_group)
  85. @capture_err
  86. async def welcome(_, message: Message):
  87. global answers_dicc
  88. # Get cached answers from mongodb in case of bot's been restarted or crashed.
  89. answers_dicc = await get_captcha_cache()
  90. # Mute new member and send message with button
  91. if not await is_captcha_on(message.chat.id):
  92. return
  93. for member in message.new_chat_members:
  94. try:
  95. if member.id in SUDOERS:
  96. continue # ignore sudo users
  97. if await is_gbanned_user(member.id):
  98. await message.chat.ban_member(member.id)
  99. await message.reply_text(
  100. f"{member.mention} was globally banned, and got removed,"
  101. + " if you think this is a false gban, you can appeal"
  102. + " for this ban in support chat."
  103. )
  104. continue
  105. if member.is_bot:
  106. continue # ignore bots
  107. # Ignore user if he has already solved captcha in this group
  108. # someday
  109. if await has_solved_captcha_once(message.chat.id, member.id):
  110. continue
  111. await message.chat.restrict_member(member.id, ChatPermissions())
  112. text = (
  113. f"{(member.mention())} Are you human?\n"
  114. f"Solve this captcha in {WELCOME_DELAY_KICK_SEC} "
  115. "seconds and 4 attempts or you'll be kicked."
  116. )
  117. except ChatAdminRequired:
  118. return
  119. # Generate a captcha image, answers and some wrong answers
  120. captcha = generate_captcha()
  121. captcha_image = captcha[0]
  122. captcha_answer = captcha[1]
  123. wrong_answers = captcha[2] # This consists of 8 wrong answers
  124. correct_button = InlineKeyboardButton(
  125. f"{captcha_answer}",
  126. callback_data=f"pressed_button {captcha_answer} {member.id}",
  127. )
  128. temp_keyboard_1 = [correct_button] # Button row 1
  129. temp_keyboard_2 = [] # Botton row 2
  130. temp_keyboard_3 = []
  131. for i in range(2):
  132. temp_keyboard_1.append(
  133. InlineKeyboardButton(
  134. f"{wrong_answers[i]}",
  135. callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
  136. )
  137. )
  138. for i in range(2, 5):
  139. temp_keyboard_2.append(
  140. InlineKeyboardButton(
  141. f"{wrong_answers[i]}",
  142. callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
  143. )
  144. )
  145. for i in range(5, 8):
  146. temp_keyboard_3.append(
  147. InlineKeyboardButton(
  148. f"{wrong_answers[i]}",
  149. callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
  150. )
  151. )
  152. shuffle(temp_keyboard_1)
  153. keyboard = [temp_keyboard_1, temp_keyboard_2, temp_keyboard_3]
  154. shuffle(keyboard)
  155. verification_data = {
  156. "chat_id": message.chat.id,
  157. "user_id": member.id,
  158. "answer": captcha_answer,
  159. "keyboard": keyboard,
  160. "attempts": 0,
  161. }
  162. keyboard = InlineKeyboardMarkup(keyboard)
  163. # Append user info, correct answer and
  164. answers_dicc.append(verification_data)
  165. # keyboard for later use with callback query
  166. button_message = await message.reply_photo(
  167. photo=captcha_image,
  168. caption=text,
  169. reply_markup=keyboard,
  170. quote=True,
  171. )
  172. os.remove(captcha_image)
  173. # Save captcha answers etc in mongodb in case bot gets crashed or restarted.
  174. await update_captcha_cache(answers_dicc)
  175. asyncio.create_task(
  176. kick_restricted_after_delay(WELCOME_DELAY_KICK_SEC, button_message, member)
  177. )
  178. await asyncio.sleep(0.5)
  179. async def send_welcome_message(chat: Chat, user_id: int, delete: bool = False):
  180. raw_text = await get_welcome(chat.id)
  181. if not raw_text:
  182. return
  183. text, keyb = extract_text_and_keyb(ikb, raw_text)
  184. if "{chat}" in text:
  185. text = text.replace("{chat}", chat.title)
  186. if "{name}" in text:
  187. text = text.replace("{name}", (await app.get_users(user_id)).mention)
  188. async def _send_wait_delete():
  189. m = await app.send_message(
  190. chat.id,
  191. text=text,
  192. reply_markup=keyb,
  193. disable_web_page_preview=True,
  194. )
  195. await asyncio.sleep(300)
  196. await m.delete()
  197. asyncio.create_task(_send_wait_delete())
  198. @app.on_callback_query(filters.regex("pressed_button"))
  199. async def callback_query_welcome_button(_, callback_query):
  200. """After the new member presses the correct button,
  201. set his permissions to chat permissions,
  202. delete button message and join message.
  203. """
  204. global answers_dicc
  205. data = callback_query.data
  206. pressed_user_id = callback_query.from_user.id
  207. pending_user_id = int(data.split(None, 2)[2])
  208. button_message = callback_query.message
  209. answer = data.split(None, 2)[1]
  210. correct_answer = None
  211. keyboard = None
  212. if len(answers_dicc) != 0:
  213. for i in answers_dicc:
  214. if (
  215. i["user_id"] == pending_user_id
  216. and i["chat_id"] == button_message.chat.id
  217. ):
  218. correct_answer = i["answer"]
  219. keyboard = i["keyboard"]
  220. if not (correct_answer and keyboard):
  221. return await callback_query.answer("Something went wrong, Rejoin the " "chat!")
  222. if pending_user_id != pressed_user_id:
  223. return await callback_query.answer("This is not for you")
  224. if answer != correct_answer:
  225. await callback_query.answer("Yeah, It's Wrong.")
  226. for iii in answers_dicc:
  227. if (
  228. iii["user_id"] == pending_user_id
  229. and iii["chat_id"] == button_message.chat.id
  230. ):
  231. attempts = iii["attempts"]
  232. if attempts >= 3:
  233. answers_dicc.remove(iii)
  234. await button_message.chat.ban_member(pending_user_id)
  235. await asyncio.sleep(1)
  236. await button_message.chat.unban_member(pending_user_id)
  237. await button_message.delete()
  238. await update_captcha_cache(answers_dicc)
  239. return
  240. iii["attempts"] += 1
  241. break
  242. shuffle(keyboard[0])
  243. shuffle(keyboard[1])
  244. shuffle(keyboard[2])
  245. shuffle(keyboard)
  246. keyboard = InlineKeyboardMarkup(keyboard)
  247. return await button_message.edit(
  248. text=button_message.caption.markdown,
  249. reply_markup=keyboard,
  250. )
  251. await callback_query.answer("Captcha passed successfully!")
  252. await button_message.chat.unban_member(pending_user_id)
  253. await button_message.delete()
  254. if len(answers_dicc) != 0:
  255. for ii in answers_dicc:
  256. if (
  257. ii["user_id"] == pending_user_id
  258. and ii["chat_id"] == button_message.chat.id
  259. ):
  260. answers_dicc.remove(ii)
  261. await update_captcha_cache(answers_dicc)
  262. chat = callback_query.message.chat
  263. # Save this verification in db, so we don't have to
  264. # send captcha to this user when he joins again.
  265. await save_captcha_solved(chat.id, pending_user_id)
  266. return await send_welcome_message(chat, pending_user_id, True)
  267. async def kick_restricted_after_delay(delay, button_message: Message, user: User):
  268. """If the new member is still restricted after the delay, delete
  269. button message and join message and then kick him
  270. """
  271. global answers_dicc
  272. await asyncio.sleep(delay)
  273. join_message = button_message.reply_to_message
  274. group_chat = button_message.chat
  275. user_id = user.id
  276. await join_message.delete()
  277. await button_message.delete()
  278. if len(answers_dicc) != 0:
  279. for i in answers_dicc:
  280. if i["user_id"] == user_id:
  281. answers_dicc.remove(i)
  282. await update_captcha_cache(answers_dicc)
  283. await _ban_restricted_user_until_date(group_chat, user_id, duration=delay)
  284. async def _ban_restricted_user_until_date(group_chat, user_id: int, duration: int):
  285. try:
  286. member = await group_chat.get_member(user_id)
  287. if member.status == ChatMemberStatus.RESTRICTED:
  288. until_date = int(datetime.utcnow().timestamp() + duration)
  289. await group_chat.ban_member(user_id, until_date=until_date)
  290. except UserNotParticipant:
  291. pass
  292. @app.on_message(filters.command("captcha") & ~filters.private)
  293. @adminsOnly("can_restrict_members")
  294. async def captcha_state(_, message):
  295. usage = "**Usage:**\n/captcha [ENABLE|DISABLE]"
  296. if len(message.command) != 2:
  297. await message.reply_text(usage)
  298. return
  299. chat_id = message.chat.id
  300. state = message.text.split(None, 1)[1].strip()
  301. state = state.lower()
  302. if state == "enable":
  303. await captcha_on(chat_id)
  304. await message.reply_text("Enabled Captcha For New Users.")
  305. elif state == "disable":
  306. await captcha_off(chat_id)
  307. await message.reply_text("Disabled Captcha For New Users.")
  308. else:
  309. await message.reply_text(usage)
  310. # WELCOME MESSAGE
  311. @app.on_message(filters.command("set_welcome") & ~filters.private)
  312. @adminsOnly("can_change_info")
  313. async def set_welcome_func(_, message):
  314. usage = "You need to reply to a text, check the Greetings module in /help"
  315. if not message.reply_to_message:
  316. await message.reply_text(usage)
  317. return
  318. if not message.reply_to_message.text:
  319. await message.reply_text(usage)
  320. return
  321. chat_id = message.chat.id
  322. raw_text = message.reply_to_message.text.markdown
  323. if not (extract_text_and_keyb(ikb, raw_text)):
  324. return await message.reply_text("Wrong formating, check help section.")
  325. await set_welcome(chat_id, raw_text)
  326. await message.reply_text("Welcome message has been successfully set.")
  327. @app.on_message(filters.command("del_welcome") & ~filters.private)
  328. @adminsOnly("can_change_info")
  329. async def del_welcome_func(_, message):
  330. chat_id = message.chat.id
  331. await del_welcome(chat_id)
  332. await message.reply_text("Welcome message has been deleted.")
  333. @app.on_message(filters.command("get_welcome") & ~filters.private)
  334. @adminsOnly("can_change_info")
  335. async def get_welcome_func(_, message):
  336. chat = message.chat
  337. welcome = await get_welcome(chat.id)
  338. if not welcome:
  339. return await message.reply_text("No welcome message set.")
  340. if not message.from_user:
  341. return await message.reply_text("You're anon, can't send welcome message.")
  342. await send_welcome_message(chat, message.from_user.id)
  343. await message.reply_text(f'`{welcome.replace("`", "")}`')