greetings.py 14 KB

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