Skip to content

Commit

Permalink
🎨 Improved startup tips.
Browse files Browse the repository at this point in the history
  • Loading branch information
AirportR committed Feb 29, 2024
1 parent 1a586f6 commit 051f0d4
Show file tree
Hide file tree
Showing 5 changed files with 105 additions and 67 deletions.
7 changes: 2 additions & 5 deletions botmodule/command/connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,9 @@
from pyrogram import Client

from botmodule.init_bot import config
from botmodule import restart_or_killme, select_export
from botmodule import select_export
from utils import message_delete_queue, safe
from utils.cleaner import ArgCleaner
# from utils.clash import new_batch_start, check_port
from utils.myqueue import bot_put_slave
from glovar import app2

Expand Down Expand Up @@ -116,7 +115,7 @@ async def conn_simple(app: Client, message: Message):


@logger.catch()
async def simple_conn_resp(app: Client, message: Message):
async def simple_conn_resp(_, message: Message):
"""
后端bot专属
"""
Expand All @@ -133,7 +132,6 @@ async def simple_conn_resp(app: Client, message: Message):
config.reload()
logger.info("master连接配置已保存")
await message.reply("已收到master请求,配置已保存,重启生效", quote=True)
await restart_or_killme(app, message)


async def recvtask(app: Client, message: Message):
Expand All @@ -152,7 +150,6 @@ async def recvtask(app: Client, message: Message):
plaindata = await plain_data(message, key)
await message.reply("Get data success!\nplease wait.", quote=True)
putinfo: dict = json.loads(plaindata)
# coreindex = putinfo.get('coreindex', 0)
await bot_put_slave(app, message, putinfo, master_id=master_id)


Expand Down
118 changes: 70 additions & 48 deletions botmodule/init_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,21 @@

from loguru import logger
from utils.cleaner import config
from utils import HOME_DIR

admin = config.getAdmin() # 管理员
config.add_user(admin) # 管理员同时也是用户
config.reload()


def check_permission():
if sys.platform != "win32":
try:
status = os.system(f"chmod +x {clash_path}")
if status != 0:
raise OSError(f"Failed to execute command: chmod +x {clash_path}")
except OSError as o:
print(o)
# def check_permission():
# if sys.platform != "win32":
# try:
# status = os.system(f"chmod +x {clash_path}")
# if status != 0:
# raise OSError(f"Failed to execute command: chmod +x {clash_path}")
# except OSError as o:
# print(o)


def check_args():
Expand Down Expand Up @@ -74,47 +75,70 @@ def check_args():
logger.warning("覆写配置失败!")


class Init:
@staticmethod
def init_emoji():
emoji_source = config.config.get('emoji', {}).get('emoji-source', 'TwemojiLocalSource')
if config.config.get('emoji', {}).get('enable', True) and emoji_source == 'TwemojiLocalSource':
from utils.emoji_custom import TwemojiLocalSource
if not os.path.isdir('./resources/emoji/twemoji'):
twemoji = TwemojiLocalSource()
logger.info("检测到未安装emoji资源包,正在初始化本地emoji...")
asyncio.get_event_loop().run_until_complete(twemoji.download_emoji(proxy=config.get_proxy()))
if twemoji.init_emoji(twemoji.savepath):
logger.info("初始化emoji成功")
else:
logger.warning("初始化emoji失败")

@staticmethod
def init_dir():
dirs = os.listdir(HOME_DIR)
if "logs" in dirs and "results" in dirs:
return
logger.info("检测到初次使用,正在初始化...")
if not os.path.isdir('logs'):
os.mkdir("logs")
logger.info("创建文件夹: logs 用于保存日志")
if not os.path.isdir('results'):
os.mkdir("results")
logger.info("创建文件夹: results 用于保存测试结果")

@staticmethod
def init_permission():
if sys.platform != "win32":
try:
status = os.system(f"chmod +x {CLASH_PATH}")
if status != 0:
raise OSError(f"Failed to execute command: chmod +x {CLASH_PATH}")
except OSError as o:
print(o)

@staticmethod
def init_commit_string():
_latest_version_hash = ""
try:
output = check_output(['git', 'log'], shell=False, encoding="utf-8").strip()
# 解析输出,提取最新提交的哈希值
for line in output.split("\n"):
if "commit" in line:
_latest_version_hash = line.split()[1][:7]
break
except Exception as e:
logger.info(f"可能不是通过git拉取源码,因此version将无法查看提交哈希。{str(e)}")
_latest_version_hash = "Unknown"
return _latest_version_hash


def check_init():
if config.getClashBranch() == 'meta':
logger.info('✅检测到启用clash.meta系内核配置,请自行配置更换成fulltclash-meta代理客户端(默认为原生clash内核)。')
emoji_source = config.config.get('emoji', {}).get('emoji-source', 'TwemojiLocalSource')
if config.config.get('emoji', {}).get('enable', True) and emoji_source == 'TwemojiLocalSource':
from utils.emoji_custom import TwemojiLocalSource
if not os.path.isdir('./resources/emoji/twemoji'):
twemoji = TwemojiLocalSource()
logger.info("检测到未安装emoji资源包,正在初始化本地emoji...")
asyncio.get_event_loop().run_until_complete(twemoji.download_emoji(proxy=config.get_proxy()))
if twemoji.init_emoji(twemoji.savepath):
logger.info("初始化emoji成功")
else:
logger.warning("初始化emoji失败")
dirs = os.listdir()
if "logs" in dirs and "results" in dirs:
return
logger.info("检测到初次使用,正在初始化...")
if not os.path.isdir('logs'):
os.mkdir("logs")
logger.info("创建文件夹: logs 用于保存日志")
if not os.path.isdir('results'):
os.mkdir("results")
logger.info("创建文件夹: results 用于保存测试结果")
check_permission()
logger.info('✅检测到启用clash.meta系内核配置')
Init.init_emoji()
Init.init_dir()
Init.init_permission()


def check_version() -> str:
_latest_version_hash = ""
try:
output = check_output(['git', 'log'], shell=False, encoding="utf-8").strip()
# 解析输出,提取最新提交的哈希值
for line in output.split("\n"):
if "commit" in line:
_latest_version_hash = line.split()[1][:7]
break
except Exception as e0:
logger.info("可能不是通过git拉取源码,因此version将无法查看提交哈希。")
logger.warning(str(e0))
_latest_version_hash = "Unavailable"
return _latest_version_hash
return Init.init_commit_string()


def parse_proxy():
Expand Down Expand Up @@ -154,17 +178,15 @@ def parse_proxy():


# 获取远程仓库的最新提交哈希
latest_version_hash = check_version()
latest_version_hash = Init.init_commit_string()

logger.add("./logs/fulltclash_{time}.log", rotation='7 days')

botconfig = config.getBotconfig()
api_id = botconfig.get('api_id', None)
api_hash = botconfig.get('api_hash', None)
bot_token = botconfig.get('bot_token', None)
clash_path = config.get_clash_path() # 为代理客户端运行路径
# clash_work_path = config.get_clash_work_path() # clash工作路径
corenum = min(config.config.get('clash', {}).get('core', 1), 128)
CLASH_PATH = config.get_clash_path() # 为代理客户端运行路径

USER_TARGET = config.getuser() # 这是用户列表,从配置文件读取
logger.info("管理员名单加载:" + str(admin))
Expand Down
2 changes: 0 additions & 2 deletions glovar.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os
import time

import tzlocal
Expand All @@ -17,7 +16,6 @@
bot_config = init_bot.config
BUILD_TOKEN = init_bot.config.getBuildToken()
userbot_config = bot_config.config.get('userbot', {})
HOME_DIR = os.getcwd()

# 客户端
app = Client("my_bot",
Expand Down
31 changes: 21 additions & 10 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import sys
from sqlite3 import OperationalError

from utils import bot
from glovar import app as app1, bot_info, app2
from pyrogram import idle
Expand All @@ -8,16 +11,24 @@

# app1 is bot,app2 is user bot.
def start():
app1.start()
bot.loader(app1)
if app2 is not None:
app2.start()
bot.user_loder(app2)
bot_info(app1, app2)
idle()
app1.stop()
if app2 is not None:
app2.stop()
try:
app1.start()
bot.loader(app1)
if app2 is not None:
app2.start()
bot.user_loder(app2)
bot_info(app1, app2)
idle()
app1.stop()
if app2 is not None:
app2.stop()
except OperationalError as err:
if str(err) == "database is locked":
print(f"Bot的会话数据库已被锁定,这可能是之前启动时出现了错误,"
f"尝试删除当前文件夹下的 {app1.name}.session 与 {app1.name}.session-journal 文件")
sys.exit()
else:
raise


if __name__ == "__main__":
Expand Down
14 changes: 12 additions & 2 deletions utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
from os import getcwd
import aiohttp

from utils.cron import *
from typing import Callable, Any, Union, Coroutine

__version__ = "3.6.7" # 项目版本号
__all__ = ["cron_delete_message", "cron_edit_message", "message_delete_queue", "message_edit_queue", "__version__",
"retry", "script_demo"]
HOME_DIR = getcwd()
__all__ = [
"cron_delete_message",
"cron_edit_message",
"message_delete_queue",
"message_edit_queue",
"__version__",
"retry",
"script_demo",
"HOME_DIR"
]


def default_breakfunc(ret_val: bool) -> bool:
Expand Down

0 comments on commit 051f0d4

Please sign in to comment.