greetings.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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.enums import ChatMemberStatus
  26. from pyrogram.errors.exceptions.bad_request_400 import (
  27. ChatAdminRequired,
  28. UserNotParticipant,
  29. )
  30. from pyrogram.types import (
  31. Chat,
  32. ChatPermissions,
  33. InlineKeyboardButton,
  34. InlineKeyboardMarkup,
  35. Message,
  36. User,
  37. )
  38. from wbb import SUDOERS, WELCOME_DELAY_KICK_SEC, app
  39. from wbb.core.decorators.errors import capture_err
  40. from wbb.core.decorators.permissions import adminsOnly
  41. from wbb.core.keyboard import ikb
  42. from wbb.utils.dbfunctions import (
  43. captcha_off,
  44. captcha_on,
  45. del_welcome,
  46. get_captcha_cache,
  47. get_welcome,
  48. has_solved_captcha_once,
  49. is_captcha_on,
  50. is_gbanned_user,
  51. save_captcha_solved,
  52. set_welcome,
  53. update_captcha_cache,
  54. )
  55. from wbb.utils.filter_groups import welcome_captcha_group
  56. from wbb.utils.functions import extract_text_and_keyb, generate_captcha
  57. __MODULE__ = "Greetings"
  58. __HELP__ = """
  59. /captcha [ENABLE|DISABLE] - Enable/Disable captcha.
  60. /set_welcome - Reply this to a message containing correct
  61. format for a welcome message, check end of this message.
  62. /del_welcome - Delete the welcome message.
  63. /get_welcome - Get the welcome message.
  64. **SET_WELCOME ->**
  65. The format should be something like below.
  66. ```
  67. **Hi** {name} Welcome to {chat}
  68. ~ #This separater (~) should be there between text and buttons, remove this comment also
  69. button=[Duck, https://duckduckgo.com]
  70. button2=[Github, https://github.com]
  71. ```
  72. **NOTES ->**
  73. for /rules, you can do /filter rules to a message
  74. containing rules of your groups whenever a user
  75. sends /rules, he'll get the message
  76. Checkout /markdownhelp to know more about formattings and other syntax.
  77. """
  78. answers_dicc = []
  79. loop = asyncio.get_running_loop()
  80. async def get_initial_captcha_cache():
  81. global answers_dicc
  82. answers_dicc = await get_captcha_cache()
  83. return answers_dicc
  84. loop.create_task(get_initial_captcha_cache())
  85. async def handle_new_member(message: Message, member, chat):
  86. global answers_dicc
  87. # Get cached answers from mongodb in case of bot's been restarted or crashed.
  88. answers_dicc = await get_captcha_cache()
  89. # Mute new member and send message with button
  90. if not await is_captcha_on(message.chat.id):
  91. await send_welcome_message(message.chat, member.id)
  92. return
  93. try:
  94. if member.id in SUDOERS:
  95. return # Ignore sudo users
  96. if await is_gbanned_user(member.id):
  97. await message.chat.ban_member(member.id)
  98. await app.send_message(
  99. chat.id,
  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. return
  105. if member.is_bot:
  106. return # 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. return
  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 app.send_photo(
  167. chat_id=chat.id,
  168. photo=captcha_image,
  169. caption=text,
  170. reply_markup=keyboard,
  171. )
  172. os.remove(captcha_image)
  173. # Save captcha answers etc in mongodb in case the 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. @app.on_message(filters.new_chat_members, group=welcome_captcha_group)
  180. @capture_err
  181. async def welcome(_, message: Message):
  182. chat = message.chat
  183. members = message.new_chat_members
  184. for member in members:
  185. return await handle_new_member(message, member, chat)
  186. async def send_welcome_message(chat: Chat, user_id: int, delete: bool = False):
  187. raw_text = await get_welcome(chat.id)
  188. if not raw_text:
  189. return
  190. text, keyb = extract_text_and_keyb(ikb, raw_text)
  191. if "{chat}" in text:
  192. text = text.replace("{chat}", chat.title)
  193. if "{name}" in text:
  194. text = text.replace("{name}", (await app.get_users(user_id)).mention)
  195. async def _send_wait_delete():
  196. m = await app.send_message(
  197. chat.id,
  198. text=text,
  199. reply_markup=keyb,
  200. disable_web_page_preview=True,
  201. )
  202. await asyncio.sleep(300)
  203. await m.delete()
  204. asyncio.create_task(_send_wait_delete())
  205. @app.on_callback_query(filters.regex("pressed_button"))
  206. async def callback_query_welcome_button(_, callback_query):
  207. """After the new member presses the correct button,
  208. set his permissions to chat permissions,
  209. delete button message and join message.
  210. """
  211. global answers_dicc
  212. data = callback_query.data
  213. pressed_user_id = callback_query.from_user.id
  214. pending_user_id = int(data.split(None, 2)[2])
  215. button_message = callback_query.message
  216. answer = data.split(None, 2)[1]
  217. correct_answer = None
  218. keyboard = None
  219. if len(answers_dicc) != 0:
  220. for i in answers_dicc:
  221. if (
  222. i["user_id"] == pending_user_id
  223. and i["chat_id"] == button_message.chat.id
  224. ):
  225. correct_answer = i["answer"]
  226. keyboard = i["keyboard"]
  227. if not (correct_answer and keyboard):
  228. return await callback_query.answer("Something went wrong, Rejoin the " "chat!")
  229. if pending_user_id != pressed_user_id:
  230. return await callback_query.answer("This is not for you")
  231. if answer != correct_answer:
  232. await callback_query.answer("Yeah, It's Wrong.")
  233. for iii in answers_dicc:
  234. if (
  235. iii["user_id"] == pending_user_id
  236. and iii["chat_id"] == button_message.chat.id
  237. ):
  238. attempts = iii["attempts"]
  239. if attempts >= 3:
  240. answers_dicc.remove(iii)
  241. await button_message.chat.ban_member(pending_user_id)
  242. await asyncio.sleep(1)
  243. await button_message.chat.unban_member(pending_user_id)
  244. await button_message.delete()
  245. await update_captcha_cache(answers_dicc)
  246. return
  247. iii["attempts"] += 1
  248. break
  249. shuffle(keyboard[0])
  250. shuffle(keyboard[1])
  251. shuffle(keyboard[2])
  252. shuffle(keyboard)
  253. keyboard = InlineKeyboardMarkup(keyboard)
  254. return await button_message.edit(
  255. text=button_message.caption.markdown,
  256. reply_markup=keyboard,
  257. )
  258. await callback_query.answer("Captcha passed successfully!")
  259. await button_message.chat.unban_member(pending_user_id)
  260. await button_message.delete()
  261. if len(answers_dicc) != 0:
  262. for ii in answers_dicc:
  263. if (
  264. ii["user_id"] == pending_user_id
  265. and ii["chat_id"] == button_message.chat.id
  266. ):
  267. answers_dicc.remove(ii)
  268. await update_captcha_cache(answers_dicc)
  269. chat = callback_query.message.chat
  270. # Save this verification in db, so we don't have to
  271. # send captcha to this user when he joins again.
  272. await save_captcha_solved(chat.id, pending_user_id)
  273. return await send_welcome_message(chat, pending_user_id, True)
  274. async def kick_restricted_after_delay(delay, button_message: Message, user: User):
  275. """If the new member is still restricted after the delay, delete
  276. button message and join message and then kick him
  277. """
  278. global answers_dicc
  279. await asyncio.sleep(delay)
  280. join_message = button_message.reply_to_message
  281. group_chat = button_message.chat
  282. user_id = user.id
  283. await join_message.delete()
  284. await button_message.delete()
  285. if len(answers_dicc) != 0:
  286. for i in answers_dicc:
  287. if i["user_id"] == user_id:
  288. answers_dicc.remove(i)
  289. await update_captcha_cache(answers_dicc)
  290. await _ban_restricted_user_until_date(group_chat, user_id, duration=delay)
  291. async def _ban_restricted_user_until_date(group_chat, user_id: int, duration: int):
  292. try:
  293. member = await group_chat.get_member(user_id)
  294. if member.status == ChatMemberStatus.RESTRICTED:
  295. until_date = int(datetime.utcnow().timestamp() + duration)
  296. await group_chat.ban_member(user_id, until_date=until_date)
  297. except UserNotParticipant:
  298. pass
  299. @app.on_message(filters.command("captcha") & ~filters.private)
  300. @adminsOnly("can_restrict_members")
  301. async def captcha_state(_, message):
  302. usage = "**Usage:**\n/captcha [ENABLE|DISABLE]"
  303. if len(message.command) != 2:
  304. await message.reply_text(usage)
  305. return
  306. chat_id = message.chat.id
  307. state = message.text.split(None, 1)[1].strip()
  308. state = state.lower()
  309. if state == "enable":
  310. await captcha_on(chat_id)
  311. await message.reply_text("Enabled Captcha For New Users.")
  312. elif state == "disable":
  313. await captcha_off(chat_id)
  314. await message.reply_text("Disabled Captcha For New Users.")
  315. else:
  316. await message.reply_text(usage)
  317. # WELCOME MESSAGE
  318. @app.on_message(filters.command("set_welcome") & ~filters.private)
  319. @adminsOnly("can_change_info")
  320. async def set_welcome_func(_, message):
  321. usage = "You need to reply to a text, check the Greetings module in /help"
  322. if not message.reply_to_message:
  323. await message.reply_text(usage)
  324. return
  325. if not message.reply_to_message.text:
  326. await message.reply_text(usage)
  327. return
  328. chat_id = message.chat.id
  329. raw_text = message.reply_to_message.text.markdown
  330. if not (extract_text_and_keyb(ikb, raw_text)):
  331. return await message.reply_text("Wrong formating, check help section.")
  332. await set_welcome(chat_id, raw_text)
  333. await message.reply_text("Welcome message has been successfully set.")
  334. @app.on_message(filters.command("del_welcome") & ~filters.private)
  335. @adminsOnly("can_change_info")
  336. async def del_welcome_func(_, message):
  337. chat_id = message.chat.id
  338. await del_welcome(chat_id)
  339. await message.reply_text("Welcome message has been deleted.")
  340. @app.on_message(filters.command("get_welcome") & ~filters.private)
  341. @adminsOnly("can_change_info")
  342. async def get_welcome_func(_, message):
  343. chat = message.chat
  344. welcome = await get_welcome(chat.id)
  345. if not welcome:
  346. return await message.reply_text("No welcome message set.")
  347. if not message.from_user:
  348. return await message.reply_text("You're anon, can't send welcome message.")
  349. await send_welcome_message(chat, message.from_user.id)
  350. await message.reply_text(f'`{welcome.replace("`", "")}`')