greetings.py 14 KB

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