greetings.py 14 KB

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