__init__.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. import re
  23. import time
  24. from inspect import getfullargspec
  25. from os import path
  26. from pathlib import Path
  27. from aiohttp import ClientSession
  28. from motor.motor_asyncio import AsyncIOMotorClient as MongoClient
  29. from pyrogram import Client, filters
  30. from pyrogram.types import Message
  31. from pyromod import listen
  32. from pymongo.errors import ConfigurationError
  33. from Python_ARQ import ARQ
  34. from telegraph import Telegraph
  35. is_config = path.exists("config.py")
  36. if is_config:
  37. from config import *
  38. else:
  39. from sample_config import *
  40. Path("sessions").mkdir(exist_ok=True)
  41. USERBOT_PREFIX = USERBOT_PREFIX
  42. GBAN_LOG_GROUP_ID = GBAN_LOG_GROUP_ID
  43. WELCOME_DELAY_KICK_SEC = WELCOME_DELAY_KICK_SEC
  44. LOG_GROUP_ID = LOG_GROUP_ID
  45. MESSAGE_DUMP_CHAT = MESSAGE_DUMP_CHAT
  46. BOT_PERMISSIONS = globals().get("BOT_PERMISSIONS", {"*"})
  47. MOD_LOAD = [
  48. "admin",
  49. "admin_misc",
  50. "admin_panel",
  51. "admin_web",
  52. "antiservice",
  53. "blacklist",
  54. "blacklist_chat",
  55. "chat_watcher",
  56. "chatbot",
  57. "filters",
  58. "flood",
  59. "giveaway",
  60. "greetings",
  61. "interaction_cleanup",
  62. "karma",
  63. "locks",
  64. "notes",
  65. "points",
  66. "rules",
  67. "teacher_directory",
  68. "technician_services",
  69. ]
  70. MOD_NOLOAD = []
  71. SUDOERS = filters.user()
  72. bot_start_time = time.time()
  73. BOT_SUPERVISOR = None
  74. class TelegramNotConnectedError(RuntimeError):
  75. pass
  76. class UnavailableTelegramClient:
  77. def __getattr__(self, _name):
  78. async def unavailable(*_args, **_kwargs):
  79. raise TelegramNotConnectedError("Telegram Bot 尚未连接。")
  80. return unavailable
  81. class Log:
  82. def __init__(self, save_to_file=False, file_name="wbb.log"):
  83. self.save_to_file = save_to_file
  84. self.file_name = file_name
  85. def info(self, msg):
  86. print(f"[+]: {msg}")
  87. if self.save_to_file:
  88. with open(self.file_name, "a") as f:
  89. f.write(f"[INFO]({time.ctime(time.time())}): {msg}\n")
  90. def error(self, msg):
  91. print(f"[-]: {msg}")
  92. if self.save_to_file:
  93. with open(self.file_name, "a") as f:
  94. f.write(f"[ERROR]({time.ctime(time.time())}): {msg}\n")
  95. profile_slug = re.sub(r"[^A-Za-z0-9_-]", "-", str(BOT_PROFILE_ID))[:48]
  96. log = Log(True, f"bot-{profile_slug}.log" if not ADMIN_BOOTSTRAP_MODE else "admin.log")
  97. # MongoDB client
  98. log.info("Initializing MongoDB client")
  99. mongo_client = MongoClient(MONGO_URL)
  100. try:
  101. control_db = mongo_client.get_default_database()
  102. except ConfigurationError:
  103. control_db = mongo_client.wbb
  104. bot_database_name = os.environ.get("WBB_BOT_DATABASE", "").strip()
  105. db = mongo_client[bot_database_name] if bot_database_name else control_db
  106. aiohttpsession = None
  107. async def initialize():
  108. global aiohttpsession, SUDOERS
  109. aiohttpsession = ClientSession()
  110. log.info("Loading sudoers")
  111. sudoersdb = db.sudoers
  112. sudoers = await sudoersdb.find_one({"sudo": "sudo"})
  113. sudoers = [] if not sudoers else sudoers["sudoers"]
  114. for user_id in SUDO_USERS_ID:
  115. SUDOERS.add(user_id)
  116. if user_id not in sudoers:
  117. sudoers.append(user_id)
  118. await sudoersdb.update_one(
  119. {"sudo": "sudo"},
  120. {"$set": {"sudoers": sudoers}},
  121. upsert=True,
  122. )
  123. if sudoers:
  124. for user_id in sudoers:
  125. SUDOERS.add(user_id)
  126. if ADMIN_BOOTSTRAP_MODE:
  127. app = UnavailableTelegramClient()
  128. app2 = UnavailableTelegramClient()
  129. arq = None
  130. telegraph = None
  131. TELEGRAM_CONNECTED = False
  132. USERBOT_CONNECTED = False
  133. BOT_ID = 0
  134. BOT_NAME = ""
  135. BOT_USERNAME = ""
  136. BOT_MENTION = ""
  137. BOT_DC_ID = 0
  138. USERBOT_ID = 0
  139. USERBOT_NAME = ""
  140. USERBOT_USERNAME = ""
  141. USERBOT_MENTION = ""
  142. USERBOT_DC_ID = 0
  143. else:
  144. if not BOT_TOKEN or API_ID <= 0 or not API_HASH:
  145. raise RuntimeError("Telegram Bot 配置不完整,请先在管理面板中配置。")
  146. loop = asyncio.get_event_loop()
  147. loop.run_until_complete(initialize())
  148. token_owner = str(BOT_TOKEN).split(":", 1)[0]
  149. session_name = f"sessions/wbb-{profile_slug}-{token_owner}"
  150. app = Client(session_name, bot_token=BOT_TOKEN, api_id=API_ID, api_hash=API_HASH)
  151. userbot_session_name = f"sessions/userbot-{profile_slug}"
  152. if SESSION_STRING:
  153. app2 = Client(
  154. userbot_session_name,
  155. api_id=API_ID,
  156. api_hash=API_HASH,
  157. session_string=SESSION_STRING,
  158. )
  159. else:
  160. app2 = Client(
  161. userbot_session_name,
  162. api_id=API_ID,
  163. api_hash=API_HASH,
  164. phone_number=PHONE_NUMBER or None,
  165. in_memory=not USERBOT_ENABLED,
  166. )
  167. arq = ARQ(ARQ_API_URL, ARQ_API_KEY, aiohttpsession)
  168. log.info("Starting bot client")
  169. app.start()
  170. x = app.get_me()
  171. TELEGRAM_CONNECTED = True
  172. BOT_ID = x.id
  173. BOT_NAME = x.first_name + (x.last_name or "")
  174. BOT_USERNAME = x.username
  175. BOT_MENTION = x.mention
  176. BOT_DC_ID = x.dc_id
  177. USERBOT_CONNECTED = False
  178. USERBOT_ID = 0
  179. USERBOT_NAME = "Disabled"
  180. USERBOT_USERNAME = ""
  181. USERBOT_MENTION = ""
  182. USERBOT_DC_ID = 0
  183. if USERBOT_ENABLED:
  184. if not SESSION_STRING and not PHONE_NUMBER:
  185. raise RuntimeError("Userbot 已启用,但未配置 Session String 或手机号。")
  186. log.info("Starting userbot client")
  187. app2.start()
  188. y = app2.get_me()
  189. USERBOT_CONNECTED = True
  190. USERBOT_ID = y.id
  191. USERBOT_NAME = y.first_name + (y.last_name or "")
  192. USERBOT_USERNAME = y.username
  193. USERBOT_MENTION = y.mention
  194. USERBOT_DC_ID = y.dc_id
  195. if USERBOT_ID not in SUDOERS:
  196. SUDOERS.add(USERBOT_ID)
  197. log.info("Initializing Telegraph client")
  198. telegraph = Telegraph(domain="graph.org")
  199. telegraph.create_account(short_name=BOT_USERNAME)
  200. async def eor(msg: Message, **kwargs):
  201. func = (
  202. (msg.edit_text if msg.from_user.is_self else msg.reply)
  203. if msg.from_user
  204. else msg.reply
  205. )
  206. spec = getfullargspec(func.__wrapped__).args
  207. return await func(**{k: v for k, v in kwargs.items() if k in spec})