__init__.py 7.0 KB

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