greetings.py 14 KB

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