greetings.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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 pykeyboard import InlineKeyboard
  25. from pyrogram import filters
  26. from pyrogram.errors.exceptions.bad_request_400 import (
  27. ChatAdminRequired, UserNotParticipant)
  28. from pyrogram.types import (ChatPermissions, 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.utils.dbfunctions import (captcha_off, captcha_on,
  34. del_welcome, get_captcha_cache,
  35. get_welcome, is_captcha_on,
  36. is_gbanned_user, set_welcome,
  37. update_captcha_cache)
  38. from wbb.utils.filter_groups import welcome_captcha_group
  39. from wbb.utils.functions import 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 sudos
  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. await message.chat.restrict_member(
  91. member.id, ChatPermissions()
  92. )
  93. text = (
  94. f"{(member.mention())} Are you human?\n"
  95. f"Solve this captcha in {WELCOME_DELAY_KICK_SEC} seconds and 4 attempts or you'll be kicked."
  96. )
  97. except ChatAdminRequired:
  98. return
  99. # Generate a captcha image, answers and some wrong answers
  100. captcha = generate_captcha()
  101. captcha_image = captcha[0]
  102. captcha_answer = captcha[1]
  103. wrong_answers = captcha[2] # This consists of 8 wrong answers
  104. correct_button = InlineKeyboardButton(
  105. f"{captcha_answer}",
  106. callback_data=f"pressed_button {captcha_answer} {member.id}",
  107. )
  108. temp_keyboard_1 = [correct_button] # Button row 1
  109. temp_keyboard_2 = [] # Botton row 2
  110. temp_keyboard_3 = []
  111. for i in range(2):
  112. temp_keyboard_1.append(
  113. InlineKeyboardButton(
  114. f"{wrong_answers[i]}",
  115. callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
  116. )
  117. )
  118. for i in range(2, 5):
  119. temp_keyboard_2.append(
  120. InlineKeyboardButton(
  121. f"{wrong_answers[i]}",
  122. callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
  123. )
  124. )
  125. for i in range(5, 8):
  126. temp_keyboard_3.append(
  127. InlineKeyboardButton(
  128. f"{wrong_answers[i]}",
  129. callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
  130. )
  131. )
  132. shuffle(temp_keyboard_1)
  133. keyboard = [temp_keyboard_1, temp_keyboard_2, temp_keyboard_3]
  134. shuffle(keyboard)
  135. verification_data = {
  136. "chat_id": message.chat.id,
  137. "user_id": member.id,
  138. "answer": captcha_answer,
  139. "keyboard": keyboard,
  140. "attempts": 0,
  141. }
  142. keyboard = InlineKeyboardMarkup(keyboard)
  143. # Append user info, correct answer and
  144. answers_dicc.append(verification_data)
  145. # keyboard for later use with callback query
  146. button_message = await message.reply_photo(
  147. photo=captcha_image,
  148. caption=text,
  149. reply_markup=keyboard,
  150. quote=True,
  151. )
  152. os.remove(captcha_image)
  153. """ Save captcha answers etc in mongodb in case bot gets crashed or restarted. """
  154. await update_captcha_cache(answers_dicc)
  155. asyncio.create_task(
  156. kick_restricted_after_delay(
  157. WELCOME_DELAY_KICK_SEC, button_message, member
  158. )
  159. )
  160. await asyncio.sleep(0.5)
  161. async def send_welcome_message(callback_query, pending_user_id):
  162. try:
  163. raw_text = await get_welcome(callback_query.message.chat.id)
  164. except TypeError:
  165. return
  166. raw_text = raw_text.strip().replace("`", "")
  167. if not raw_text:
  168. return
  169. text = raw_text.split("~")[0].strip()
  170. buttons_text_list = raw_text.split("~")[1].strip().splitlines()
  171. if "{chat}" in text:
  172. text = text.replace(
  173. "{chat}", callback_query.message.chat.title
  174. )
  175. if "{name}" in text:
  176. text = text.replace(
  177. "{name}", (await app.get_users(pending_user_id)).mention
  178. )
  179. buttons = InlineKeyboard(row_width=2)
  180. list_of_buttons = []
  181. for button_string in buttons_text_list:
  182. button_string = button_string.strip().split("=")[1].strip()
  183. button_string = button_string.replace("[", "").strip()
  184. button_string = button_string.replace("]", "").strip()
  185. button_string = button_string.split(",")
  186. button_text = button_string[0].strip()
  187. button_url = button_string[1].strip()
  188. list_of_buttons.append(
  189. InlineKeyboardButton(text=button_text, url=button_url)
  190. )
  191. buttons.add(*list_of_buttons)
  192. await app.send_message(
  193. callback_query.message.chat.id,
  194. text=text,
  195. reply_markup=buttons,
  196. disable_web_page_preview=True,
  197. )
  198. @app.on_callback_query(filters.regex("pressed_button"))
  199. async def callback_query_welcome_button(_, callback_query):
  200. """After the new member presses the correct button,
  201. set his permissions to chat permissions,
  202. delete button message and join message.
  203. """
  204. global answers_dicc
  205. data = callback_query.data
  206. pressed_user_id = callback_query.from_user.id
  207. pending_user_id = int(data.split(None, 2)[2])
  208. button_message = callback_query.message
  209. answer = data.split(None, 2)[1]
  210. if len(answers_dicc) != 0:
  211. for i in answers_dicc:
  212. if (
  213. i["user_id"] == pending_user_id
  214. and i["chat_id"] == button_message.chat.id
  215. ):
  216. correct_answer = i["answer"]
  217. keyboard = i["keyboard"]
  218. if pending_user_id == pressed_user_id:
  219. if answer != correct_answer:
  220. await callback_query.answer("Yeah, It's Wrong.")
  221. for iii in answers_dicc:
  222. if (
  223. iii["user_id"] == pending_user_id
  224. and iii["chat_id"] == button_message.chat.id
  225. ):
  226. attempts = iii["attempts"]
  227. if attempts >= 3:
  228. answers_dicc.remove(iii)
  229. await button_message.chat.kick_member(
  230. pending_user_id
  231. )
  232. await asyncio.sleep(1)
  233. await button_message.chat.unban_member(
  234. pending_user_id
  235. )
  236. await button_message.delete()
  237. await update_captcha_cache(answers_dicc)
  238. return
  239. else:
  240. iii["attempts"] += 1
  241. break
  242. shuffle(keyboard[0])
  243. shuffle(keyboard[1])
  244. shuffle(keyboard[2])
  245. shuffle(keyboard)
  246. keyboard = InlineKeyboardMarkup(keyboard)
  247. await button_message.edit(
  248. text=button_message.caption.markdown,
  249. reply_markup=keyboard,
  250. )
  251. return
  252. await callback_query.answer("Captcha passed successfully!")
  253. await button_message.chat.unban_member(pending_user_id)
  254. await button_message.delete()
  255. if len(answers_dicc) != 0:
  256. for ii in answers_dicc:
  257. if (
  258. ii["user_id"] == pending_user_id
  259. and ii["chat_id"] == button_message.chat.id
  260. ):
  261. answers_dicc.remove(ii)
  262. await update_captcha_cache(answers_dicc)
  263. """ send welcome message """
  264. await send_welcome_message(callback_query, pending_user_id)
  265. return
  266. else:
  267. await callback_query.answer("This is not for you")
  268. return
  269. async def kick_restricted_after_delay(
  270. delay, button_message: Message, user: User
  271. ):
  272. """If the new member is still restricted after the delay, delete
  273. button message and join message and then kick him
  274. """
  275. global answers_dicc
  276. await asyncio.sleep(delay)
  277. join_message = button_message.reply_to_message
  278. group_chat = button_message.chat
  279. user_id = user.id
  280. await join_message.delete()
  281. await button_message.delete()
  282. if len(answers_dicc) != 0:
  283. for i in answers_dicc:
  284. if i["user_id"] == user_id:
  285. answers_dicc.remove(i)
  286. await update_captcha_cache(answers_dicc)
  287. await _ban_restricted_user_until_date(
  288. group_chat, user_id, duration=delay
  289. )
  290. async def _ban_restricted_user_until_date(
  291. group_chat, user_id: int, duration: int
  292. ):
  293. try:
  294. member = await group_chat.get_member(user_id)
  295. if member.status == "restricted":
  296. until_date = int(datetime.utcnow().timestamp() + duration)
  297. await group_chat.kick_member(
  298. user_id, until_date=until_date
  299. )
  300. except UserNotParticipant:
  301. pass
  302. @app.on_message(filters.command("captcha") & ~filters.private)
  303. @adminsOnly("can_restrict_members")
  304. async def captcha_state(_, message):
  305. usage = "**Usage:**\n/captcha [ENABLE|DISABLE]"
  306. if len(message.command) != 2:
  307. await message.reply_text(usage)
  308. return
  309. chat_id = message.chat.id
  310. state = message.text.split(None, 1)[1].strip()
  311. state = state.lower()
  312. if state == "enable":
  313. await captcha_on(chat_id)
  314. await message.reply_text("Enabled Captcha For New Users.")
  315. elif state == "disable":
  316. await captcha_off(chat_id)
  317. await message.reply_text("Disabled Captcha For New Users.")
  318. else:
  319. await message.reply_text(usage)
  320. """ WELCOME MESSAGE """
  321. @app.on_message(filters.command("set_welcome") & ~filters.private)
  322. @adminsOnly("can_change_info")
  323. async def set_welcome_func(_, message):
  324. usage = "You need to reply to a text, check the Greetings module in /help"
  325. if not message.reply_to_message:
  326. await message.reply_text(usage)
  327. return
  328. if not message.reply_to_message.text:
  329. await message.reply_text(usage)
  330. return
  331. chat_id = message.chat.id
  332. raw_text = str(message.reply_to_message.text.markdown)
  333. await set_welcome(chat_id, raw_text)
  334. await message.reply_text(
  335. "Welcome message has been successfully set."
  336. )
  337. @app.on_message(filters.command("del_welcome") & ~filters.private)
  338. @adminsOnly("can_change_info")
  339. async def del_welcome_func(_, message):
  340. chat_id = message.chat.id
  341. await del_welcome(chat_id)
  342. await message.reply_text("Welcome message has been deleted.")
  343. @app.on_message(filters.command("get_welcome") & ~filters.private)
  344. @adminsOnly("can_change_info")
  345. async def get_welcome_func(_, message):
  346. chat_id = message.chat.id
  347. welcome_message = await get_welcome(chat_id)
  348. await message.reply_text(welcome_message)