greetings.py 14 KB

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