__init__.py 7.1 KB

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