Linux 脚本:查询 API Key 的余额

import requests import cmd import readline class KeyBalanceCLI(cmd.Cmd): intro = "Welcome to the Key Balance CLI. Type 'help' for a list of commands." prompt = "(key_balance) > " def do_query(self, arg): """ 查询单个 API Key 的余额。 用法: query <API_KEY> """ if not arg: print("Error: Please provide an API Key.") return balance, total_balance = get_balances(arg) if balance is not None and total_balance is not None: print_balances(arg, balance, total_balance) else: print(f"Failed to query key: {arg}") def do_batch_query(self, arg): """ 从 keys.db 文件中批量查询所有 API Key 的余额。 用法: batch_query """ try: with open("keys.db", "r") as file: keys = file.read().strip().split(",") # 按逗号分隔读取 Key except FileNotFoundError: print("Error: keys.db file not found.") return total_balance = 0 # balance 总和 total_total_balance = 0 # totalBalance 总和 for key in keys: key = key.strip() # 去除前后空格 if not key: continue # 跳过空 Key balance, total_balance_field = get_balances(key) # 查询 balance 和 totalBalance if balance is not None and total_balance_field is not None: print_balances(key, balance, total_balance_field) # 累加到总和 total_balance += balance total_total_balance += total_balance_field # 打印总 balance 和 totalBalance print(f"总 Balance: {total_balance:.2f}") print(f"总 TotalBalance: {total_total_balance:.2f}") def do_exit(self, arg): """ 退出程序。 用法: exit """ print("Exiting...") return True def get_balances(api_key): """ 查询给定 API Key 的 balance 和 totalBalance。 :param api_key: API Key :return: (balance, totalBalance),如果查询失败则返回 (None, None) """ url = "https://api.siliconflow.cn/v1/user/info" # 替换为实际的 API 地址 headers = {"Authorization": f"Bearer {api_key}"} try: response = requests.get(url, headers=headers) response.raise_for_status() # 检查 HTTP 状态码是否为 200 data = response.json() # 解析 JSON 响应 balance = float(data.get("balance", 0)) # 提取 balance 字段 total_balance = float(data.get("totalBalance", 0)) # 提取 totalBalance 字段 return balance, total_balance except requests.exceptions.RequestException as e: print(f"Key {api_key} 查询失败: {e}") return None, None def print_balances(key, balance, total_balance): """ 打印 API Key 的 balance 和 totalBalance。 :param key: API Key :param balance: balance 值 :param total_balance: totalBalance 值 """ print(f"Key: {key}, Balance: {balance:.2f}, TotalBalance: {total_balance:.2f}") if __name__ == "__main__": KeyBalanceCLI().cmdloop()

July 5, 2023 · 2 min · 302 words

Renew Typora

import winreg from datetime import datetime def get_current_date(): """ 获取当前日期并格式化为月/日/年的格式,无前导零。 返回格式:月/日/年 """ current_date = datetime.now() month = current_date.month # 月份,无前导零 day = current_date.day # 日期,无前导零 year = current_date.year # 年份,四位数 return f"{month}/{day}/{year}" def modify_registry(key_path, value_name, value_data, value_type): """ 修改注册表键值 :param key_path: 注册表键的路径,例如 r"SOFTWARE\MyApp" :param value_name: 要修改的值的名称 :param value_data: 要设置的值 :param value_type: 值的类型,例如 winreg.REG_SZ (字符串), winreg.REG_DWORD (整数) 等 """ try: # 打开注册表键(如果不存在则会报错) with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as registry: with winreg.OpenKey(registry, key_path, 0, winreg.KEY_SET_VALUE) as key: # 修改键值 winreg.SetValueEx(key, value_name, 0, value_type, value_data) return print(f"成功修改注册表键值:{key_path}\\{value_name}") except PermissionError: return print("权限不足,无法修改注册表。") except FileNotFoundError: return print("指定的注册表键或路径不存在。") except Exception as e: return print(f"发生错误:{e}") # 示例:修改注册表 modify_registry("SOFTWARE\\Typora", "IDate", get_current_date(), winreg.REG_SZ)

March 26, 2023 · 1 min · 102 words

获取epub目录

import xml.etree.ElementTree as ET def parse_epub_toc(toc_file): """解析 EPUB 的 toc.ncx 文件""" try: tree = ET.parse(toc_file) root = tree.getroot() # 定义命名空间 ns = {'ncx': 'http://www.daisy.org/z3986/2005/ncx/'} # 获取书籍标题 doc_title = root.find('.//ncx:docTitle/ncx:text', ns) book_title = doc_title.text if doc_title is not None else "未知标题" # 获取所有 navPoint 元素 #nav_points = root.findall('.//ncx:navPoint', ns) nav_points = root.findall('./ncx:navMap/ncx:navPoint', ns) print(len(nav_points)) return book_title, nav_points, ns except Exception as e: print(f"解析文件出错: {e}") return None, None, None def build_toc_tree(nav_points, ns): """构建目录树结构""" toc = [] for nav_point in nav_points: # 获取章节信息 nav_label = nav_point.find('ncx:navLabel/ncx:text', ns) content = nav_point.find('ncx:content', ns) if nav_label is not None and content is not None: chapter = { 'id': nav_point.get('id', ''), 'play_order': nav_point.get('playOrder', ''), 'title': nav_label.text, 'src': content.get('src', ''), 'children': [] } # 递归处理子章节 sub_nav_points = nav_point.findall('ncx:navPoint', ns) if sub_nav_points: sub=True chapter['children'] = build_toc_tree(sub_nav_points, ns) toc.append(chapter) return toc def print_tree(toc, prefix='', is_last=True): """打印树形目录结构""" for i, chapter in enumerate(toc): # 当前节点连接符 #connector = '└── ' if (i == len(toc) - 1 and is_last) else '├── ' connector = ' ' if (i == len(toc) - 1 and is_last) else ' ' # 打印当前节点 print(prefix + connector + chapter['title']) # 准备子节点前缀 # new_prefix = prefix + (' ' if (i == len(toc) - 1 and is_last) else '│ ') new_prefix = prefix + (' ' if (i == len(toc) - 1 and is_last) else ' ') # 递归打印子节点 if chapter['children']: print_tree(chapter['children'], new_prefix , is_last and i == len(toc) - 2) #print(is_last,i,len(toc) - 1) def main(): # 输入文件路径 toc_file = 'toc.ncx' # 解析文件 book_title, nav_points, ns = parse_epub_toc(toc_file) if not book_title: return print(f"书籍标题: {book_title}\n") print("目录结构:") # 构建目录树 toc_tree = build_toc_tree(nav_points, ns) # 打印树形结构 print_tree(toc_tree) if __name__ == "__main__": main()

2 min · 269 words