greetings.py 17 KB

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