greetings.py 13 KB

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