greetings.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. try:
  143. raw_text = await get_welcome(callback_query.message.chat.id)
  144. except TypeError:
  145. return
  146. raw_text = raw_text.strip().replace("`", "")
  147. if not raw_text:
  148. return
  149. text = raw_text.split("~")[0].strip()
  150. buttons_text_list = raw_text.split("~")[1].strip().splitlines()
  151. if "{chat}" in text:
  152. text = text.replace("{chat}", callback_query.message.chat.title)
  153. if "{name}" in text:
  154. text = text.replace("{name}", (await app.get_users(pending_user_id)).mention)
  155. buttons = InlineKeyboard(row_width=2)
  156. list_of_buttons = []
  157. for button_string in buttons_text_list:
  158. button_string = button_string.strip().split("=")[1].strip()
  159. button_string = button_string.replace("[", "").strip()
  160. button_string = button_string.replace("]", "").strip()
  161. button_string = button_string.split(",")
  162. button_text = button_string[0].strip()
  163. button_url = button_string[1].strip()
  164. list_of_buttons.append(
  165. InlineKeyboardButton(
  166. text=button_text,
  167. url=button_url
  168. )
  169. )
  170. buttons.add(*list_of_buttons)
  171. await app.send_message(
  172. callback_query.message.chat.id,
  173. text=text,
  174. reply_markup=buttons,
  175. disable_web_page_preview=True
  176. )
  177. @app.on_callback_query(filters.regex("pressed_button"))
  178. async def callback_query_welcome_button(_, callback_query):
  179. """After the new member presses the correct button,
  180. set his permissions to chat permissions,
  181. delete button message and join message.
  182. """
  183. global answers_dicc
  184. data = callback_query.data
  185. pending_user = await app.get_users(int(data.split(None, 2)[2]))
  186. pressed_user_id = callback_query.from_user.id
  187. pending_user_id = pending_user.id
  188. button_message = callback_query.message
  189. answer = data.split(None, 2)[1]
  190. if len(answers_dicc) != 0:
  191. for i in answers_dicc:
  192. if i['user_id'] == pending_user_id:
  193. correct_answer = i['answer']
  194. keyboard = i['keyboard']
  195. if pending_user_id == pressed_user_id:
  196. if answer != correct_answer:
  197. await callback_query.answer("Yeah, It's Wrong.")
  198. for iii in answers_dicc:
  199. if iii['user_id'] == pending_user_id:
  200. attempts = iii['attempts']
  201. if attempts >= 3:
  202. answers_dicc.remove(iii)
  203. await button_message.chat.kick_member(pending_user_id)
  204. await asyncio.sleep(1)
  205. await button_message.chat.unban_member(pending_user_id)
  206. await button_message.delete()
  207. return
  208. else:
  209. iii['attempts'] += 1
  210. break
  211. shuffle(keyboard[0])
  212. shuffle(keyboard[1])
  213. shuffle(keyboard[2])
  214. shuffle(keyboard)
  215. keyboard = InlineKeyboardMarkup(keyboard)
  216. await button_message.edit(
  217. text=button_message.caption.markdown,
  218. reply_markup=keyboard
  219. )
  220. return
  221. await callback_query.answer("Captcha passed successfully!")
  222. await button_message.chat.unban_member(pending_user_id)
  223. await button_message.delete()
  224. if len(answers_dicc) != 0:
  225. for ii in answers_dicc:
  226. if ii['user_id'] == pending_user_id:
  227. answers_dicc.remove(ii)
  228. """ send welcome message """
  229. await send_welcome_message(callback_query, pending_user_id)
  230. return
  231. else:
  232. await callback_query.answer("This is not for you")
  233. return
  234. async def kick_restricted_after_delay(delay, button_message: Message, user: User):
  235. """If the new member is still restricted after the delay, delete
  236. button message and join message and then kick him
  237. """
  238. global answers_dicc
  239. await asyncio.sleep(delay)
  240. join_message = button_message.reply_to_message
  241. group_chat = button_message.chat
  242. user_id = user.id
  243. await join_message.delete()
  244. await button_message.delete()
  245. if len(answers_dicc) != 0:
  246. for i in answers_dicc:
  247. if i['user_id'] == user_id:
  248. answers_dicc.remove(i)
  249. await _ban_restricted_user_until_date(group_chat, user_id, duration=delay)
  250. async def _ban_restricted_user_until_date(group_chat,
  251. user_id: int,
  252. duration: int):
  253. try:
  254. member = await group_chat.get_member(user_id)
  255. if member.status == "restricted":
  256. until_date = int(datetime.utcnow().timestamp() + duration)
  257. await group_chat.kick_member(user_id, until_date=until_date)
  258. except UserNotParticipant:
  259. pass
  260. @app.on_message(filters.command("captcha") & ~filters.private)
  261. @capture_err
  262. async def captcha_state(_, message):
  263. usage = "**Usage:**\n/captcha [ON|OFF]"
  264. if len(message.command) != 2:
  265. await message.reply_text(usage)
  266. return
  267. user_id = message.from_user.id
  268. chat_id = message.chat.id
  269. permissions = await member_permissions(chat_id, user_id)
  270. if "can_restrict_members" not in permissions:
  271. await message.reply_text("You don't have enough permissions.")
  272. return
  273. state = message.text.split(None, 1)[1].strip()
  274. state = state.lower()
  275. if state == "on":
  276. await captcha_on(chat_id)
  277. await message.reply_text("Enabled Captcha For New Users.")
  278. elif state == "off":
  279. await captcha_off(chat_id)
  280. await message.reply_text("Disabled Captcha For New Users.")
  281. else:
  282. await message.reply_text(usage)
  283. """ WELCOME MESSAGE """
  284. @app.on_message(filters.command("set_welcome") & ~filters.private)
  285. @capture_err
  286. async def set_welcome_func(_, message):
  287. usage = "You need to reply to a text, check the Greetings module in /help"
  288. if not message.reply_to_message:
  289. await message.reply_text(usage)
  290. return
  291. if not message.reply_to_message.text:
  292. await message.reply_text(usage)
  293. return
  294. user_id = message.from_user.id
  295. chat_id = message.chat.id
  296. permissions = await member_permissions(chat_id, user_id)
  297. if "can_change_info" not in permissions:
  298. await message.reply_text("You don't have enough permissions.")
  299. return
  300. raw_text = str(message.reply_to_message.text.markdown)
  301. await set_welcome(chat_id, raw_text)
  302. await message.reply_text("Welcome message has been successfully set.")
  303. @app.on_message(filters.command("del_welcome") & ~filters.private)
  304. @capture_err
  305. async def del_welcome_func(_, message):
  306. user_id = message.from_user.id
  307. chat_id = message.chat.id
  308. permissions = await member_permissions(chat_id, user_id)
  309. if "can_change_info" not in permissions:
  310. await message.reply_text("You don't have enough permissions.")
  311. return
  312. await del_welcome(chat_id)
  313. await message.reply_text("Welcome message has been deleted.")
  314. @app.on_message(filters.command("get_welcome") & ~filters.private)
  315. @capture_err
  316. async def get_welcome_func(_, message):
  317. user_id = message.from_user.id
  318. chat_id = message.chat.id
  319. permissions = await member_permissions(chat_id, user_id)
  320. if "can_change_info" not in permissions:
  321. await message.reply_text("You don't have enough permissions.")
  322. return
  323. welcome_message = await get_welcome(chat_id)
  324. await message.reply_text(welcome_message)