greetings.py 13 KB

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