greetings.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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. from datetime import datetime, timedelta
  22. from random import shuffle
  23. from re import findall
  24. from uuid import uuid4
  25. from pyrogram import filters
  26. from pyrogram.enums import ChatMemberStatus
  27. from pyrogram.enums import ChatMemberStatus as CMS
  28. from pyrogram.errors.exceptions.bad_request_400 import (
  29. ChatAdminRequired,
  30. UserNotParticipant,
  31. )
  32. from pyrogram.types import (
  33. Chat,
  34. ChatMemberUpdated,
  35. ChatPermissions,
  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__ = "欢迎语与入群验证"
  67. __HELP__ = """
  68. /captcha [开启|关闭] - 开启或关闭新成员入群验证。
  69. /set_welcome - 回复一条消息,将其设为欢迎语。
  70. /del_welcome - 删除欢迎语。
  71. /get_welcome - 查看当前欢迎语。
  72. **欢迎语设置说明**
  73. 图片或动图欢迎语:把欢迎文字写在媒体说明中,再回复该媒体发送命令。
  74. 纯文字欢迎语:回复文字消息发送命令。
  75. 格式示例:
  76. ```
  77. **你好** {name},欢迎加入 {chat}
  78. ~
  79. button=[查看群规, https://example.com]
  80. ```
  81. 发送 /markdownhelp 可查看更多格式和按钮语法。
  82. """
  83. answers_dicc = []
  84. _captcha_lock = asyncio.Lock()
  85. loop = asyncio.get_running_loop()
  86. async def get_initial_captcha_cache():
  87. global answers_dicc
  88. answers_dicc = await get_captcha_cache()
  89. return answers_dicc
  90. loop.create_task(get_initial_captcha_cache())
  91. async def handle_new_member(member, chat):
  92. global answers_dicc
  93. # Get cached answers from mongodb in case of bot's been restarted or crashed.
  94. answers_dicc = await get_captcha_cache()
  95. # Mute new member and send message with button
  96. try:
  97. if member.id in SUDOERS:
  98. return # Ignore sudo users
  99. fed_id = await get_fed_id(chat.id)
  100. if fed_id:
  101. check_user = await check_banned_user(fed_id, member.id)
  102. if check_user:
  103. reason = check_user["reason"]
  104. date = check_user["date"]
  105. await chat.ban_member(member.id)
  106. return await app.send_message(
  107. chat.id,
  108. f"**成员 {member.mention} 已被联邦封禁。\n\n"
  109. f"原因:{reason}\n时间:{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} 已被全局封禁,因此已从本群移除。",
  116. )
  117. return
  118. if member.is_bot:
  119. return # Ignore bots
  120. if not await is_captcha_on(chat.id):
  121. return await send_welcome_message(
  122. chat, member.id
  123. )
  124. # Ignore user if he has already solved captcha in this group
  125. # someday
  126. if await has_solved_captcha_once(chat.id, member.id):
  127. return
  128. await chat.restrict_member(member.id, ChatPermissions())
  129. text = (
  130. f"{(member.mention())},请完成人机验证。\n"
  131. f"请在 {WELCOME_DELAY_KICK_SEC} 秒内、最多 4 次尝试中选择正确答案,"
  132. "否则你将被移出群组。"
  133. )
  134. except ChatAdminRequired:
  135. return
  136. # Generate a captcha image, answers, and some wrong answers
  137. captcha = generate_captcha()
  138. captcha_image = captcha[0]
  139. captcha_answer = captcha[1]
  140. wrong_answers = captcha[2] # This consists of 8 wrong answers
  141. correct_button = InlineKeyboardButton(
  142. f"{captcha_answer}",
  143. callback_data=f"pressed_button {captcha_answer} {member.id}",
  144. )
  145. temp_keyboard_1 = [correct_button] # Button row 1
  146. temp_keyboard_2 = [] # Botton row 2
  147. temp_keyboard_3 = []
  148. for i in range(2):
  149. temp_keyboard_1.append(
  150. InlineKeyboardButton(
  151. f"{wrong_answers[i]}",
  152. callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
  153. )
  154. )
  155. for i in range(2, 5):
  156. temp_keyboard_2.append(
  157. InlineKeyboardButton(
  158. f"{wrong_answers[i]}",
  159. callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
  160. )
  161. )
  162. for i in range(5, 8):
  163. temp_keyboard_3.append(
  164. InlineKeyboardButton(
  165. f"{wrong_answers[i]}",
  166. callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
  167. )
  168. )
  169. shuffle(temp_keyboard_1)
  170. keyboard = [temp_keyboard_1, temp_keyboard_2, temp_keyboard_3]
  171. shuffle(keyboard)
  172. verification_data = {
  173. "chat_id": chat.id,
  174. "user_id": member.id,
  175. "attempt_id": uuid4().hex,
  176. "answer": captcha_answer,
  177. "keyboard": keyboard,
  178. "attempts": 0,
  179. }
  180. keyboard = InlineKeyboardMarkup(keyboard)
  181. # Append user info, correct answer, and
  182. # keyboard for later use with callback query
  183. button_message = await app.send_photo(
  184. chat_id=chat.id,
  185. photo=captcha_image,
  186. caption=text,
  187. reply_markup=keyboard,
  188. )
  189. # Save captcha answers etc in mongodb in case the bot gets crashed or restarted.
  190. async with _captcha_lock:
  191. answers_dicc = await get_captcha_cache()
  192. answers_dicc.append(verification_data)
  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. verification_data["attempt_id"],
  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, CMS.BANNED}
  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. "验证信息已失效,请退出群组后重新加入。"
  277. )
  278. if pending_user_id != pressed_user_id:
  279. return await callback_query.answer("这不是你的验证。")
  280. if answer != correct_answer:
  281. await callback_query.answer("答案错误,请重试。")
  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. chat = button_message.chat
  307. # Make the old timeout ineligible before changing Telegram permissions.
  308. async with _captcha_lock:
  309. answers_dicc = await get_captcha_cache()
  310. pending = next(
  311. (
  312. item for item in answers_dicc
  313. if item.get("user_id") == pending_user_id
  314. and item.get("chat_id") == chat.id
  315. and item.get("answer") == answer
  316. ),
  317. None,
  318. )
  319. if pending is None:
  320. return await callback_query.answer("验证信息已失效,请退出群组后重新加入。")
  321. await save_captcha_solved(chat.id, pending_user_id)
  322. answers_dicc.remove(pending)
  323. await update_captcha_cache(answers_dicc)
  324. await callback_query.answer("验证通过,欢迎加入。")
  325. await button_message.chat.unban_member(pending_user_id)
  326. await button_message.delete()
  327. return await send_welcome_message(chat, pending_user_id, True)
  328. async def kick_restricted_after_delay(
  329. delay, button_message: Message, user: User, attempt_id: str
  330. ):
  331. """Only expire the still-pending verification that started this timer."""
  332. global answers_dicc
  333. await asyncio.sleep(delay)
  334. group_chat = button_message.chat
  335. user_id = user.id
  336. async with _captcha_lock:
  337. answers_dicc = await get_captcha_cache()
  338. pending = next(
  339. (
  340. item for item in answers_dicc
  341. if item.get("chat_id") == group_chat.id
  342. and item.get("user_id") == user_id
  343. and item.get("attempt_id") == attempt_id
  344. ),
  345. None,
  346. )
  347. if pending is None:
  348. return
  349. answers_dicc.remove(pending)
  350. await update_captcha_cache(answers_dicc)
  351. if await has_solved_captcha_once(group_chat.id, user_id):
  352. return
  353. try:
  354. await button_message.delete()
  355. except Exception:
  356. pass # The message may already have been deleted by another handler.
  357. await _ban_restricted_user_until_date(group_chat, user_id, duration=delay)
  358. async def _ban_restricted_user_until_date(
  359. group_chat, user_id: int, duration: int
  360. ):
  361. try:
  362. member = await group_chat.get_member(user_id)
  363. if member.status == ChatMemberStatus.RESTRICTED:
  364. until_date = (datetime.now() + timedelta(seconds=duration))
  365. await group_chat.ban_member(user_id, until_date=until_date)
  366. except UserNotParticipant:
  367. pass
  368. @app.on_message(filters.command("captcha") & ~filters.private)
  369. @adminsOnly("can_restrict_members")
  370. async def captcha_state(_, message):
  371. usage = "**用法:**\n/captcha [开启|关闭]"
  372. if len(message.command) != 2:
  373. return await message.reply_text(usage)
  374. chat_id = message.chat.id
  375. state = message.text.split(None, 1)[1].strip()
  376. state = state.lower()
  377. state = {
  378. "开启": "enable",
  379. "打开": "enable",
  380. "关闭": "disable",
  381. }.get(state, state)
  382. if state == "enable":
  383. await captcha_on(chat_id)
  384. await message.reply_text("新成员入群验证已开启。")
  385. elif state == "disable":
  386. await captcha_off(chat_id)
  387. await message.reply_text("新成员入群验证已关闭。")
  388. else:
  389. await message.reply_text(usage)
  390. # WELCOME MESSAGE
  391. @app.on_message(filters.command("set_welcome") & ~filters.private)
  392. @adminsOnly("can_change_info")
  393. async def set_welcome_func(_, message):
  394. usage = (
  395. "请回复文字、动图或图片,将其设为欢迎语。\n\n"
  396. "注意:动图和图片必须填写媒体说明。"
  397. )
  398. key = InlineKeyboardMarkup(
  399. [
  400. [
  401. InlineKeyboardButton(
  402. text="查看详细帮助",
  403. url=f"t.me/{BOT_USERNAME}?start=help_greetings",
  404. )
  405. ],
  406. ]
  407. )
  408. replied_message = message.reply_to_message
  409. chat_id = message.chat.id
  410. try:
  411. if not replied_message:
  412. await message.reply_text(usage, reply_markup=key)
  413. return
  414. if replied_message.animation:
  415. welcome = "Animation"
  416. file_id = replied_message.animation.file_id
  417. text = replied_message.caption
  418. if not text:
  419. return await message.reply_text(usage, reply_markup=key)
  420. raw_text = text.markdown
  421. if replied_message.photo:
  422. welcome = "Photo"
  423. file_id = replied_message.photo.file_id
  424. text = replied_message.caption
  425. if not text:
  426. return await message.reply_text(usage, reply_markup=key)
  427. raw_text = text.markdown
  428. if replied_message.text:
  429. welcome = "Text"
  430. file_id = None
  431. text = replied_message.text
  432. raw_text = text.markdown
  433. if replied_message.reply_markup and not findall(r"\[.+\,.+\]", raw_text):
  434. urls = extract_urls(replied_message.reply_markup)
  435. if urls:
  436. response = "\n".join(
  437. [f"{name}=[{text}, {url}]" for name, text, url in urls]
  438. )
  439. raw_text = raw_text + response
  440. raw_text = await check_format(ikb, raw_text)
  441. if raw_text:
  442. await set_welcome(chat_id, welcome, raw_text, file_id)
  443. return await message.reply_text(
  444. "欢迎语已设置。"
  445. )
  446. else:
  447. return await message.reply_text(
  448. "消息格式不正确,请查看帮助。\n\n"
  449. "**用法:**\n纯文字:`文字`\n文字加按钮:`文字 ~ 按钮`",
  450. reply_markup=key,
  451. )
  452. except UnboundLocalError:
  453. return await message.reply_text(
  454. "**欢迎语仅支持文字、动图和图片。**"
  455. )
  456. @app.on_message(filters.command("del_welcome") & ~filters.private)
  457. @adminsOnly("can_change_info")
  458. async def del_welcome_func(_, message):
  459. chat_id = message.chat.id
  460. await del_welcome(chat_id)
  461. await message.reply_text("欢迎语已删除。")
  462. @app.on_message(filters.command("get_welcome") & ~filters.private)
  463. @adminsOnly("can_change_info")
  464. async def get_welcome_func(_, message):
  465. chat = message.chat
  466. welcome, raw_text, file_id = await get_welcome(chat.id)
  467. if not raw_text:
  468. return await message.reply_text("本群尚未设置欢迎语。")
  469. if not message.from_user:
  470. return await message.reply_text(
  471. "匿名管理员无法预览欢迎语。"
  472. )
  473. await send_welcome_message(chat, message.from_user.id)
  474. welcome_label = {
  475. "Text": "文字",
  476. "Photo": "图片",
  477. "Animation": "动图",
  478. }.get(welcome, welcome)
  479. await message.reply_text(
  480. f'欢迎语类型:{welcome_label}\n\n文件标识:`{file_id}`\n\n'
  481. f'`{raw_text.replace("`", "")}`'
  482. )