""" 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 import os import re import time from inspect import getfullargspec from os import path from pathlib import Path from aiohttp import ClientSession from motor.motor_asyncio import AsyncIOMotorClient as MongoClient from pyrogram import Client, filters from pyrogram.types import Message from pyromod import listen from pymongo.errors import ConfigurationError from Python_ARQ import ARQ from telegraph import Telegraph is_config = path.exists("config.py") if is_config: from config import * else: from sample_config import * Path("sessions").mkdir(exist_ok=True) USERBOT_PREFIX = USERBOT_PREFIX GBAN_LOG_GROUP_ID = GBAN_LOG_GROUP_ID WELCOME_DELAY_KICK_SEC = WELCOME_DELAY_KICK_SEC LOG_GROUP_ID = LOG_GROUP_ID MESSAGE_DUMP_CHAT = MESSAGE_DUMP_CHAT BOT_PERMISSIONS = globals().get("BOT_PERMISSIONS", {"*"}) MOD_LOAD = [ "admin", "admin_misc", "admin_panel", "admin_web", "antiservice", "blacklist", "blacklist_chat", "business_assistant", "channels", "chat_watcher", "chatbot", "filters", "flood", "giveaway", "greetings", "interaction_cleanup", "karma", "locks", "notes", "points", "rules", "teacher_directory", "technician_services", ] MOD_NOLOAD = [] SUDOERS = filters.user() bot_start_time = time.time() BOT_SUPERVISOR = None class TelegramNotConnectedError(RuntimeError): pass class UnavailableTelegramClient: def __getattr__(self, _name): async def unavailable(*_args, **_kwargs): raise TelegramNotConnectedError("Telegram Bot 尚未连接。") return unavailable class Log: def __init__(self, save_to_file=False, file_name="wbb.log"): self.save_to_file = save_to_file self.file_name = file_name def info(self, msg): print(f"[+]: {msg}") if self.save_to_file: with open(self.file_name, "a") as f: f.write(f"[INFO]({time.ctime(time.time())}): {msg}\n") def error(self, msg): print(f"[-]: {msg}") if self.save_to_file: with open(self.file_name, "a") as f: f.write(f"[ERROR]({time.ctime(time.time())}): {msg}\n") profile_slug = re.sub(r"[^A-Za-z0-9_-]", "-", str(BOT_PROFILE_ID))[:48] log = Log(True, f"bot-{profile_slug}.log" if not ADMIN_BOOTSTRAP_MODE else "admin.log") # MongoDB client log.info("Initializing MongoDB client") mongo_client = MongoClient(MONGO_URL) try: control_db = mongo_client.get_default_database() except ConfigurationError: control_db = mongo_client.wbb bot_database_name = os.environ.get("WBB_BOT_DATABASE", "").strip() db = mongo_client[bot_database_name] if bot_database_name else control_db aiohttpsession = None async def initialize(): global aiohttpsession, SUDOERS aiohttpsession = ClientSession() log.info("Loading sudoers") sudoersdb = db.sudoers sudoers = await sudoersdb.find_one({"sudo": "sudo"}) sudoers = [] if not sudoers else sudoers["sudoers"] for user_id in SUDO_USERS_ID: SUDOERS.add(user_id) if user_id not in sudoers: sudoers.append(user_id) await sudoersdb.update_one( {"sudo": "sudo"}, {"$set": {"sudoers": sudoers}}, upsert=True, ) if sudoers: for user_id in sudoers: SUDOERS.add(user_id) if ADMIN_BOOTSTRAP_MODE: app = UnavailableTelegramClient() app2 = UnavailableTelegramClient() arq = None telegraph = None TELEGRAM_CONNECTED = False USERBOT_CONNECTED = False BOT_ID = 0 BOT_NAME = "" BOT_USERNAME = "" BOT_MENTION = "" BOT_DC_ID = 0 USERBOT_ID = 0 USERBOT_NAME = "" USERBOT_USERNAME = "" USERBOT_MENTION = "" USERBOT_DC_ID = 0 else: if not BOT_TOKEN or API_ID <= 0 or not API_HASH: raise RuntimeError("Telegram Bot 配置不完整,请先在管理面板中配置。") loop = asyncio.get_event_loop() loop.run_until_complete(initialize()) token_owner = str(BOT_TOKEN).split(":", 1)[0] session_name = f"sessions/wbb-{profile_slug}-{token_owner}" app = Client(session_name, bot_token=BOT_TOKEN, api_id=API_ID, api_hash=API_HASH) userbot_session_name = f"sessions/userbot-{profile_slug}" if SESSION_STRING: app2 = Client( userbot_session_name, api_id=API_ID, api_hash=API_HASH, session_string=SESSION_STRING, ) else: app2 = Client( userbot_session_name, api_id=API_ID, api_hash=API_HASH, phone_number=PHONE_NUMBER or None, in_memory=not USERBOT_ENABLED, ) arq = ARQ(ARQ_API_URL, ARQ_API_KEY, aiohttpsession) log.info("Starting bot client") app.start() x = app.get_me() TELEGRAM_CONNECTED = True BOT_ID = x.id BOT_NAME = x.first_name + (x.last_name or "") BOT_USERNAME = x.username BOT_MENTION = x.mention BOT_DC_ID = x.dc_id USERBOT_CONNECTED = False USERBOT_ID = 0 USERBOT_NAME = "Disabled" USERBOT_USERNAME = "" USERBOT_MENTION = "" USERBOT_DC_ID = 0 if USERBOT_ENABLED: if not SESSION_STRING and not PHONE_NUMBER: raise RuntimeError("Userbot 已启用,但未配置 Session String 或手机号。") log.info("Starting userbot client") app2.start() y = app2.get_me() USERBOT_CONNECTED = True USERBOT_ID = y.id USERBOT_NAME = y.first_name + (y.last_name or "") USERBOT_USERNAME = y.username USERBOT_MENTION = y.mention USERBOT_DC_ID = y.dc_id if USERBOT_ID not in SUDOERS: SUDOERS.add(USERBOT_ID) log.info("Initializing Telegraph client") telegraph = Telegraph(domain="graph.org") telegraph.create_account(short_name=BOT_USERNAME) async def eor(msg: Message, **kwargs): func = ( (msg.edit_text if msg.from_user.is_self else msg.reply) if msg.from_user else msg.reply ) spec = getfullargspec(func.__wrapped__).args return await func(**{k: v for k, v in kwargs.items() if k in spec})