greetings.py 13 KB

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