greetings.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. """
  2. MIT License
  3. Copyright (c) 2023 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 pyrogram import filters
  25. from pyrogram.enums import ChatMemberStatus
  26. from pyrogram.errors.exceptions.bad_request_400 import (
  27. ChatAdminRequired,
  28. UserNotParticipant,
  29. )
  30. from pyrogram.types import (
  31. Chat,
  32. ChatPermissions,
  33. InlineKeyboardButton,
  34. InlineKeyboardMarkup,
  35. Message,
  36. User,
  37. )
  38. from wbb import BOT_USERNAME, SUDOERS, WELCOME_DELAY_KICK_SEC, app
  39. from wbb.core.decorators.errors import capture_err
  40. from wbb.core.decorators.permissions import adminsOnly
  41. from wbb.core.keyboard import ikb
  42. from wbb.modules.notes import extract_urls
  43. from wbb.utils.dbfunctions import (
  44. captcha_off,
  45. captcha_on,
  46. del_welcome,
  47. get_captcha_cache,
  48. get_welcome,
  49. has_solved_captcha_once,
  50. is_captcha_on,
  51. is_gbanned_user,
  52. save_captcha_solved,
  53. set_welcome,
  54. update_captcha_cache,
  55. )
  56. from wbb.utils.filter_groups import welcome_captcha_group
  57. from wbb.utils.functions import (
  58. check_format,
  59. extract_text_and_keyb,
  60. generate_captcha,
  61. )
  62. __MODULE__ = "Greetings"
  63. __HELP__ = """
  64. /captcha [ENABLE|DISABLE] - Enable/Disable captcha.
  65. /set_welcome - Reply this to a message containing correct
  66. format for a welcome message, check end of this message.
  67. /del_welcome - Delete the welcome message.
  68. /get_welcome - Get the welcome message.
  69. **SET_WELCOME ->**
  70. **To set a photo or gif as welcome message. Add your welcome message as caption to the photo or gif. The caption muse be in the format given below.**
  71. For text welcome message just send the text. Then reply with the command
  72. The format should be something like below.
  73. ```
  74. **Hi** {name} Welcome to {chat}
  75. ~ #This separater (~) should be there between text and buttons, remove this comment also
  76. button=[Duck, https://duckduckgo.com]
  77. button2=[Github, https://github.com]
  78. ```
  79. **NOTES ->**
  80. Checkout /markdownhelp to know more about formattings and other syntax.
  81. """
  82. answers_dicc = []
  83. loop = asyncio.get_running_loop()
  84. async def get_initial_captcha_cache():
  85. global answers_dicc
  86. answers_dicc = await get_captcha_cache()
  87. return answers_dicc
  88. loop.create_task(get_initial_captcha_cache())
  89. async def handle_new_member(message: Message, member, chat):
  90. global answers_dicc
  91. # Get cached answers from mongodb in case of bot's been restarted or crashed.
  92. answers_dicc = await get_captcha_cache()
  93. # Mute new member and send message with button
  94. if not await is_captcha_on(message.chat.id):
  95. if member.is_bot:
  96. return
  97. return await send_welcome_message(message.chat, message.from_user.id)
  98. try:
  99. if member.id in SUDOERS:
  100. return # Ignore sudo users
  101. if await is_gbanned_user(member.id):
  102. await message.chat.ban_member(member.id)
  103. await app.send_message(
  104. chat.id,
  105. f"{member.mention} was globally banned, and got removed,"
  106. + " if you think this is a false gban, you can appeal"
  107. + " for this ban in support chat.",
  108. )
  109. return
  110. if member.is_bot:
  111. return # Ignore bots
  112. # Ignore user if he has already solved captcha in this group
  113. # someday
  114. if await has_solved_captcha_once(message.chat.id, member.id):
  115. return
  116. await message.chat.restrict_member(member.id, ChatPermissions())
  117. text = (
  118. f"{(member.mention())} Are you human?\n"
  119. f"Solve this captcha in {WELCOME_DELAY_KICK_SEC} "
  120. "seconds and 4 attempts or you'll be kicked."
  121. )
  122. except ChatAdminRequired:
  123. return
  124. # Generate a captcha image, answers, and some wrong answers
  125. captcha = generate_captcha()
  126. captcha_image = captcha[0]
  127. captcha_answer = captcha[1]
  128. wrong_answers = captcha[2] # This consists of 8 wrong answers
  129. correct_button = InlineKeyboardButton(
  130. f"{captcha_answer}",
  131. callback_data=f"pressed_button {captcha_answer} {member.id}",
  132. )
  133. temp_keyboard_1 = [correct_button] # Button row 1
  134. temp_keyboard_2 = [] # Botton row 2
  135. temp_keyboard_3 = []
  136. for i in range(2):
  137. temp_keyboard_1.append(
  138. InlineKeyboardButton(
  139. f"{wrong_answers[i]}",
  140. callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
  141. )
  142. )
  143. for i in range(2, 5):
  144. temp_keyboard_2.append(
  145. InlineKeyboardButton(
  146. f"{wrong_answers[i]}",
  147. callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
  148. )
  149. )
  150. for i in range(5, 8):
  151. temp_keyboard_3.append(
  152. InlineKeyboardButton(
  153. f"{wrong_answers[i]}",
  154. callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
  155. )
  156. )
  157. shuffle(temp_keyboard_1)
  158. keyboard = [temp_keyboard_1, temp_keyboard_2, temp_keyboard_3]
  159. shuffle(keyboard)
  160. verification_data = {
  161. "chat_id": message.chat.id,
  162. "user_id": member.id,
  163. "answer": captcha_answer,
  164. "keyboard": keyboard,
  165. "attempts": 0,
  166. }
  167. keyboard = InlineKeyboardMarkup(keyboard)
  168. # Append user info, correct answer, and
  169. answers_dicc.append(verification_data)
  170. # keyboard for later use with callback query
  171. button_message = await app.send_photo(
  172. chat_id=chat.id,
  173. photo=captcha_image,
  174. caption=text,
  175. reply_markup=keyboard,
  176. )
  177. os.remove(captcha_image)
  178. # Save captcha answers etc in mongodb in case the bot gets crashed or restarted.
  179. await update_captcha_cache(answers_dicc)
  180. asyncio.create_task(
  181. kick_restricted_after_delay(
  182. WELCOME_DELAY_KICK_SEC, button_message, member
  183. )
  184. )
  185. await asyncio.sleep(0.5)
  186. @app.on_message(filters.new_chat_members, group=welcome_captcha_group)
  187. @capture_err
  188. async def welcome(_, message: Message):
  189. chat = message.chat
  190. members = message.new_chat_members
  191. for member in members:
  192. return await handle_new_member(message, member, chat)
  193. async def send_welcome_message(chat: Chat, user_id: int, delete: bool = False):
  194. welcome, raw_text, file_id = await get_welcome(chat.id)
  195. if not raw_text:
  196. return
  197. text = raw_text
  198. keyb = None
  199. if "~" in raw_text:
  200. text, keyb = extract_text_and_keyb(ikb, raw_text)
  201. if "{chat}" in text:
  202. text = text.replace("{chat}", chat.title)
  203. if "{name}" in text:
  204. text = text.replace("{name}", (await app.get_users(user_id)).mention)
  205. async def _send_wait_delete():
  206. if welcome == "Text":
  207. m = await app.send_message(
  208. chat.id,
  209. text=text,
  210. reply_markup=keyb,
  211. disable_web_page_preview=True,
  212. )
  213. elif welcome == "Photo":
  214. m = await app.send_photo(
  215. chat.id,
  216. photo=file_id,
  217. caption=text,
  218. reply_markup=keyb,
  219. )
  220. else:
  221. m = await app.send_animation(
  222. chat.id,
  223. animation=file_id,
  224. caption=text,
  225. reply_markup=keyb,
  226. )
  227. await asyncio.sleep(300)
  228. await m.delete()
  229. asyncio.create_task(_send_wait_delete())
  230. @app.on_callback_query(filters.regex("pressed_button"))
  231. async def callback_query_welcome_button(_, callback_query):
  232. """After the new member presses the correct button,
  233. set his permissions to chat permissions,
  234. delete button message and join message.
  235. """
  236. global answers_dicc
  237. data = callback_query.data
  238. pressed_user_id = callback_query.from_user.id
  239. pending_user_id = int(data.split(None, 2)[2])
  240. button_message = callback_query.message
  241. answer = data.split(None, 2)[1]
  242. correct_answer = None
  243. keyboard = None
  244. if len(answers_dicc) != 0:
  245. for i in answers_dicc:
  246. if (
  247. i["user_id"] == pending_user_id
  248. and i["chat_id"] == button_message.chat.id
  249. ):
  250. correct_answer = i["answer"]
  251. keyboard = i["keyboard"]
  252. if not (correct_answer and keyboard):
  253. return await callback_query.answer(
  254. "Something went wrong, Rejoin the " "chat!"
  255. )
  256. if pending_user_id != pressed_user_id:
  257. return await callback_query.answer("This is not for you")
  258. if answer != correct_answer:
  259. await callback_query.answer("Yeah, It's Wrong.")
  260. for iii in answers_dicc:
  261. if (
  262. iii["user_id"] == pending_user_id
  263. and iii["chat_id"] == button_message.chat.id
  264. ):
  265. attempts = iii["attempts"]
  266. if attempts >= 3:
  267. answers_dicc.remove(iii)
  268. await button_message.chat.ban_member(pending_user_id)
  269. await asyncio.sleep(1)
  270. await button_message.chat.unban_member(pending_user_id)
  271. await button_message.delete()
  272. return await update_captcha_cache(answers_dicc)
  273. iii["attempts"] += 1
  274. break
  275. shuffle(keyboard[0])
  276. shuffle(keyboard[1])
  277. shuffle(keyboard[2])
  278. shuffle(keyboard)
  279. keyboard = InlineKeyboardMarkup(keyboard)
  280. return await button_message.edit(
  281. text=button_message.caption.markdown,
  282. reply_markup=keyboard,
  283. )
  284. await callback_query.answer("Captcha passed successfully!")
  285. await button_message.chat.unban_member(pending_user_id)
  286. await button_message.delete()
  287. if len(answers_dicc) != 0:
  288. for ii in answers_dicc:
  289. if (
  290. ii["user_id"] == pending_user_id
  291. and ii["chat_id"] == button_message.chat.id
  292. ):
  293. answers_dicc.remove(ii)
  294. await update_captcha_cache(answers_dicc)
  295. chat = callback_query.message.chat
  296. # Save this verification in db, so we don't have to
  297. # send captcha to this user when he joins again.
  298. await save_captcha_solved(chat.id, pending_user_id)
  299. return await send_welcome_message(chat, pending_user_id, True)
  300. async def kick_restricted_after_delay(
  301. delay, button_message: Message, user: User
  302. ):
  303. """If the new member is still restricted after the delay, delete
  304. button message and join message and then kick him
  305. """
  306. global answers_dicc
  307. await asyncio.sleep(delay)
  308. group_chat = button_message.chat
  309. user_id = user.id
  310. await button_message.delete()
  311. if len(answers_dicc) != 0:
  312. for i in answers_dicc:
  313. if i["user_id"] == user_id:
  314. answers_dicc.remove(i)
  315. await update_captcha_cache(answers_dicc)
  316. await _ban_restricted_user_until_date(group_chat, user_id, duration=delay)
  317. async def _ban_restricted_user_until_date(
  318. group_chat, user_id: int, duration: int
  319. ):
  320. try:
  321. member = await group_chat.get_member(user_id)
  322. if member.status == ChatMemberStatus.RESTRICTED:
  323. until_date = int(datetime.utcnow().timestamp() + duration)
  324. await group_chat.ban_member(user_id, until_date=until_date)
  325. except UserNotParticipant:
  326. pass
  327. @app.on_message(filters.command("captcha") & ~filters.private)
  328. @adminsOnly("can_restrict_members")
  329. async def captcha_state(_, message):
  330. usage = "**Usage:**\n/captcha [ENABLE|DISABLE]"
  331. if len(message.command) != 2:
  332. return await message.reply_text(usage)
  333. chat_id = message.chat.id
  334. state = message.text.split(None, 1)[1].strip()
  335. state = state.lower()
  336. if state == "enable":
  337. await captcha_on(chat_id)
  338. await message.reply_text("Enabled Captcha For New Users.")
  339. elif state == "disable":
  340. await captcha_off(chat_id)
  341. await message.reply_text("Disabled Captcha For New Users.")
  342. else:
  343. await message.reply_text(usage)
  344. # WELCOME MESSAGE
  345. @app.on_message(filters.command("set_welcome") & ~filters.private)
  346. @adminsOnly("can_change_info")
  347. async def set_welcome_func(_, message):
  348. usage = "You need to reply to a text, gif or photo to set it as greetings.\n\nNotes: caption required for gif and photo."
  349. key = InlineKeyboardMarkup(
  350. [
  351. [
  352. InlineKeyboardButton(
  353. text="More Help",
  354. url=f"t.me/{BOT_USERNAME}?start=help_greetings",
  355. )
  356. ],
  357. ]
  358. )
  359. replied_message = message.reply_to_message
  360. chat_id = message.chat.id
  361. try:
  362. if not replied_message:
  363. await message.reply_text(usage, reply_markup=key)
  364. return
  365. if replied_message.animation:
  366. welcome = "Animation"
  367. file_id = replied_message.animation.file_id
  368. text = replied_message.caption
  369. if not text:
  370. return await message.reply_text(usage, reply_markup=key)
  371. raw_text = text.markdown
  372. if replied_message.photo:
  373. welcome = "Photo"
  374. file_id = replied_message.photo.file_id
  375. text = replied_message.caption
  376. if not text:
  377. return await message.reply_text(usage, reply_markup=key)
  378. raw_text = text.markdown
  379. if replied_message.text:
  380. welcome = "Text"
  381. file_id = None
  382. text = replied_message.text
  383. raw_text = text.markdown
  384. if replied_message.reply_markup and not "~" in raw_text:
  385. urls = extract_urls(replied_message.reply_markup)
  386. if urls:
  387. response = "\n".join(
  388. [f"{name}=[{text}, {url}]" for name, text, url in urls]
  389. )
  390. raw_text = raw_text + response
  391. raw_text = await check_format(ikb, raw_text)
  392. if raw_text:
  393. await set_welcome(chat_id, welcome, raw_text, file_id)
  394. return await message.reply_text(
  395. "Welcome message has been successfully set."
  396. )
  397. else:
  398. return await message.reply_text(
  399. "Wrong formatting, check the help section.\n\n**Usage:**\nText: `Text`\nText + Buttons: `Text ~ Buttons`",
  400. reply_markup=key,
  401. )
  402. except UnboundLocalError:
  403. return await message.reply_text(
  404. "**Only Text, Gif and Photo welcome message are supported.**"
  405. )
  406. @app.on_message(filters.command("del_welcome") & ~filters.private)
  407. @adminsOnly("can_change_info")
  408. async def del_welcome_func(_, message):
  409. chat_id = message.chat.id
  410. await del_welcome(chat_id)
  411. await message.reply_text("Welcome message has been deleted.")
  412. @app.on_message(filters.command("get_welcome") & ~filters.private)
  413. @adminsOnly("can_change_info")
  414. async def get_welcome_func(_, message):
  415. chat = message.chat
  416. welcome, raw_text, file_id = await get_welcome(chat.id)
  417. if not raw_text:
  418. return await message.reply_text("No welcome message set.")
  419. if not message.from_user:
  420. return await message.reply_text(
  421. "You're anon, can't send welcome message."
  422. )
  423. await send_welcome_message(chat, message.from_user.id)
  424. await message.reply_text(
  425. f'Welcome: {welcome}\n\nFile_id: `{file_id}`\n\n`{raw_text.replace("`", "")}`'
  426. )