greetings.py 17 KB

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