| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552 |
- """
- MIT License
- Copyright (c) 2024 TheHamkerCat
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in all
- copies or substantial portions of the Software.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- SOFTWARE.
- """
- import asyncio
- from datetime import datetime, timedelta
- from random import shuffle
- from re import findall
- from uuid import uuid4
- from pyrogram import filters
- from pyrogram.enums import ChatMemberStatus
- from pyrogram.enums import ChatMemberStatus as CMS
- from pyrogram.errors.exceptions.bad_request_400 import (
- ChatAdminRequired,
- UserNotParticipant,
- )
- from pyrogram.types import (
- Chat,
- ChatMemberUpdated,
- ChatPermissions,
- InlineKeyboardButton,
- InlineKeyboardMarkup,
- Message,
- User,
- )
- from wbb import BOT_USERNAME, SUDOERS, WELCOME_DELAY_KICK_SEC, app
- from wbb.core.decorators.errors import capture_err
- from wbb.core.decorators.permissions import adminsOnly
- from wbb.core.keyboard import ikb
- from wbb.modules.notes import extract_urls
- from wbb.utils.dbfeds import check_banned_user, get_fed_id
- from wbb.utils.dbfunctions import (
- captcha_off,
- captcha_on,
- del_welcome,
- get_captcha_cache,
- get_welcome,
- has_solved_captcha_once,
- is_captcha_on,
- is_gbanned_user,
- save_captcha_solved,
- set_welcome,
- update_captcha_cache,
- )
- from wbb.utils.filter_groups import welcome_captcha_group
- from wbb.utils.functions import (
- check_format,
- extract_text_and_keyb,
- generate_captcha,
- )
- __MODULE__ = "欢迎语与入群验证"
- __HELP__ = """
- /captcha [开启|关闭] - 开启或关闭新成员入群验证。
- /set_welcome - 回复一条消息,将其设为欢迎语。
- /del_welcome - 删除欢迎语。
- /get_welcome - 查看当前欢迎语。
- **欢迎语设置说明**
- 图片或动图欢迎语:把欢迎文字写在媒体说明中,再回复该媒体发送命令。
- 纯文字欢迎语:回复文字消息发送命令。
- 格式示例:
- ```
- **你好** {name},欢迎加入 {chat}
- ~
- button=[查看群规, https://example.com]
- ```
- 发送 /markdownhelp 可查看更多格式和按钮语法。
- """
- answers_dicc = []
- _captcha_lock = asyncio.Lock()
- loop = asyncio.get_running_loop()
- async def get_initial_captcha_cache():
- global answers_dicc
- answers_dicc = await get_captcha_cache()
- return answers_dicc
- loop.create_task(get_initial_captcha_cache())
- async def handle_new_member(member, chat):
- global answers_dicc
- # Get cached answers from mongodb in case of bot's been restarted or crashed.
- answers_dicc = await get_captcha_cache()
- # Mute new member and send message with button
- try:
- if member.id in SUDOERS:
- return # Ignore sudo users
- fed_id = await get_fed_id(chat.id)
- if fed_id:
- check_user = await check_banned_user(fed_id, member.id)
- if check_user:
- reason = check_user["reason"]
- date = check_user["date"]
- await chat.ban_member(member.id)
- return await app.send_message(
- chat.id,
- f"**成员 {member.mention} 已被联邦封禁。\n\n"
- f"原因:{reason}\n时间:{date}**",
- )
- if await is_gbanned_user(member.id):
- await chat.ban_member(member.id)
- await app.send_message(
- chat.id,
- f"{member.mention} 已被全局封禁,因此已从本群移除。",
- )
- return
- if member.is_bot:
- return # Ignore bots
- if not await is_captcha_on(chat.id):
- return await send_welcome_message(
- chat, member.id
- )
- # Ignore user if he has already solved captcha in this group
- # someday
- if await has_solved_captcha_once(chat.id, member.id):
- return
- await chat.restrict_member(member.id, ChatPermissions())
- text = (
- f"{(member.mention())},请完成人机验证。\n"
- f"请在 {WELCOME_DELAY_KICK_SEC} 秒内、最多 4 次尝试中选择正确答案,"
- "否则你将被移出群组。"
- )
- except ChatAdminRequired:
- return
- # Generate a captcha image, answers, and some wrong answers
- captcha = generate_captcha()
- captcha_image = captcha[0]
- captcha_answer = captcha[1]
- wrong_answers = captcha[2] # This consists of 8 wrong answers
- correct_button = InlineKeyboardButton(
- f"{captcha_answer}",
- callback_data=f"pressed_button {captcha_answer} {member.id}",
- )
- temp_keyboard_1 = [correct_button] # Button row 1
- temp_keyboard_2 = [] # Botton row 2
- temp_keyboard_3 = []
- for i in range(2):
- temp_keyboard_1.append(
- InlineKeyboardButton(
- f"{wrong_answers[i]}",
- callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
- )
- )
- for i in range(2, 5):
- temp_keyboard_2.append(
- InlineKeyboardButton(
- f"{wrong_answers[i]}",
- callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
- )
- )
- for i in range(5, 8):
- temp_keyboard_3.append(
- InlineKeyboardButton(
- f"{wrong_answers[i]}",
- callback_data=f"pressed_button {wrong_answers[i]} {member.id}",
- )
- )
- shuffle(temp_keyboard_1)
- keyboard = [temp_keyboard_1, temp_keyboard_2, temp_keyboard_3]
- shuffle(keyboard)
- verification_data = {
- "chat_id": chat.id,
- "user_id": member.id,
- "attempt_id": uuid4().hex,
- "answer": captcha_answer,
- "keyboard": keyboard,
- "attempts": 0,
- }
- keyboard = InlineKeyboardMarkup(keyboard)
- # Append user info, correct answer, and
- # keyboard for later use with callback query
- button_message = await app.send_photo(
- chat_id=chat.id,
- photo=captcha_image,
- caption=text,
- reply_markup=keyboard,
- )
- # Save captcha answers etc in mongodb in case the bot gets crashed or restarted.
- async with _captcha_lock:
- answers_dicc = await get_captcha_cache()
- answers_dicc.append(verification_data)
- await update_captcha_cache(answers_dicc)
- asyncio.create_task(
- kick_restricted_after_delay(
- WELCOME_DELAY_KICK_SEC, button_message, member,
- verification_data["attempt_id"],
- )
- )
- await asyncio.sleep(0.5)
- @app.on_chat_member_updated(filters.group, group=welcome_captcha_group)
- @capture_err
- async def welcome(_, user: ChatMemberUpdated):
- if not (
- user.new_chat_member
- and user.new_chat_member.status not in {CMS.RESTRICTED, CMS.BANNED}
- and not user.old_chat_member
- ):
- return
- member = user.new_chat_member.user if user.new_chat_member else user.from_user
- chat = user.chat
- return await handle_new_member(member, chat)
- async def send_welcome_message(chat: Chat, user_id: int, delete: bool = False):
- welcome, raw_text, file_id = await get_welcome(chat.id)
- if not raw_text:
- return
- text = raw_text
- keyb = None
- if findall(r"\[.+\,.+\]", raw_text):
- text, keyb = extract_text_and_keyb(ikb, raw_text)
- if "{chat}" in text:
- text = text.replace("{chat}", chat.title)
- if "{name}" in text:
- text = text.replace("{name}", (await app.get_users(user_id)).mention)
- if "{id}" in text:
- text = text.replace("{id}", f"`{user_id}`")
- async def _send_wait_delete():
- if welcome == "Text":
- m = await app.send_message(
- chat.id,
- text=text,
- reply_markup=keyb,
- disable_web_page_preview=True,
- )
- elif welcome == "Photo":
- m = await app.send_photo(
- chat.id,
- photo=file_id,
- caption=text,
- reply_markup=keyb,
- )
- else:
- m = await app.send_animation(
- chat.id,
- animation=file_id,
- caption=text,
- reply_markup=keyb,
- )
- await asyncio.sleep(300)
- await m.delete()
- asyncio.create_task(_send_wait_delete())
- @app.on_callback_query(filters.regex("pressed_button"))
- async def callback_query_welcome_button(_, callback_query):
- """After the new member presses the correct button,
- set his permissions to chat permissions,
- delete button message and join message.
- """
- global answers_dicc
- data = callback_query.data
- pressed_user_id = callback_query.from_user.id
- pending_user_id = int(data.split(None, 2)[2])
- button_message = callback_query.message
- answer = data.split(None, 2)[1]
- correct_answer = None
- keyboard = None
- if len(answers_dicc) != 0:
- for i in answers_dicc:
- if (
- i["user_id"] == pending_user_id
- and i["chat_id"] == button_message.chat.id
- ):
- correct_answer = i["answer"]
- keyboard = i["keyboard"]
- if not (correct_answer and keyboard):
- return await callback_query.answer(
- "验证信息已失效,请退出群组后重新加入。"
- )
- if pending_user_id != pressed_user_id:
- return await callback_query.answer("这不是你的验证。")
- if answer != correct_answer:
- await callback_query.answer("答案错误,请重试。")
- for iii in answers_dicc:
- if (
- iii["user_id"] == pending_user_id
- and iii["chat_id"] == button_message.chat.id
- ):
- attempts = iii["attempts"]
- if attempts >= 3:
- answers_dicc.remove(iii)
- await button_message.chat.ban_member(pending_user_id)
- await asyncio.sleep(1)
- await button_message.chat.unban_member(pending_user_id)
- await button_message.delete()
- return await update_captcha_cache(answers_dicc)
- iii["attempts"] += 1
- break
- shuffle(keyboard[0])
- shuffle(keyboard[1])
- shuffle(keyboard[2])
- shuffle(keyboard)
- keyboard = InlineKeyboardMarkup(keyboard)
- return await button_message.edit(
- text=button_message.caption.markdown,
- reply_markup=keyboard,
- )
- chat = button_message.chat
- # Make the old timeout ineligible before changing Telegram permissions.
- async with _captcha_lock:
- answers_dicc = await get_captcha_cache()
- pending = next(
- (
- item for item in answers_dicc
- if item.get("user_id") == pending_user_id
- and item.get("chat_id") == chat.id
- and item.get("answer") == answer
- ),
- None,
- )
- if pending is None:
- return await callback_query.answer("验证信息已失效,请退出群组后重新加入。")
- await save_captcha_solved(chat.id, pending_user_id)
- answers_dicc.remove(pending)
- await update_captcha_cache(answers_dicc)
- await callback_query.answer("验证通过,欢迎加入。")
- await button_message.chat.unban_member(pending_user_id)
- await button_message.delete()
- return await send_welcome_message(chat, pending_user_id, True)
- async def kick_restricted_after_delay(
- delay, button_message: Message, user: User, attempt_id: str
- ):
- """Only expire the still-pending verification that started this timer."""
- global answers_dicc
- await asyncio.sleep(delay)
- group_chat = button_message.chat
- user_id = user.id
- async with _captcha_lock:
- answers_dicc = await get_captcha_cache()
- pending = next(
- (
- item for item in answers_dicc
- if item.get("chat_id") == group_chat.id
- and item.get("user_id") == user_id
- and item.get("attempt_id") == attempt_id
- ),
- None,
- )
- if pending is None:
- return
- answers_dicc.remove(pending)
- await update_captcha_cache(answers_dicc)
- if await has_solved_captcha_once(group_chat.id, user_id):
- return
- try:
- await button_message.delete()
- except Exception:
- pass # The message may already have been deleted by another handler.
- await _ban_restricted_user_until_date(group_chat, user_id, duration=delay)
- async def _ban_restricted_user_until_date(
- group_chat, user_id: int, duration: int
- ):
- try:
- member = await group_chat.get_member(user_id)
- if member.status == ChatMemberStatus.RESTRICTED:
- until_date = (datetime.now() + timedelta(seconds=duration))
- await group_chat.ban_member(user_id, until_date=until_date)
- except UserNotParticipant:
- pass
- @app.on_message(filters.command("captcha") & ~filters.private)
- @adminsOnly("can_restrict_members")
- async def captcha_state(_, message):
- usage = "**用法:**\n/captcha [开启|关闭]"
- if len(message.command) != 2:
- return await message.reply_text(usage)
- chat_id = message.chat.id
- state = message.text.split(None, 1)[1].strip()
- state = state.lower()
- state = {
- "开启": "enable",
- "打开": "enable",
- "关闭": "disable",
- }.get(state, state)
- if state == "enable":
- await captcha_on(chat_id)
- await message.reply_text("新成员入群验证已开启。")
- elif state == "disable":
- await captcha_off(chat_id)
- await message.reply_text("新成员入群验证已关闭。")
- else:
- await message.reply_text(usage)
- # WELCOME MESSAGE
- @app.on_message(filters.command("set_welcome") & ~filters.private)
- @adminsOnly("can_change_info")
- async def set_welcome_func(_, message):
- usage = (
- "请回复文字、动图或图片,将其设为欢迎语。\n\n"
- "注意:动图和图片必须填写媒体说明。"
- )
- key = InlineKeyboardMarkup(
- [
- [
- InlineKeyboardButton(
- text="查看详细帮助",
- url=f"t.me/{BOT_USERNAME}?start=help_greetings",
- )
- ],
- ]
- )
- replied_message = message.reply_to_message
- chat_id = message.chat.id
- try:
- if not replied_message:
- await message.reply_text(usage, reply_markup=key)
- return
- if replied_message.animation:
- welcome = "Animation"
- file_id = replied_message.animation.file_id
- text = replied_message.caption
- if not text:
- return await message.reply_text(usage, reply_markup=key)
- raw_text = text.markdown
- if replied_message.photo:
- welcome = "Photo"
- file_id = replied_message.photo.file_id
- text = replied_message.caption
- if not text:
- return await message.reply_text(usage, reply_markup=key)
- raw_text = text.markdown
- if replied_message.text:
- welcome = "Text"
- file_id = None
- text = replied_message.text
- raw_text = text.markdown
- if replied_message.reply_markup and not findall(r"\[.+\,.+\]", raw_text):
- urls = extract_urls(replied_message.reply_markup)
- if urls:
- response = "\n".join(
- [f"{name}=[{text}, {url}]" for name, text, url in urls]
- )
- raw_text = raw_text + response
- raw_text = await check_format(ikb, raw_text)
- if raw_text:
- await set_welcome(chat_id, welcome, raw_text, file_id)
- return await message.reply_text(
- "欢迎语已设置。"
- )
- else:
- return await message.reply_text(
- "消息格式不正确,请查看帮助。\n\n"
- "**用法:**\n纯文字:`文字`\n文字加按钮:`文字 ~ 按钮`",
- reply_markup=key,
- )
- except UnboundLocalError:
- return await message.reply_text(
- "**欢迎语仅支持文字、动图和图片。**"
- )
- @app.on_message(filters.command("del_welcome") & ~filters.private)
- @adminsOnly("can_change_info")
- async def del_welcome_func(_, message):
- chat_id = message.chat.id
- await del_welcome(chat_id)
- await message.reply_text("欢迎语已删除。")
- @app.on_message(filters.command("get_welcome") & ~filters.private)
- @adminsOnly("can_change_info")
- async def get_welcome_func(_, message):
- chat = message.chat
- welcome, raw_text, file_id = await get_welcome(chat.id)
- if not raw_text:
- return await message.reply_text("本群尚未设置欢迎语。")
- if not message.from_user:
- return await message.reply_text(
- "匿名管理员无法预览欢迎语。"
- )
- await send_welcome_message(chat, message.from_user.id)
- welcome_label = {
- "Text": "文字",
- "Photo": "图片",
- "Animation": "动图",
- }.get(welcome, welcome)
- await message.reply_text(
- f'欢迎语类型:{welcome_label}\n\n文件标识:`{file_id}`\n\n'
- f'`{raw_text.replace("`", "")}`'
- )
|