From 751402d5c635c127a93e6ee45b9ad0fbe2e45ca5 Mon Sep 17 00:00:00 2001 From: shenjack <3695888@qq.com> Date: Fri, 2 Aug 2024 19:03:58 +0800 Subject: [PATCH] remove ica-py --- ica-py/connect.py | 161 ------------------------------------ ica-py/data_struct.py | 102 ----------------------- ica-py/main.py | 36 -------- ica-py/plugins/bmcl.py | 98 ---------------------- ica-py/plugins/safe_eval.py | 72 ---------------- ica-py/requirements.txt | 7 -- ica-py/router.py | 62 -------------- 7 files changed, 538 deletions(-) delete mode 100644 ica-py/connect.py delete mode 100644 ica-py/data_struct.py delete mode 100644 ica-py/main.py delete mode 100644 ica-py/plugins/bmcl.py delete mode 100644 ica-py/plugins/safe_eval.py delete mode 100644 ica-py/requirements.txt delete mode 100644 ica-py/router.py diff --git a/ica-py/connect.py b/ica-py/connect.py deleted file mode 100644 index 3e4ac16..0000000 --- a/ica-py/connect.py +++ /dev/null @@ -1,161 +0,0 @@ -import time -import json -import random -import asyncio -import argparse -import traceback - -from typing import Dict, List, Tuple, Any - -import socketio -from colorama import Fore -from nacl.signing import SigningKey - -from lib_not_dr.loggers import config - -from data_struct import SendMessage, ReplyMessage, get_config, BotConfig, BotStatus -from main import BOTCONFIG, _version_ -from router import route - -logger = config.get_logger("icalingua") - -sio: socketio.AsyncClient = socketio.AsyncClient() - - -@sio.on("connect") # type: ignore -def connect(): - logger.info(f"{Fore.GREEN}icalingua 已连接") - - -@sio.on("requireAuth") # type: ignore -async def require_auth(salt: str, versions: Dict[str, str]): - logger.info(f"{Fore.BLUE}versions: {versions}\n{type(salt)}|{salt=}") - # 准备数据 - sign = SigningKey(bytes.fromhex(BOTCONFIG.private_key)) - signature = sign.sign(bytes.fromhex(salt)) - - # 发送数据 - await sio.emit("auth", signature.signature) - logger.info(f"{Fore.BLUE}send auth emit") - - -@sio.on("auth") # type: ignore -def auth(data: Dict[str, Any]): - logger.info(f"auth: {data}") - - -@sio.on("authFailed") # type: ignore -async def auth_failed(): - logger.info(f"{Fore.RED}authFailed") - await sio.disconnect() - - -@sio.on("authSucceed") # type: ignore -def auth_succeed(): - logger.info(f"{Fore.GREEN}authSucceed") - - -@sio.on("connect_error") # type: ignore -def connect_error(*args, **kwargs): - logger.info(f"连接错误 {args}, {kwargs}") - - -@sio.on("updateRoom") # type: ignore -def update_room(data: Dict[str, Any]): - logger.info(f"{Fore.CYAN}update_room: {data}") - - -@sio.on("addMessage") # type: ignore -async def add_message(data: Dict[str, Any]): - logger.info(f"{Fore.MAGENTA}add_message: {data}") - - is_self = data["message"]["senderId"] == BOTCONFIG.self_id - - if not is_self: - await route(data, sio) - - -@sio.on("deleteMessage") # type: ignore -def delete_message(message_id: str): - logger.info(f"{Fore.MAGENTA}delete_message: {message_id}") - - -@sio.on("setMessages") # type: ignore -def set_messages(data: Dict[str, Any]): - logger.info( - f"{Fore.YELLOW}set_messages: {data}\nmessage_len: {len(data['messages'])}" - ) - - -async def notice_startup(room_list: List[int]): - for notice_room in BOTCONFIG.notice_room: - if notice_room in room_list: - notice_message = SendMessage( - content=f"ica bot v{_version_}", room_id=notice_room - ) - await sio.emit("sendMessage", notice_message.to_json()) - BotStatus.inited = True - logger.info("inited", tag="notice room") - else: - logger.warn(f"未找到通知房间: {notice_room}", tag="notice room") - await asyncio.sleep(random.randint(2, 5)) - - -@sio.on("setAllRooms") # type: ignore -async def set_all_rooms(rooms: List[Dict[str, Any]]): - BotStatus.running = True - room_list: List[int] = [room.get("roomId") for room in rooms] # type: ignore - if not BotStatus.inited: - logger.info("initing...", tag="setAllRooms") - logger.debug(f"room_list: {room_list}", tag="setAllRooms") - if BOTCONFIG.notice_start: - await notice_startup(room_list) - if room_list != BotStatus.rooms: - logger.info(f"{Fore.YELLOW}set_all_rooms: {rooms}\nlen: {len(rooms)}\n") - BotStatus.rooms = room_list - logger.info(f"更新房间: {room_list}", tag="setAllRooms") - - -@sio.on("setAllChatGroups") # type: ignore -def set_all_chat_groups(groups: List[Dict[str, Any]]): - logger.info(f"{Fore.YELLOW}set_all_chat_groups: {groups}\nlen: {len(groups)}\n") - - -@sio.on("notify") # type: ignore -def notify(data: List[Tuple[str, Any]]): - logger.info(f"notify: {data}") - - -@sio.on("closeLoading") # type: ignore -def close_loading(_): - logger.info(f"{Fore.GREEN}close_loading") - - -@sio.on("onlineData") # type: ignore -def online_data(data: Dict[str, Any]): - logger.info(f"{Fore.GREEN}online_data: {data}") - - -@sio.on("*") # type: ignore -def catch_all(event, data): - logger.info(f"{Fore.RED}catch_all: {event}|{data}") - - -async def main(): - """ - while True: - await self.eio.wait() - await self.sleep(1) # give the reconnect task time to start up - if not self._reconnect_task: - break - await self._reconnect_task - if self.eio.state != 'connected': - break - """ - try: - await sio.connect(BOTCONFIG.host) - await sio.wait() - except KeyboardInterrupt: - logger.info("KeyboardInterrupt") - except Exception: - logger.error(traceback.format_exc()) diff --git a/ica-py/data_struct.py b/ica-py/data_struct.py deleted file mode 100644 index 56d74d0..0000000 --- a/ica-py/data_struct.py +++ /dev/null @@ -1,102 +0,0 @@ -from typing import List, Optional, Union, Literal, Tuple - -import qtoml -from lib_not_dr.types import Options - - -class AtElement(Options): - text: str - id: Union[int, Literal['all']] = 'all' - - -class ReplyMessage(Options): - id: str - username: str = '' - content: str = '' - files: list = [] - - def to_json(self) -> dict: - return { - '_id': self.id, - 'username': self.username, - 'content': self.content, - 'files': self.files - } - - -class SendMessage(Options): - content: str - room_id: Optional[int] = None - room: Optional[int] = None # room id 和 room 二选一 ( 实际上直接填 room id 就行了 ) - file: None = None # TODO: 上传文件 - reply_to: Optional[ReplyMessage] = None # 源码 给了一个 any TODO: 回复消息 - b64_img: Optional[str] = None # TODO: 发送图片 - at: Optional[List[AtElement]] = [] # TODO: @某人 - sticker: Optional[None] = None # TODO: 发送表情 - message_type: Optional[str] = None # TODO: 消息类型 - - def to_json(self) -> dict: - return { - 'content': self.content, - 'roomId': self.room_id, - 'room': self.room, - 'file': self.file, - 'replyMessage': self.reply_to.to_json() if self.reply_to else None, - 'b64img': self.b64_img, - 'at': self.at, - 'sticker': self.sticker, - 'messageType': self.message_type - } - - def to_content(self, content: str) -> "SendMessage": - self.content = content - return self - - -class NewMessage(Options): - sender_id: int - sender_name: str - room_id: int - content: str - msg_id: str - data: dict - - def init(self, **kwargs) -> None: - data = kwargs.pop('data') - - self.sender_name = data["message"]["username"] - self.sender_id = data["message"]["senderId"] - self.content = data["message"]["content"] - self.room_id = data["roomId"] - self.msg_id = data["message"]["_id"] - - def is_self(self, self_id: int) -> bool: - return self.sender_id == self_id - - -class BotConfig(Options): - name = 'icalingua bot config' - # _check_filled = True - private_key: str - host: str - self_id: int - notice_room: List[int] - notice_start: bool = False - admin_list: List[int] - py_plugin_path: str - - def init(self, **kwargs) -> None: - if self.notice_room is None: - self.notice_start = False - - -def get_config(config_path: str = 'config.toml') -> BotConfig: - with open(config_path, 'r', encoding='utf-8') as f: - config = qtoml.decoder.load(f) - return BotConfig(**config) - - -class BotStatus(Options): - inited: bool = False - running: bool = False - rooms: List[int] = [] diff --git a/ica-py/main.py b/ica-py/main.py deleted file mode 100644 index 2cdc36f..0000000 --- a/ica-py/main.py +++ /dev/null @@ -1,36 +0,0 @@ -import asyncio -import argparse - -# from lib_not_dr.types import Options -from lib_not_dr.loggers import config - -from data_struct import get_config, BotConfig, BotStatus - -_version_ = "0.3.3" - -logger = config.get_logger("bot") - -BOTCONFIG: BotConfig = get_config() -BotStatus = BotStatus() - - -if __name__ == "__main__": - # --debug - # --config=config.toml - # -n --no-notice - parser = argparse.ArgumentParser(description=f"icalingua bot v{_version_}") - parser.add_argument("-d", "--debug", action="store_true") - parser.add_argument("-n", "--no-notice", action="store_true") - parser.add_argument("-c", "--config", type=str) - args = parser.parse_args() - if args.debug: - logger.global_level = 0 - if args.config: - # global BOTCONFIG - BOTCONFIG: BotConfig = get_config(args.config) - if args.no_notice: - BOTCONFIG.notice_start = False - - from connect import main - asyncio.run(main()) - diff --git a/ica-py/plugins/bmcl.py b/ica-py/plugins/bmcl.py deleted file mode 100644 index 23bf866..0000000 --- a/ica-py/plugins/bmcl.py +++ /dev/null @@ -1,98 +0,0 @@ -import time -import json -import aiohttp - -from lib_not_dr.loggers import config - -from data_struct import NewMessage, SendMessage - -logger = config.get_logger("bmcl") - -_version_ = "1.1.1" - - -def format_data_size(data_bytes: float) -> str: - data_lens = ["B", "KB", "MB", "GB", "TB"] - data_len = "0B" - for i in range(5): - if data_bytes < 1024: - data_bytes = round(data_bytes, 5) - data_len = f"{data_bytes}{data_lens[i]}" - break - else: - data_bytes /= 1024 - return data_len - - -def format_hit_count(count: int) -> str: - """数据分段, 四位一个下划线 - - Args: - count (int): 数据 - - Returns: - str: 格式化后的数据 - 1 -> 1 - 1000 -> 1000 - 10000 -> 1_0000 - 100000 -> 10_0000 - 1000000 -> 100_0000 - """ - count_str = str(count) - count_len = len(count_str) - if count_len <= 4: - return count_str - else: - return "_".join(count_str[i:i + 4] for i in range(0, count_len, 4)) - - -async def bmcl(sio, reply_msg: SendMessage, msg: NewMessage): - req_time = time.time() - # 记录请求时间 - async with aiohttp.ClientSession() as session: - async with session.get( - "https://bd.bangbang93.com/openbmclapi/metric/dashboard" - ) as response: - if not response.status == 200 or response.reason != "OK": - await sio.emit( - "sendMessage", - reply_msg.to_content( - f"请求数据失败\n{response.status}" - ).to_json(), - ) - logger.warn( - f"数据请求失败, 请检查网络\n{response.status}", - tag="bmclapi_dashboard", - ) - return - raw_data = await response.text() - try: - data = json.loads(raw_data) - data_bytes: float = data["bytes"] - data_hits: int = data["hits"] - data_bandwidth: float = data["currentBandwidth"] - load_str: float = data["load"] * 100 - online_node: int = data["currentNodes"] - online_bandwidth: int = data["bandwidth"] - data_len = format_data_size(data_bytes) - hits_count = format_hit_count(data_hits) - - report_msg = ( - f"OpenBMCLAPI 状态面板v{_version_} :\n" - f"实时信息: {online_node} 带宽: {online_bandwidth}Mbps\n" - f"负载: {load_str:.2f}% 带宽: {data_bandwidth:.2f}Mbps\n" - f"当日请求: {hits_count} 数据量: {data_len}\n" - f"请求时间: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(req_time))}\n" - "数据源: https://bd.bangbang93.com/pages/dashboard" - ) - await sio.emit( - "sendMessage", - reply_msg.to_content(report_msg).to_json() - ) - - except (json.JSONDecodeError, AttributeError, ValueError) as e: - await sio.emit( - "sendMessage", - reply_msg.to_content(f"返回数据解析错误\n{e}").to_json(), - ) - logger.warn(f"返回数据解析错误\n{e}", tag="bmclapi_dashboard") diff --git a/ica-py/plugins/safe_eval.py b/ica-py/plugins/safe_eval.py deleted file mode 100644 index a5ff544..0000000 --- a/ica-py/plugins/safe_eval.py +++ /dev/null @@ -1,72 +0,0 @@ -import time -import random -import traceback - -from main import BOTCONFIG - -from colorama import Fore -from lib_not_dr.loggers import config - -logger = config.get_logger("safe_eval") - -def safe_eval(code: str) -> str: - try: - # code = code.replace('help', '坏东西!\n') - # code = code.replace('bytes', '坏东西!\n') - # code = code.replace('encode', '坏东西!\n') - # code = code.replace('decode', '坏东西!\n') - # code = code.replace('compile', '屑的!\n') - # code = code.replace('globals', '拿不到!\n') - code = code.replace("os", "坏东西!\n") - code = code.replace("sys", "坏东西!\n") - # code = code.replace('input', '坏东西!\n') - # code = code.replace('__', '啊哈!\n') - # code = code.replace('import', '很坏!\n') - code = code.replace(" kill", "别跑!\n") - code = code.replace(" rm ", "别跑!\n") - code = code.replace("exit", "好坏!\n") - code = code.replace("eval", "啊哈!\n") - code = code.replace("exec", "抓住!\n") - start_time = time.time() - try: - import os - import math - import decimal - - global_val = { - "time": time, - "math": math, - "decimal": decimal, - "random": random, - "__import__": "", - "globals": "", - "compile": "", - "help": "", - "exit": "", - "input": "", - "return": "别惦记你那个 return 了", - "getattr": "", - "setattr": "", - } - os.system = "不许" - result = str(eval(code, global_val, {})) - limit = 500 - if len(result) > limit: - result = result[:limit] - except: - result = traceback.format_exc() - end_time = time.time() - result = result.replace(BOTCONFIG.private_key, "***") - result = result.replace(BOTCONFIG.host, "***") - - logger.info(f"{Fore.MAGENTA}safe_eval: {result}") - - if result == "6" or result == 6: - result = "他确实等于 6" - - result = f"{code}\neval result:\n{result}\n耗时: {end_time - start_time} s" - return result - except: - error = traceback.format_exc() - result = f"error:\n{error}" - return result diff --git a/ica-py/requirements.txt b/ica-py/requirements.txt deleted file mode 100644 index 0c0a52b..0000000 --- a/ica-py/requirements.txt +++ /dev/null @@ -1,7 +0,0 @@ -lib-not-dr >= 0.3.13 -colorama -qtoml -pynacl - -python-socketio -aiohttp diff --git a/ica-py/router.py b/ica-py/router.py deleted file mode 100644 index c435575..0000000 --- a/ica-py/router.py +++ /dev/null @@ -1,62 +0,0 @@ -import random -import asyncio - -from lib_not_dr.loggers import config - -from main import BOTCONFIG, _version_ -from data_struct import SendMessage, ReplyMessage, NewMessage - -from plugins import bmcl, safe_eval - -logger = config.get_logger("router") - -async def route(data, sio): - - is_self = data["message"]["senderId"] == BOTCONFIG.self_id - sender_name = data["message"]["username"] - sender_id = data["message"]["senderId"] - content = data["message"]["content"] - room_id = data["roomId"] - msg_id = data["message"]["_id"] - msg = NewMessage(data=data) - - reply_msg = SendMessage(content="", room_id=room_id, reply_to=ReplyMessage(id=msg_id)) - - if content == "/bot": - message = reply_msg.to_content(f"icalingua bot-python pong v{_version_}") - await sio.emit("sendMessage", message.to_json()) - - elif content.startswith("=="): - evals: str = content[2:] - - result = safe_eval.safe_eval(evals) - # whitelist = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ', '.', '+', '-', '*', '/', '(', ')', '<', - # '>', '='] - # evals = evals.replace('**', '') - # express = '' - # for text in evals: - # if text in whitelist: - # express += text - # if express == '': - # result = '你在干嘛' - # else: - # result = str(eval(express)) - message = reply_msg.to_content(result) - - await asyncio.sleep(random.random() * 2) - await sio.emit("sendMessage", message.to_json()) - - elif content == "!!jrrp": - randomer = random.Random( - f'{sender_id}-{data["message"]["date"]}-jrrp-{_version_}' - ) - result = randomer.randint(0, 50) + randomer.randint(0, 50) - logger.info(f"{sender_name} 今日人品值为 {result}") - message = reply_msg.to_content(f"{sender_name} 今日人品为 {result}") - await asyncio.sleep(0.5) - await sio.emit("sendMessage", message.to_json()) - - elif content == "/bmcl": - await bmcl.bmcl(sio, reply_msg, msg) - -