greetings.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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 wbb import app, WELCOME_DELAY_KICK_SEC, SUDOERS
  23. from wbb.modules.admin import member_permissions
  24. from wbb.core.decorators.errors import capture_err
  25. from wbb.utils.filter_groups import welcome_captcha_group
  26. from wbb.utils.functions import generate_captcha
  27. from wbb.utils.dbfunctions import (
  28. is_gbanned_user, is_captcha_on, captcha_on, captcha_off
  29. )
  30. from pyrogram.types import (
  31. Message, InlineKeyboardMarkup,
  32. InlineKeyboardButton, ChatPermissions, User
  33. )
  34. from pyrogram.errors.exceptions.bad_request_400 import UserNotParticipant, ChatAdminRequired
  35. from pyrogram import filters
  36. from random import shuffle
  37. from datetime import datetime
  38. __MODULE__ = "Captcha"
  39. __HELP__ = "/captcha [ON|OFF] - Enable/Disable Captcha."
  40. answers_dicc = []
  41. @app.on_message(filters.new_chat_members, group=welcome_captcha_group)
  42. @capture_err
  43. async def welcome(_, message: Message):
  44. global answers_dicc
  45. """Mute new member and send message with button"""
  46. if not await is_captcha_on(message.chat.id):
  47. return
  48. for member in message.new_chat_members:
  49. try:
  50. if member.id in SUDOERS:
  51. continue # ignore sudos
  52. if await is_gbanned_user(member.id):
  53. await message.chat.kick_member(member.id)
  54. await message.reply_text(f"{member.mention} was globally banned, and got removed,"
  55. + " if you think this is a false gban, you can appeal"
  56. + " for this ban in support chat.")
  57. continue
  58. if member.is_bot:
  59. continue # ignore bots
  60. await message.chat.restrict_member(member.id, ChatPermissions())
  61. text = (f"Welcome, {(member.mention())} Are you human?\n"
  62. f"Solve this captcha in {WELCOME_DELAY_KICK_SEC} seconds or you'll be kicked.")
  63. except ChatAdminRequired:
  64. break
  65. # Generate a captcha image, answers and some wrong answers
  66. captcha = generate_captcha()
  67. captcha_image = captcha[0]
  68. captcha_answer = captcha[1]
  69. wrong_answers = captcha[2] # This consists of 8 wrong answers
  70. correct_button = InlineKeyboardButton(
  71. f"{captcha_answer}",
  72. callback_data=f"pressed_button {captcha_answer} {member.id}"
  73. )
  74. temp_keyboard_1 = [correct_button] # Button row 1
  75. temp_keyboard_2 = [] # Botton row 2
  76. temp_keyboard_3 = []
  77. for i in range(2):
  78. temp_keyboard_1.append(
  79. InlineKeyboardButton(
  80. f"{wrong_answers[i]}",
  81. callback_data=f"pressed_button {wrong_answers[i]} {member.id}"
  82. )
  83. )
  84. for i in range(2, 5):
  85. temp_keyboard_2.append(
  86. InlineKeyboardButton(
  87. f"{wrong_answers[i]}",
  88. callback_data=f"pressed_button {wrong_answers[i]} {member.id}"
  89. )
  90. )
  91. for i in range(5, 8):
  92. temp_keyboard_3.append(
  93. InlineKeyboardButton(
  94. f"{wrong_answers[i]}",
  95. callback_data=f"pressed_button {wrong_answers[i]} {member.id}"
  96. )
  97. )
  98. shuffle(temp_keyboard_1)
  99. keyboard = [temp_keyboard_1, temp_keyboard_2, temp_keyboard_3]
  100. shuffle(keyboard)
  101. verification_data = {
  102. "user_id": member.id,
  103. "answer": captcha_answer,
  104. "keyboard": keyboard
  105. }
  106. keyboard = InlineKeyboardMarkup(keyboard)
  107. # Append user info, correct answer and
  108. answers_dicc.append(verification_data)
  109. # keyboard for later use with callback query
  110. button_message = await message.reply_photo(
  111. photo=captcha_image,
  112. caption=text,
  113. reply_markup=keyboard,
  114. quote=True
  115. )
  116. os.remove(captcha_image)
  117. asyncio.create_task(kick_restricted_after_delay(
  118. WELCOME_DELAY_KICK_SEC, button_message, member))
  119. await asyncio.sleep(0.5)
  120. @app.on_callback_query(filters.regex("pressed_button"))
  121. async def callback_query_welcome_button(_, callback_query):
  122. """After the new member presses the correct button,
  123. set his permissions to chat permissions,
  124. delete button message and join message.
  125. """
  126. global answers_dicc
  127. data = callback_query.data
  128. pending_user = await app.get_users(int(data.split(None, 2)[2]))
  129. pressed_user_id = callback_query.from_user.id
  130. pending_user_id = pending_user.id
  131. button_message = callback_query.message
  132. answer = data.split(None, 2)[1]
  133. if len(answers_dicc) != 0:
  134. for i in answers_dicc:
  135. if i['user_id'] == pending_user_id:
  136. correct_answer = i['answer']
  137. keyboard = i['keyboard']
  138. if pending_user_id == pressed_user_id:
  139. if answer != correct_answer:
  140. await callback_query.answer("Yeah, It's Wrong.")
  141. shuffle(keyboard[0])
  142. shuffle(keyboard[1])
  143. shuffle(keyboard[2])
  144. shuffle(keyboard)
  145. keyboard = InlineKeyboardMarkup(keyboard)
  146. await button_message.edit(
  147. text=button_message.caption.markdown,
  148. reply_markup=keyboard
  149. )
  150. return
  151. await callback_query.answer("Captcha passed successfully!")
  152. await button_message.chat.unban_member(pending_user_id)
  153. await button_message.delete()
  154. if len(answers_dicc) != 0:
  155. for ii in answers_dicc:
  156. if ii['user_id'] == pending_user_id:
  157. answers_dicc.remove(ii)
  158. return
  159. else:
  160. await callback_query.answer("This is not for you")
  161. return
  162. async def kick_restricted_after_delay(delay, button_message: Message, user: User):
  163. """If the new member is still restricted after the delay, delete
  164. button message and join message and then kick him
  165. """
  166. global answers_dicc
  167. await asyncio.sleep(delay)
  168. join_message = button_message.reply_to_message
  169. group_chat = button_message.chat
  170. user_id = user.id
  171. await join_message.delete()
  172. await button_message.delete()
  173. if len(answers_dicc) != 0:
  174. for i in answers_dicc:
  175. if i['user_id'] == user_id:
  176. answers_dicc.remove(i)
  177. await _ban_restricted_user_until_date(group_chat, user_id, duration=delay)
  178. async def _ban_restricted_user_until_date(group_chat,
  179. user_id: int,
  180. duration: int):
  181. try:
  182. member = await group_chat.get_member(user_id)
  183. if member.status == "restricted":
  184. until_date = int(datetime.utcnow().timestamp() + duration)
  185. await group_chat.kick_member(user_id, until_date=until_date)
  186. except UserNotParticipant:
  187. pass
  188. @app.on_message(filters.command("captcha") & ~filters.private)
  189. @capture_err
  190. async def captcha_state(_, message):
  191. usage = "**Usage:**\n/captcha [ON|OFF]"
  192. if len(message.command) != 2:
  193. await message.reply_text(usage)
  194. return
  195. user_id = message.from_user.id
  196. chat_id = message.chat.id
  197. permissions = await member_permissions(chat_id, user_id)
  198. if "can_restrict_members" not in permissions:
  199. await message.reply_text("You don't have enough permissions.")
  200. return
  201. state = message.text.split(None, 1)[1].strip()
  202. state = state.lower()
  203. if state == "on":
  204. await captcha_on(chat_id)
  205. await message.reply_text("Enabled Captcha For New Users.")
  206. elif state == "off":
  207. await captcha_off(chat_id)
  208. await message.reply_text("Disabled Captcha For New Users.")
  209. else:
  210. await message.reply_text(usage)