diff --git a/README.md b/README.md index b8e549b4..9552fe22 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@
-# 🎉 修仙2.2魔改版 +# 🎉 修仙2.3魔改版 _✨ QQ群聊修仙文字游戏✨_ @@ -32,7 +32,7 @@ _✨ QQ群聊修仙文字游戏✨_ 4、新增各种丹药,装备,功法,礼包 -5、更多不同请自行探索 +5、替换SQLite为Postgresql # 💿 安装 @@ -52,6 +52,8 @@ git clone -b dev --depth=1 https://github.com/wsdtl/nonebot_plugin_xiuxian_2_pmv ``` pip install -r requirements.txt + +npm i -g random_chinese_fantasy_names (这个主要是用来生成随机名字的) ``` 4、在.env.dev文件中设置超管与机器人昵称 @@ -108,6 +110,7 @@ self.layout_bot_dict = {{}} # QQ所负责的群聊{{群 :bot}} 其中 bot类 - [NoneBot2](https://github.com/nonebot/nonebot2):本插件实装的开发框架,NB天下第一可爱。 - [nonebot_plugin_xiuxian](https://github.com/s52047qwas/nonebot_plugin_xiuxian):原版修仙 - [nonebot_plugin_xiuxian_2](https://github.com/QingMuCat/nonebot_plugin_xiuxian_2):原版修仙2 +- [仙侠小说专有名词随机生成器](https://github.com/hythl0day/random_chinese_fantasy_names): 好用的仙侠名词生成器 # 🎉 支持 diff --git a/data/xiuxian/xiuxian_version.txt b/data/xiuxian/xiuxian_version.txt index f4436cbb..5a01350c 100644 --- a/data/xiuxian/xiuxian_version.txt +++ b/data/xiuxian/xiuxian_version.txt @@ -1 +1 @@ -xiuxian_2.2 \ No newline at end of file +xiuxian_2.3 \ No newline at end of file diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/alchemy/alchemy.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/alchemy/alchemy.json" new file mode 100644 index 00000000..6a2ca490 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/alchemy/alchemy.json" @@ -0,0 +1 @@ +["丹", "丸", "散", "药", "剂", "汤", "饮", "茶", "酒"] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/book/book.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/book/book.json" new file mode 100644 index 00000000..63ba94b5 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/book/book.json" @@ -0,0 +1 @@ +["图", "经", "典", "籍", "篆"] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/book/postfix.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/book/postfix.json" new file mode 100644 index 00000000..a447bd49 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/book/postfix.json" @@ -0,0 +1,4 @@ +{ + "uncommon": ["残页", "残卷", "残本"], + "rare": ["抄本", "过录本", "拓本", "摹本"] +} diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/book/prefix.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/book/prefix.json" new file mode 100644 index 00000000..3fe2c1e1 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/book/prefix.json" @@ -0,0 +1,6 @@ +{ + "epic": ["全", "总"], + "legendary": ["真", "秘"], + "mythic": ["宝", "玄"], + "exotic": ["仙", "魔"] +} diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/creature/creature.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/creature/creature.json" new file mode 100644 index 00000000..a4b5f7e2 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/creature/creature.json" @@ -0,0 +1,80 @@ +{ + "plant": ["木", "树", "草", "苔", "竹", "参", "芝", "花", "棘", "荆", "藤"], + + "worm": [ + "龙", + "蛟", + "虫", + "蛙", + "蚕", + "蛾", + "蝶", + "蛤", + "蝴蝶", + "蛤蟆", + "蚯蚓" + ], + + "fish": ["鱼", "鲸", "豚"], + + "beast": [ + "兽", + "猴", + "猿", + "马", + "牛", + "猪", + "羊", + "鹿", + "猫", + "狮", + "虎", + "狼", + "狗", + "熊", + "豹", + "狐", + "鼠", + "兔", + "狸", + "犀", + "魈", + "麒麟", + "貔貅", + "狻猊", + "狸猫", + "犀牛", + "猞猁", + "犰狳" + ], + + "bird": [ + "鸟", + "雕", + "鹰", + "鹤", + "燕", + "雀", + "鸦", + "鸡", + "凤", + "鸠", + "鹅", + "鹦", + "蝠", + "凤凰", + "孔雀", + "鴛鴦", + "天鹅", + "鹧鸪", + "鹌鹑", + "鹈鹕", + "鸬鹚", + "鹦鹉", + "蝙蝠" + ], + + "reptile": ["龟", "鳄", "鳌", "蛇", "蜥", "蜥蜴", "蝾螈"], + + "insect": ["虫", "蝎", "蜂", "蟹", "蚣", "螂", "螃蟹", "蜈蚣", "螳螂"] +} diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/creature/prefix.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/creature/prefix.json" new file mode 100644 index 00000000..e8e5b575 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/creature/prefix.json" @@ -0,0 +1 @@ +["野", "古", "玄", "灵", "仙", "魔", "神", "鬼"] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/creature/strange.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/creature/strange.json" new file mode 100644 index 00000000..7b0318a6 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/creature/strange.json" @@ -0,0 +1,86 @@ +[ + "傲因", + "毕方", + "并封", + "狴犴", + "嘲风", + "赤鱬", + "长右", + "乘黄", + "重明鸟", + "担生", + "帝江", + "刀劳鬼", + "当康", + "封豨", + "风狸", + "夫诸", + "飞诞鸟", + "肥遗", + "飞廉", + "姑获鸟", + "孰胡", + "虹蜺", + "豪彘", + "何罗鱼", + "含利", + "吉量", + "计蒙", + "钦原", + "开明兽", + "螭吻", + "龙伯", + "冉遗鱼", + "罗罗鸟", + "螭首", + "蛮蛮鸟", + "穷奇", + "梼杌", + "獬豸", + "夔牛", + "灭蒙", + "当扈", + "角端", + "陆吾", + "朱厌", + "祸斗", + "诸犍", + "白泽兽", + "夫诸", + "乘黄", + "猰貐", + "屏蓬", + "相柳", + "狍鸮", + "犀渠", + "却火雀", + "彭侯", + "却尘犀", + "庆忌", + "瞿如", + "日及", + "尚付", + "蛊雕", + "狌狌", + "驺虞", + "无支祁", + "文鳐鱼", + "狙如", + "朱厌", + "罗睺", + "蔓金苔", + "洞冥草", + "祝馀草", + "迷榖树", + "白䓘木", + "萆荔草", + "文茎木", + "棕楠树", + "黄雚草", + "蓇蓉草", + "杜衡草", + "无条草", + "沙棠木", + "雕棠木", + "葶苧草" +] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/dao/dao.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/dao/dao.json" new file mode 100644 index 00000000..bf72160d --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/dao/dao.json" @@ -0,0 +1,179 @@ +[ + "正", + "悟", + "济", + "广", + "善", + "净", + "莲", + "慧", + "普", + "觉", + "宗", + "禅", + "明", + "法", + "清", + "真", + "妙", + "海", + "智", + "颖", + "圆", + "了", + "本", + "可", + "道", + "庆", + "同", + "玄", + "静", + "湛", + "寂", + "淳", + "贞", + "素", + "德", + "行", + "永", + "延", + "恒", + "常", + "朗", + "幽", + "深", + "鉴", + "谨", + "原", + "度", + "初", + "乘", + "刚", + "量", + "藏", + "光", + "经", + "闻", + "宣", + "衍", + "兴", + "戒", + "阴", + "阳", + "云", + "极", + "古", + "今", + "慈", + "悲", + "世", + "愿", + "无", + "尽", + "启", + "花", + "宏", + "相", + "昌", + "乾", + "坤", + "虚", + "怀", + "印", + "容", + "悬", + "镜", + "融", + "惠", + "泽", + "生", + "隆", + "临", + "通", + "源", + "能", + "仁", + "果", + "惟", + "会", + "定", + "崇", + "胜", + "维", + "方", + "福", + "祥", + "澄", + "空", + "远", + "龙", + "阳", + "至", + "理", + "诚", + "信", + "高", + "景", + "荣", + "希", + "微", + "修", + "义", + "黄", + "贵", + "全", + "功", + "秀", + "木", + "山", + "宝", + "和", + "志", + "玉", + "元", + "弘", + "罗", + "贤", + "成", + "章", + "哲", + "格", + "茂", + "言", + "神", + "参", + "立", + "奇", + "恭", + "存", + "依", + "敬", + "承", + "贯", + "端", + "敏", + "华", + "礼", + "嘉", + "泰", + "宇", + "亨", + "灵", + "秘", + "慎", + "纯", + "建", + "益", + "宁", + "利", + "享", + "始", + "霄", + "炼", + "知", + "极", + "息", + "润", + "安", + "凝" +] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/dao/title_female.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/dao/title_female.json" new file mode 100644 index 00000000..6bf8015c --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/dao/title_female.json" @@ -0,0 +1,8 @@ +{ + "uncommon": ["子", "道姑"], + "rare": ["真人", "法师"], + "epic": ["公主", "洞主"], + "legendary": ["教母", "圣女"], + "mythic": ["仙", "仙子", "仙女", "圣母"], + "exotic": ["娘娘"] +} diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/dao/title_male.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/dao/title_male.json" new file mode 100644 index 00000000..bbce1f8e --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/dao/title_male.json" @@ -0,0 +1,8 @@ +{ + "uncommon": ["子", "道人"], + "rare": ["真人", "法师"], + "epic": ["上人", "洞主"], + "legendary": ["教主", "真君"], + "mythic": ["仙", "仙人", "仙师", "仙翁"], + "exotic": ["天尊"] +} diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/material/material.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/material/material.json" new file mode 100644 index 00000000..44f31bb3 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/material/material.json" @@ -0,0 +1,55 @@ +{ + "common": ["金", "银", "铜", "铁", "玉", "晶", "钻", "砂", "石", "岩", "泥"], + + "uncommon": ["水", "液", "露", "胶", "浆"], + + "rare": [ + "木", + "树", + "树皮", + "树根", + "草", + "苔", + "竹", + "参", + "芝", + "花", + "丝", + "藤", + "叶", + "碳", + "漆", + "汁", + "果", + "果核", + "果壳" + ], + + "epic": ["水晶", "珊瑚", "玛瑙", "曜石", "玳瑁", "琥珀", "珍珠"], + + "legendary": [ + "骨", + "牙", + "齿", + "髓", + "目", + "眼", + "睛", + "眼珠", + "尾", + "鳞", + "鳍", + "蹄", + "须", + "毛", + "皮", + "角", + "爪", + "翅", + "羽" + ], + + "mythic": ["火", "炎", "焰", "雷", "电", "冰"], + + "exotic": ["精", "魂", "魄"] +} diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/material/postfix.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/material/postfix.json" new file mode 100644 index 00000000..5a66b05b --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/material/postfix.json" @@ -0,0 +1 @@ +{ "broken": ["破损", "污损"], "handmade": ["残破", "缺损"] } diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/name/family.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/name/family.json" new file mode 100644 index 00000000..8470a3fd --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/name/family.json" @@ -0,0 +1,207 @@ +[ + "李", + "王", + "张", + "刘", + "陈", + "杨", + "赵", + "黄", + "周", + "吴", + "徐", + "孙", + "胡", + "朱", + "高", + "林", + "何", + "郭", + "马", + "罗", + "梁", + "宋", + "郑", + "谢", + "韩", + "唐", + "冯", + "于", + "董", + "萧", + "程", + "曹", + "袁", + "邓", + "许", + "傅", + "沈", + "曾", + "彭", + "吕", + "苏", + "卢", + "蒋", + "蔡", + "贾", + "丁", + "魏", + "薛", + "叶", + "阎", + "余", + "潘", + "杜", + "戴", + "夏", + "锺", + "汪", + "田", + "任", + "姜", + "范", + "方", + "石", + "姚", + "谭", + "廖", + "邹", + "熊", + "金", + "陆", + "郝", + "孔", + "白", + "崔", + "康", + "毛", + "邱", + "欧阳", + "秦", + "江", + "史", + "顾", + "侯", + "邵", + "南宫", + "孟", + "龙", + "万", + "段", + "漕", + "钱", + "汤", + "尹", + "东方", + "黎", + "易", + "常", + "武", + "乔", + "贺", + "赖", + "龚", + "文", + "庞", + "樊", + "兰", + "西门", + "殷", + "施", + "陶", + "洪", + "翟", + "安", + "令狐", + "颜", + "倪", + "严", + "牛", + "温", + "季", + "俞", + "章", + "鲁", + "葛", + "伍", + "百里", + "韦", + "申", + "尤", + "毕", + "聂", + "焦", + "向", + "上官", + "柳", + "邢", + "路", + "岳", + "夏侯", + "齐", + "梅", + "莫", + "庄", + "辛", + "长孙", + "管", + "祝", + "涂", + "皇甫", + "谷", + "祁", + "耿", + "路", + "慕容", + "詹", + "关", + "苗", + "凌", + "费", + "纪", + "童", + "欧", + "甄", + "诸葛", + "项", + "曲", + "裴", + "席", + "查", + "屈", + "鲍", + "霍", + "澹台", + "柯", + "阮", + "闵", + "解", + "柴", + "吉", + "瞿", + "戚", + "司徒", + "米", + "池", + "姬", + "轩辕", + "晏", + "栾", + "商", + "敖", + "冷", + "司马", + "花", + "艾", + "蓝", + "都", + "司空", + "仲", + "乐", + "封", + "楚", + "蔺", + "端木", + "墨", + "宁" +] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/name/female.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/name/female.json" new file mode 100644 index 00000000..2f3590ab --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/name/female.json" @@ -0,0 +1,429 @@ +[ + "兮", + "芳", + "星", + "清", + "夏", + "月", + "初", + "书", + "简", + "雪", + "益", + "纯", + "琛", + "馨", + "宁", + "吉", + "柔", + "心", + "婉", + "昭", + "文", + "嘉", + "微", + "秋", + "声", + "桐", + "颜", + "杭", + "洲", + "笑", + "语", + "新", + "佩", + "卓", + "伊", + "云", + "洁", + "宛", + "田", + "惠", + "瑜", + "瑾", + "萌", + "礼", + "佳", + "夕", + "灼", + "华", + "彤", + "美", + "盈", + "媛", + "奕", + "依", + "林", + "艾", + "君", + "景", + "舟", + "楚", + "英", + "卉", + "雨", + "瑶", + "舒", + "恬", + "温", + "怡", + "曼", + "斯", + "言", + "湘", + "灵", + "琼", + "钟", + "柯", + "康", + "昊", + "蔚", + "兰", + "莹", + "重", + "臻", + "素", + "菲", + "琴", + "远", + "南", + "念", + "荷", + "献", + "晨", + "京", + "冬", + "斐", + "禾", + "静", + "畅", + "的", + "亿", + "薇", + "锦", + "靖", + "白", + "慧", + "楠", + "敏", + "卿", + "音", + "竞", + "中", + "芮", + "鸿", + "羽", + "愉", + "驰", + "攸", + "悠", + "涵", + "蓉", + "淇", + "彦", + "姬", + "紫", + "霜", + "偲", + "娟", + "娜", + "媚", + "彩", + "桃", + "姣", + "宝", + "娇", + "春", + "露", + "棋", + "巧", + "嫔", + "菱", + "晗", + "妍", + "妙", + "香", + "娴", + "姝", + "雅", + "琪", + "姗", + "仪", + "源", + "芷", + "芹", + "谷", + "晴", + "珍", + "婷", + "寻", + "妩", + "旋", + "菡", + "颖", + "娅", + "筠", + "妮", + "沛", + "芙", + "婕", + "贻", + "萱", + "赫", + "凝", + "容", + "莲", + "玉", + "俞", + "情", + "娈", + "姿", + "柳", + "希", + "岚", + "蝶", + "盼", + "玲", + "娆", + "婵", + "海", + "幻", + "晓", + "婧", + "丹", + "娉", + "妃", + "冰", + "凡", + "听", + "寒", + "旭", + "翠", + "烟", + "倩", + "伶", + "丽", + "萍", + "蓝", + "瑷", + "珊", + "代", + "蕾", + "俪", + "梓", + "怜", + "雯", + "琳", + "璎", + "霏", + "霖", + "瑞", + "嫣", + "妤", + "画", + "含", + "慕", + "蕊", + "嫱", + "枫", + "雁", + "蓓", + "纨", + "眉", + "菁", + "苑", + "瑗", + "琰", + "淑", + "珠", + "芝", + "红", + "娥", + "芬", + "燕", + "菊", + "凤", + "梅", + "真", + "环", + "荣", + "爱", + "妹", + "霞", + "莺", + "艳", + "勤", + "贞", + "莉", + "桂", + "娣", + "叶", + "璧", + "璐", + "琦", + "晶", + "茜", + "莎", + "黛", + "青", + "韵", + "融", + "园", + "艺", + "咏", + "聪", + "澜", + "毓", + "悦", + "爽", + "琬", + "茗", + "欣", + "飘", + "育", + "滢", + "馥", + "竹", + "霭", + "欢", + "霄", + "芸", + "亚", + "影", + "荔", + "枝", + "秀", + "抒", + "轩", + "睿", + "懿", + "凌", + "翊", + "茹", + "嫦", + "逸", + "潍", + "滔", + "泊", + "会", + "研", + "阳", + "森", + "弘", + "昱", + "世", + "灏", + "沁", + "锘", + "锐", + "鑫", + "宇", + "贤", + "玥", + "泽", + "镒", + "橙", + "蕙", + "滟", + "柄", + "铭", + "双", + "燨", + "芊", + "壬", + "岩", + "煦", + "筱", + "茵", + "辰", + "弈", + "格", + "瑛", + "珺", + "亭", + "泉", + "尹", + "优", + "杨", + "垣", + "葶", + "贝", + "栩", + "芯", + "禹", + "冉", + "漫", + "童", + "麒", + "澄", + "苏", + "葛", + "珂", + "尚", + "豫", + "溪", + "齐", + "喻", + "皖", + "曦", + "闵", + "丞", + "孝", + "绮", + "诗", + "殷", + "婼", + "虹", + "翌", + "曜", + "萧", + "唤", + "缨", + "诺", + "金", + "皎", + "蓁", + "飞", + "慎", + "炜", + "洵", + "邦", + "芃", + "绿", + "琇", + "琚", + "陶", + "玖", + "好", + "舜", + "德", + "零", + "猗", + "衣", + "苓", + "湄", + "渥", + "窈", + "荟", + "翕", + "绥", + "令", + "闻", + "天", + "骏", + "翰", + "溱", + "苾", + "桢", + "缉", + "熙", + "鹰", + "瓒", + "徽", + "穆", + "哲", + "秉", + "振", + "鹭", + "铃" +] \ No newline at end of file diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/name/male.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/name/male.json" new file mode 100644 index 00000000..8ac9a188 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/name/male.json" @@ -0,0 +1,398 @@ +[ + "国", + "民", + "邦", + "杰", + "宝", + "森", + "炳", + "文", + "伯", + "华", + "龙", + "伦", + "阳", + "博", + "常", + "春", + "栋", + "凤", + "贵", + "俊", + "德", + "章", + "恩", + "芳", + "业", + "志", + "光", + "泽", + "昌", + "川", + "方", + "奎", + "亮", + "明", + "年", + "鹏", + "全", + "顺", + "同", + "武", + "治", + "智", + "忠", + "壮", + "道", + "清", + "兴", + "远", + "诚", + "辉", + "良", + "林", + "隆", + "敏", + "仁", + "荣", + "容", + "润", + "生", + "威", + "祥", + "新", + "馨", + "秀", + "义", + "玉", + "源", + "政", + "中", + "云", + "定", + "东", + "彩", + "鸣", + "翔", + "仪", + "福", + "海", + "前", + "宇", + "裕", + "桂", + "芬", + "宾", + "均", + "卿", + "瑞", + "泰", + "贤", + "彦", + "英", + "珍", + "汉", + "浩", + "河", + "鹤", + "弘", + "毅", + "鸿", + "儒", + "焕", + "吉", + "济", + "先", + "嘉", + "景", + "山", + "星", + "刚", + "俭", + "勤", + "来", + "兰", + "言", + "利", + "臣", + "金", + "凌", + "茂", + "孟", + "麟", + "学", + "哲", + "南", + "培", + "基", + "沛", + "霖", + "程", + "举", + "霄", + "启", + "起", + "千", + "里", + "松", + "谷", + "尚", + "微", + "绍", + "时", + "雨", + "达", + "奇", + "伟", + "世", + "科", + "禄", + "美", + "铭", + "宁", + "雄", + "勋", + "仕", + "淑", + "树", + "聪", + "齐", + "睿", + "四", + "天", + "保", + "祺", + "麒", + "廷", + "庭", + "彬", + "斌", + "灿", + "鼎", + "富", + "广", + "翰", + "瀚", + "虎", + "会", + "惠", + "锦", + "魁", + "澜", + "礼", + "升", + "胜", + "盛", + "通", + "炜", + "蔚", + "熙", + "信", + "选", + "雅", + "耀", + "烨", + "友", + "煜", + "渊", + "昭", + "照", + "希", + "锡", + "显", + "宪", + "孝", + "飞", + "康", + "贞", + "恒", + "书", + "堂", + "凯", + "跃", + "路", + "运", + "庚", + "兆", + "丰", + "振", + "声", + "震", + "昂", + "高", + "致", + "仲", + "谦", + "真", + "江", + "寒", + "轩", + "宣", + "竹", + "苑", + "权", + "琛", + "晋", + "衡", + "昱", + "航", + "辰", + "昊", + "旭", + "季", + "丞", + "锋", + "濯", + "玮", + "皓", + "炎", + "温", + "煊", + "柯", + "恺", + "靖", + "瑜", + "宏", + "衿", + "卓", + "洺", + "艺", + "晨", + "晖", + "洋", + "歌", + "修", + "君", + "玄", + "仙", + "毛", + "问", + "菱", + "官", + "稷", + "邺", + "洁", + "岚", + "乾", + "游", + "陆", + "晓", + "墨", + "殿", + "晏", + "佑", + "圭", + "沅", + "楚", + "梓", + "坤", + "拓", + "苗", + "鹭", + "霆", + "茗", + "黎", + "洲", + "伊", + "冷", + "然", + "宥", + "韬", + "陌", + "旋", + "予", + "展", + "宸", + "司", + "暮", + "迅", + "朔", + "驹", + "羽", + "侗", + "圣", + "风", + "深", + "祁", + "靳", + "翌", + "枫", + "炫", + "瑾", + "叶", + "赫", + "厚", + "擎", + "翊", + "夜", + "倾", + "淮", + "简", + "朴", + "桦", + "健", + "裴", + "汜", + "捷", + "幕", + "珏", + "木", + "钧", + "默", + "顾", + "洛", + "初", + "弦", + "络", + "昕", + "野", + "骞", + "庸", + "能", + "骐", + "骥", + "峻", + "曼", + "舒", + "离", + "珵", + "旗", + "锵", + "倡", + "灵", + "杜", + "波", + "既", + "翾", + "青", + "勇", + "坚", + "璐", + "秉", + "翼", + "遥", + "休", + "尤", + "琬", + "琰", + "冬", + "衍", + "绎", + "心", + "怿", + "幼", + "静", + "闲", + "嫮", + "理", + "慈", + "逾", + "依", + "斐", + "月", + "奋", + "素", + "菀", + "璋", + "硕" +] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/name/middle.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/name/middle.json" new file mode 100644 index 00000000..f916890c --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/name/middle.json" @@ -0,0 +1,129 @@ +[ + "之", + "亦", + "其", + "如", + "而", + "何", + "乃", + "且", + "若", + "和", + "所", + "为", + "也", + "以", + "因", + "于", + "与", + "则", + "之", + "尔", + "化", + "从", + "可", + "在", + "再", + "然", + "已", + "大", + "不", + "弃", + "自", + "准", + "岂", + "才", + "仅", + "今", + "非", + "公", + "允", + "又", + "有", + "由", + "必", + "竟", + "予", + "充", + "少", + "宜", + "更", + "复", + "者", + "客", + "安", + "成", + "承", + "崇", + "继", + "进", + "敬", + "克", + "立", + "士", + "知", + "维", + "唯", + "采", + "易", + "扬", + "思", + "望", + "乐", + "忆", + "一", + "元", + "长", + "正", + "子", + "宗", + "朝", + "怀", + "无", + "建", + "梦", + "庆", + "万", + "向", + "延", + "应", + "永", + "飞", + "广", + "垂", + "振", + "兴", + "照", + "行", + "羡", + "摇", + "凝", + "笑", + "融", + "听", + "忍", + "游", + "潜", + "眠", + "念", + "近", + "献", + "留", + "寻", + "展", + "入", + "恨", + "染", + "谈", + "追", + "惜", + "容", + "生", + "落", + "凌", + "修", + "依", + "含", + "咏", + "学" +] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/organization/clan.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/organization/clan.json" new file mode 100644 index 00000000..ce58cf7e --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/organization/clan.json" @@ -0,0 +1,50 @@ +[ + "门", + "宗", + "派", + "教", + "帮", + "盟", + "会", + "社", + "党", + "阁", + "刹", + "庙", + "庵", + "楼", + "房", + "观", + "宫", + "寺", + "府", + "院", + "堂", + "坞", + "坊", + "轩", + "苑", + "斋", + "殿", + "城", + "堡", + "村", + "庄", + "寨", + "山", + "峰", + "崖", + "谷", + "洞", + "岛", + "塔", + "狱", + "旗", + "道", + "世家", + "山庄", + "书院", + "客栈", + "剑派", + "神教" +] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/organization/nation.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/organization/nation.json" new file mode 100644 index 00000000..f7fd5f58 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/organization/nation.json" @@ -0,0 +1 @@ +["国", "族", "部落", "联盟"] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/continent.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/continent.json" new file mode 100644 index 00000000..17c9ba10 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/continent.json" @@ -0,0 +1 @@ +["洲", "大陆", "海", "洋", "天", "界", "域"] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/location.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/location.json" new file mode 100644 index 00000000..3c99cdf4 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/location.json" @@ -0,0 +1,51 @@ +[ + "州", + "县", + "市", + "郡", + "乡", + "道", + "府", + "城", + "堡", + "镇", + "村", + "庄", + "驿", + "营", + "寨", + "山", + "峰", + "岭", + "坪", + "崖", + "谷", + "岗", + "洞", + "川", + "坡", + "观", + "寺", + "宫", + "原", + "岛", + "屿", + "渚", + "汀", + "湾", + "港", + "渡", + "津", + "坞", + "关", + "林", + "湖", + "潭", + "池", + "泊", + "泽", + "河", + "海", + "江", + "水" +] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/place.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/place.json" new file mode 100644 index 00000000..6f5d5ee7 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/place.json" @@ -0,0 +1,117 @@ +[ + "景", + "葛", + "岐", + "历", + "文", + "岷", + "涿", + "盂", + "崂", + "申", + "莱", + "渤", + "夷", + "羽", + "青", + "成", + "渭", + "竹", + "浮", + "英", + "时", + "咸", + "鲜", + "单", + "雍", + "瀛", + "苗", + "狄", + "炎", + "玄", + "长", + "元", + "晋", + "越", + "燕", + "蓟", + "安", + "定", + "虹", + "浦", + "万", + "朔", + "兴", + "宿", + "亳", + "池", + "宣", + "福", + "泉", + "德", + "宁", + "景", + "吉", + "抚", + "济", + "泰", + "聊", + "滨", + "焦", + "鄂", + "随", + "常", + "淮", + "惠", + "梅", + "潮", + "柳", + "钦", + "贺", + "琼", + "泸", + "乐", + "眉", + "丽", + "庆", + "夏", + "栾", + "广", + "满", + "涿", + "雄", + "顺", + "易", + "容", + "赤", + "丰", + "广", + "固", + "冀", + "平", + "云", + "灵", + "潞", + "滁", + "霸", + "应", + "洪", + "蒲", + "交", + "岚", + "扬", + "荆", + "凉", + "益", + "幽", + "并", + "襄", + "永", + "辽", + "巴", + "清", + "明", + "义", + "梁", + "信" +] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/postfix.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/postfix.json" new file mode 100644 index 00000000..1138b022 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/postfix.json" @@ -0,0 +1 @@ +["阴", "阳", "东", "西", "南", "北", "中", "安", "平", "昌", "宁", "庆"] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/prefix.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/prefix.json" new file mode 100644 index 00000000..bfc192f5 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/prefix.json" @@ -0,0 +1,20 @@ +[ + "前", + "后", + "上", + "下", + "大", + "小", + "内", + "外", + "左", + "右", + "临", + "望", + "正", + "东", + "西", + "南", + "北", + "中" +] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/zone.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/zone.json" new file mode 100644 index 00000000..a3a32665 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/place/zone.json" @@ -0,0 +1,5 @@ +{ + "water": ["海", "洋"], + "land": ["洲", "大陆"], + "void": ["域", "境", "天", "界"] +} diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/shared/color.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/shared/color.json" new file mode 100644 index 00000000..a5614e61 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/shared/color.json" @@ -0,0 +1 @@ +["赤", "青", "紫", "碧", "白", "灰", "乌", "黑", "墨", "暗"] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/shared/common.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/shared/common.json" new file mode 100644 index 00000000..8a80dc14 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/shared/common.json" @@ -0,0 +1,606 @@ +{ + "dao": [ + "长生", + "玉清", + "清微", + "元始", + "上清", + "禹余", + "灵宝", + "太清", + "大赤", + "道德", + "兜率", + "紫微", + "太微", + "禹余", + "洞玄", + "大赤", + "内景", + "混世", + "合欢", + "极乐", + "欢喜", + "慈悲", + "大品", + "真武", + "灵宝", + "神照", + "星枢", + "神宝", + "禅音", + "异相", + "巨阙", + "玲珑", + "罗烟", + "如意", + "太祖", + "罗汉", + "大衍", + "中孚", + "无色", + "菩提", + "普贤", + "莲华", + "心意", + "静禅", + "光相", + "达摩", + "般若", + "涅槃", + "灵武", + "灵悟", + "坐忘", + "不念", + "百合", + "芙蓉", + "宝色", + "灵枢", + "素问", + "云环", + "玉虚", + "归藏", + "连山", + "奇经", + "奇门", + "遁甲", + "霸王", + "守拙", + "若愚", + "太保", + "璇玑", + "神机", + "昆吾", + "金刚", + "罗刹", + "修罗", + "如意", + "周天", + "轮回", + "潇湘", + "轩辕", + "枯荣", + "雌雄", + "子母" + ], + + "element": [ + "天罡", + "天师", + "天府", + "天照", + "天仙", + "天宫", + "天雷", + "天火", + "天宝", + "天兵", + "天枢", + "天魔", + "天地", + "地煞", + "地仙", + "地宝", + "幽冥", + "冥河", + "日月", + "古仙", + "古佛", + "火焰", + "火元", + "神火", + "烈火", + "青焰", + "焰光", + "寒冰", + "玄冰", + "光明", + "雷电", + "水火", + "风雷", + "雷火", + "风火", + "冰火", + "晶炎" + ], + "creature": [ + "金童", + "玉女", + "帝女", + "素女", + "星女", + "游龙", + "蟠龙", + "神龙", + "天龙", + "火龙", + "毒龙", + "狂龙", + "烛龙", + "应龙", + "龙虎", + "老虎", + "狮子", + "狮吼", + "狮啸", + "苍狼", + "野熊", + "仙鹤", + "灵鹤", + "神龟", + "灵龟", + "玄龟", + "灵鳌", + "灵蛇", + "金蛇", + "灵猴", + "灵猿", + "仙猿", + "灵兔", + "飞燕", + "麒麟", + "凤凰", + "孔雀", + "鴛鴦", + "蝴蝶", + "螳螂", + "天蝉", + "燕子", + "青龙", + "白虎", + "朱雀" + ], + + "thing": [ + "紫云", + "紫霄", + "紫府", + "黄泉", + "黄竹", + "金阙", + "金玉", + "金身", + "金砂", + "青莲", + "青竹", + "青花", + "白云", + "白虹", + "白玉", + "白眉", + "朱砂", + "玄武", + "玄门", + "玄女", + "玄天", + "玄都", + "黑木", + "黑石", + "风雨", + "花雨", + "烟雨", + "霹雳", + "幻梦", + "灵丹", + "莲花", + "梅花", + "琼花", + "梨花", + "桃花", + "飞云", + "柔云", + "青云", + "彩云", + "阴风", + "寒风", + "罡风", + "流星", + "长风", + "长春", + "昇阳", + "残魂", + "残虹" + ], + + "color": [ + "素心", + "素银", + "紫霞", + "素光", + "金霞", + "金光", + "赤霄", + "玄阴", + "玄冥", + "玄微", + "青面" + ], + + "place": [ + "少林", + "武当", + "峨眉", + "昆仑", + "崆峒", + "点苍", + "终南", + "武夷", + "哀牢", + "太行", + "华山", + "泰山", + "嵩山", + "天山", + "衡山", + "恒山", + "须弥", + "蓬莱", + "东海", + "东华", + "南海", + "南华", + "南斗", + "西海", + "西域", + "北海", + "北斗" + ], + + "adj": [ + "通天", + "通臂", + "通身", + "一字", + "大力", + "迷踪", + "沛然", + "清净", + "逍遥", + "缥缈" + ], + + "number": [ + "无常", + "无相", + "无量", + "无极", + "无上", + "无形", + "无影", + "无妄", + "无定", + "无踪", + "无为", + "无涯", + "无终", + "无根", + "虚空", + "空冥", + "先天", + "希夷", + "混沌", + "混天", + "混元", + "浑元", + "大荒", + "大成", + "太极", + "太元", + "太乙", + "太一", + "太初", + "太始", + "太玄", + "正气", + "朝元", + "归元", + "归一", + "一元", + "一气", + "一阳", + "阴阳", + "紫阳", + "太阳", + "纯阳", + "少阳", + "太阴", + "纯阴", + "少阴", + "寒阴", + "二气", + "两仪", + "两界", + "三清", + "三昧", + "三生", + "三世", + "三才", + "三元", + "三危", + "三尸", + "四方", + "四海", + "四象", + "五行", + "五光", + "五气", + "五色", + "五彩", + "五火", + "五龙", + "五阴", + "五阳", + "五花", + "五鬼", + "五毒", + "五雷", + "六合", + "六弦", + "六阴", + "六阳", + "六丁", + "六甲", + "六虚", + "七星", + "七宝", + "七彩", + "七香", + "七巧", + "七弦", + "七杀", + "七煞", + "八卦", + "八门", + "八方", + "八级", + "八目", + "八脉", + "九龙", + "九天", + "九转", + "九阴", + "九阳", + "九幽", + "九宫", + "九炼", + "九华", + "九鼎", + "九曜", + "九曲", + "十方", + "百花", + "百灵", + "百毒", + "百魔", + "百仙", + "百里", + "百丈", + "百兽", + "百鬼", + "百炼", + "千机", + "千钧", + "千里", + "万花", + "万剑", + "万刃", + "万仙", + "万魂", + "万里" + ], + + "gesture": [ + "别离", + "离别", + "开阖", + "离合", + "穿梭", + "纵横", + "来去", + "连环", + "参合" + ], + + "action": [ + "抱元", + "守一", + "炼气", + "筑基", + "结丹", + "分神", + "合体", + "炼虚", + "洞真", + "洞虚", + "凌虚", + "易筋", + "洗髓", + "养志", + "散势", + "照神", + "照天", + "照妖", + "降魔", + "驱魔", + "荡魔", + "度难", + "度厄", + "辟邪", + "灭神", + "灭魔", + "伏虎", + "吞象", + "吞星", + "吸星", + "移星", + "摘星", + "问天", + "拂云", + "浮光", + "浮花", + "分花", + "掠影", + "化影", + "游身", + "拂柳", + "凌云", + "飞渡", + "追风", + "扫霞", + "听雨", + "听雪", + "踏雪", + "寻梅", + "葬花", + "望月", + "掷灵", + "缠丝", + "扫尘", + "离尘", + "御风", + "乘风", + "弄雾", + "兴云", + "消冰", + "陨玉", + "碎玉", + "斩铁", + "控鹤", + "定海", + "定风", + "定慧", + "定影", + "开碑", + "开弓", + "开天", + "开山", + "劈地", + "震岳", + "震山", + "担山", + "架海", + "养气", + "摧心", + "炼血", + "化血", + "化骨", + "化脉", + "化煞", + "化功", + "落阳", + "离梦", + + "绝情", + "问情", + + "诛佛", + "戮佛", + "困佛", + + "泣灵", + "化灵", + "叱灵", + + "斩妖", + "诛妖", + "戮妖", + "困妖", + "锁妖", + + "还魂", + "化魂", + "落魂", + "噬魂", + "失魂", + "追魂", + "断魂", + "摄魂", + "勾魂", + "戮魂", + "锁魂", + "封魂", + "养魂", + + "荡魔", + "镇魔", + "伏魔", + "诛魔", + "戮魔", + "困魔", + "绝魔", + "锁魔", + "封魔", + "养魔", + "护魔", + "守魔", + + "伏天", + "诛天", + "戮天", + "困天", + "绝天", + "锁天", + "封天", + "养天", + "护天", + "守天", + + "伏神", + "诛神", + "戮神", + "困神", + "绝神", + "锁神", + "封神", + "养神", + "护神", + "守神", + + "迷仙", + "伏仙", + "诛仙", + "戮仙", + "困仙", + "绝仙", + "锁仙", + "封仙", + "养仙", + "护仙", + "守仙", + + "擒龙", + "乘龙", + "御龙", + "降龙", + "伏龙", + "诛龙", + "戮龙", + "困龙", + "绝龙", + "锁龙", + "封龙", + "养龙", + "护龙", + "守龙" + ] +} diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/shared/spirit.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/shared/spirit.json" new file mode 100644 index 00000000..50fcd995 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/shared/spirit.json" @@ -0,0 +1 @@ +["秘", "精", "真", "宝", "古", "玄", "灵", "仙", "魔", "神", "鬼"] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/shared/strange.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/shared/strange.json" new file mode 100644 index 00000000..c2c4f61e --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/shared/strange.json" @@ -0,0 +1,139 @@ +[ + "招摇", + "堂庭", + "祝余", + "宪翼", + "陵居", + "留牛", + "箕尾", + "诸毗", + "长右", + "丹粟", + "尧光", + "瞿父", + "句余", + "浮玉", + "会稽", + "列涂", + "仆勾", + "咸阴", + "荆杞", + "区吴", + "鹿吴", + "蛊雕", + "漆吴", + "天虞", + "瞿如", + "丹穴", + "发爽", + "育遗", + "阳夹", + "灌湘", + "仑者", + "南禺", + "太华", + "符禺", + "大时", + "嶓冡", + "皋涂", + "无条", + "数斯", + "泰冒", + "数历", + "鹿台", + "龙首", + "鸟危", + "崇吾", + "博望", + "不周", + "蠃母", + "长留", + "积石", + "翼望", + "上申", + "诸次", + "白于", + "申首", + "中曲", + "单狐", + "肥遗", + "谯明", + "涿光", + "诸怀", + "领胡", + "求如", + "丹熏", + "边春", + "单张", + "灌题", + "潘侯", + "浑夕", + "狐岐", + "诸余", + "钩吾", + "梁渠", + "姑灌", + "敦题", + "龙侯", + "马成", + "天池", + "王屋", + "孟门", + "虫尾", + "彭毗", + "泰头", + "发鸠", + "题首", + "敦与", + "维龙", + "碣石", + "雁门", + "卢其", + "姑射", + "姑逢", + "空桑", + "诸钩", + "中父", + "胡射", + "宜苏", + "犀渠", + "蒙木", + "帝休", + "嘉荣", + "马嵬", + "敖岸", + "熊耳", + "鹿蹄", + "成侯", + "朝歌", + "长石", + "阳华", + "放皋", + "婴梁", + "宜诸", + "仁举", + "隅阳", + "支离", + "瑶碧", + "高前", + "乐马", + "虎首", + "丑阳", + "结匈", + "厌火", + "周饶", + "祝融", + "灭蒙", + "奇肱", + "柔利", + "勾芒", + "苍梧", + "高柳", + "服常", + "凤尾", + "凤麟", + "聚窟", + "鲜虞", + "义渠", + "陆浑" +] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/skill/numfix.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/skill/numfix.json" new file mode 100644 index 00000000..ecca579f --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/skill/numfix.json" @@ -0,0 +1,21 @@ +[ + "三", + "四", + "五", + "六", + "七", + "八", + "九", + "十", + "十一", + "十二", + "十五", + "十八", + "二十四", + "三十六", + "四十八", + "六十四", + "七十二", + "八十一", + "一百零八" +] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/skill/prefix.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/skill/prefix.json" new file mode 100644 index 00000000..7630e13b --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/skill/prefix.json" @@ -0,0 +1 @@ +["小", "大"] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/skill/skill.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/skill/skill.json" new file mode 100644 index 00000000..2e94ae78 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/skill/skill.json" @@ -0,0 +1,39 @@ +[ + "劲", + "气", + "气功", + "内功", + "玄功", + "吐纳术", + "导引术", + "轻身术", + "御剑术", + "御风术", + "轻功", + "遁术", + "擒拿手", + "神行法", + "纵跃功", + "步法", + "身法", + "拳", + "掌", + "指", + "爪", + "手", + "腿", + "步", + "刀", + "剑", + "枪", + "棍", + "心法", + "心诀", + "神术", + "神法", + "神功", + "功", + "诀", + "神通", + "绝技" +] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/talisman/material.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/talisman/material.json" new file mode 100644 index 00000000..19646a25 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/talisman/material.json" @@ -0,0 +1 @@ +["金", "银", "铁", "木", "竹", "石", "玉", "骨", "琉璃", "水晶"] diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/talisman/postfix.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/talisman/postfix.json" new file mode 100644 index 00000000..ce46fbcd --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/talisman/postfix.json" @@ -0,0 +1 @@ +{ "broken": ["未完成", "次品", "破损"], "handmade": ["仿制品", "赝品"] } diff --git "a/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/talisman/talisman.json" "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/talisman/talisman.json" new file mode 100644 index 00000000..71338ab2 --- /dev/null +++ "b/data/xiuxian/\344\277\256\344\273\231\351\232\217\346\234\272\345\220\215\350\257\215\346\225\260\346\215\256/talisman/talisman.json" @@ -0,0 +1,65 @@ +{ + "common": [ + "刀", + "剑", + "枪", + "棍", + "弓", + "矛", + "斧", + "锤", + "弩", + "鞭", + "戟", + "戈", + "环", + "钩", + "刺", + "爪", + "针", + "钉", + "镖", + "盾", + "衣", + "甲" + ], + "uncommon": [ + "索", + "链", + "网", + "锁", + "扇", + "罩", + "伞", + "鼓", + "琴", + "骰", + "袋", + "钟", + "梭", + "牌", + "盘", + "印", + "玺", + "葫芦" + ], + "rare": ["旗", "尺", "珠", "绫", "镯", "戒", "简"], + "epic": ["铃", "镜", "瓶", "图", "轮", "幡"], + "legendary": ["碑", "鼎", "塔", "亭", "舟", "车"], + "mythic": ["目", "眼", "睛", "牙", "角", "爪", "鳞", "翅", "羽"], + "exotic": [ + "雷", + "电", + "火", + "炎", + "焰", + "山", + "峰", + "石", + "晶", + "砂", + "冰", + "水", + "魂" + ] +} diff --git "a/data/xiuxian/\347\244\274\345\214\205/\347\244\274\345\214\205.json" "b/data/xiuxian/\347\244\274\345\214\205/\347\244\274\345\214\205.json" index bade9e18..2814badf 100644 --- "a/data/xiuxian/\347\244\274\345\214\205/\347\244\274\345\214\205.json" +++ "b/data/xiuxian/\347\244\274\345\214\205/\347\244\274\345\214\205.json" @@ -19,20 +19,20 @@ "name": "新手大礼包", "type": "礼包", "buff_1": 9937, - "type_1": "功法", + "type_1": "技能", "name_1": "一气化三清", "amount_1": 1, "buff_2": 8932, - "type_2": "神通", + "type_2": "技能", "name_2": "星宿劫", "amount_2": 1, "buff_3": 15408, - "type_3": "辅修功法", + "type_3": "技能", "name_3": "斗战诀", "amount_3": 1, - "buff_4": 7085, - "type_4": "法器", - "name_4": "冲天槊", + "buff_4": 15466, + "type_4": "装备", + "name_4": "少姜", "amount_4": 1, "buff_5": 15050, "type_5": "礼包", diff --git "a/data/xiuxian/\350\243\205\345\244\207/\346\263\225\345\231\250.json" "b/data/xiuxian/\350\243\205\345\244\207/\346\263\225\345\231\250.json" index 5cb42a29..dfa61eb6 100644 --- "a/data/xiuxian/\350\243\205\345\244\207/\346\263\225\345\231\250.json" +++ "b/data/xiuxian/\350\243\205\345\244\207/\346\263\225\345\231\250.json" @@ -806,7 +806,7 @@ "atk_buff": 0.7, "crit_buff": 0.6, "def_buff": 0, - "critatk": 0, + "critatk": 0.6, "zw": 0, "mp_buff": 0, "rank": -5, @@ -863,12 +863,12 @@ }, "15466": { "name": "少姜", - "atk_buff": 1, - "crit_buff": 1, + "atk_buff": 100, + "crit_buff": 100, "def_buff": 1, - "critatk": 1, + "critatk": 100, "zw": 0, - "mp_buff": 1, + "mp_buff": 100, "rank": -5, "level": "无上仙器", "type": "装备", @@ -884,5 +884,17 @@ "need_stone": "10000000000", "limit": 1 } + }, + "15467": { + "name": "荒", + "atk_buff": 0.9, + "crit_buff": 0.4, + "def_buff": 0.2, + "critatk": 1, + "zw": 0, + "mp_buff": 0.5, + "rank": -5, + "level": "无上仙器", + "type": "装备" } } \ No newline at end of file diff --git "a/data/xiuxian/\350\243\205\345\244\207/\351\230\262\345\205\267.json" "b/data/xiuxian/\350\243\205\345\244\207/\351\230\262\345\205\267.json" index 88473be3..040f0aa8 100755 --- "a/data/xiuxian/\350\243\205\345\244\207/\351\230\262\345\205\267.json" +++ "b/data/xiuxian/\350\243\205\345\244\207/\351\230\262\345\205\267.json" @@ -117,6 +117,15 @@ "level": "极品仙器", "type": "装备" }, + "6095": { + "name": "伽域封界", + "def_buff": 0.5, + "atk_buff": -0.5, + "crit_buff": 0, + "rank": -5, + "level": "无上仙器", + "type": "装备" + }, "11051": { "name": "女武神的叹息之壁", "def_buff": 0.32, @@ -332,14 +341,5 @@ "rank": -5, "level": "无上仙器", "type": "装备" - }, - "6095": { - "name": "伽域封界", - "def_buff": 0.5, - "atk_buff": -0.5, - "crit_buff": 0, - "rank": -5, - "level": "无上仙器", - "type": "装备" } } \ No newline at end of file diff --git a/nonebot_plugin_xiuxian_2/xiuxian/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/__init__.py index e66152c9..61f7d4bf 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/__init__.py @@ -12,7 +12,6 @@ from .xiuxian_config import XiuConfig from pathlib import Path from pkgutil import iter_modules -from nonebot.log import logger from nonebot import require, load_all_plugins, get_plugin_by_module_name from .xiuxian_utils.config import config as _config @@ -23,7 +22,7 @@ NICKNAME: str = list(DRIVER.config.nickname)[0] except Exception as e: logger.opt(colors=True).info(f"缺少超级用户配置文件,{e}!") - logger.opt(colors=True).info(f"请去.env.dev文件中设置超级用户QQ号以及nickname!") + logger.opt(colors=True).info("请去.env.dev文件中设置超级用户QQ号以及nickname!") NICKNAME = 'bot' try: @@ -37,13 +36,13 @@ try: put_bot_ = put_bot[0] -except: - logger.opt(colors=True).info(f"修仙插件没有配置put_bot,如果有多个qq和nb链接,请务必配置put_bot,具体介绍参考【风控帮助】!") +except IndexError: + logger.opt(colors=True).info("修仙插件没有配置put_bot,如果有多个qq和nb链接,请务必配置put_bot,具体介绍参考【风控帮助】!") require('nonebot_plugin_apscheduler') if get_plugin_by_module_name("xiuxian"): - logger.opt(colors=True).info(f"推荐直接加载 xiuxian 仓库文件夹") + logger.opt(colors=True).info("推荐直接加载 xiuxian 仓库文件夹") load_all_plugins( [ f"xiuxian.{module.name}" diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_back/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_back/__init__.py index cb705842..22bf6906 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_back/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_back/__init__.py @@ -27,11 +27,11 @@ from ..xiuxian_utils.utils import ( check_user, get_msg_pic, send_msg_handler, CommandObjectID, - Txt2Img, number_to + Txt2Img, number_to, handle_send ) from ..xiuxian_utils.xiuxian2_handle import ( - XiuxianDateManage, get_weapon_info_msg, get_armor_info_msg, - get_sec_msg, get_main_info_msg, get_sub_info_msg, UserBuffDate + XiuxianDataManager, get_weapon_info_msg, get_armor_info_msg, + get_sec_msg, get_main_info_msg, get_sub_info_msg, UserBuffData ) from ..xiuxian_config import XiuConfig, convert_rank @@ -46,7 +46,6 @@ auction_offer_time_count = 0 # 计算剩余时间 auction_offer_all_count = 0 # 控制线程等待时间 auction_time_config = config['拍卖会定时参数'] # 定时配置 -sql_message = XiuxianDateManage() # sql类 # 定时任务 set_auction_by_scheduler = require("nonebot_plugin_apscheduler").scheduler reset_day_num_scheduler = require("nonebot_plugin_apscheduler").scheduler @@ -71,7 +70,7 @@ xiuxian_sone = on_fullmatch("灵石", priority=4, permission=GROUP, block=True) chakan_wupin = on_command("查看修仙界物品", priority=25, permission=GROUP, block=True) -__back_help__ = f""" +__back_help__ = """ 指令: 1、我的背包、我的物品:查看自身背包前196个物品的信息 2、使用+物品名字:使用物品,可批量使用 @@ -83,7 +82,7 @@ 8、提交拍卖品:提交拍卖品 物品 金额,上架背包内的物品,最低金额随意,可批量上架(需要超管重启机器人) 9、系统坊市上架:系统坊市上架 物品 金额,上架任意存在的物品,超管权限 10、坊市下架+物品编号:下架坊市内的物品,管理员和群主可以下架任意编号的物品! -11、群交流会开启、关闭:开启/关闭拍卖行功能,管理员指令,注意:会在机器人所在的全部已开启此功能的群内通报拍卖消息 +11、群拍卖会开启、关闭:开启/关闭拍卖行功能,管理员指令,注意:会在机器人所在的全部已开启此功能的群内通报拍卖消息 12、拍卖+金额:对本次拍卖会的物品进行拍卖 13、炼金+物品名字:将物品炼化为灵石,支持批量炼金和绑定丹药炼金 14、背包帮助:获取背包帮助指令 @@ -97,8 +96,8 @@ # 重置丹药每日使用次数 @reset_day_num_scheduler.scheduled_job("cron", hour=0, minute=0, ) async def reset_day_num_scheduler_(): - sql_message.day_num_reset() - logger.opt(colors=True).info(f"每日丹药使用次数重置成功!") + await XiuxianDataManager().day_num_reset() + logger.opt(colors=True).info("每日丹药使用次数重置成功!") # 定时任务生成拍卖会 @@ -107,7 +106,7 @@ async def set_auction_by_scheduler_(): global auction, auction_offer_flag, auction_offer_all_count, auction_offer_time_count if groups: if auction: - logger.opt(colors=True).info(f"本群已存在一场拍卖会,已清除!") + logger.opt(colors=True).info("本群已存在一场拍卖会,已清除!") auction = {} auction_items = [] @@ -136,13 +135,13 @@ async def set_auction_by_scheduler_(): random.shuffle(auction_items) logger.opt(colors=True).info("野生的大世界定时拍卖会出现了!!!,请管理员在这个时候不要重启机器人") - msg = f"大世界定时拍卖会出现了!!!\n" - msg = f"请各位道友稍作准备,拍卖即将开始...\n" + msg = "大世界定时拍卖会出现了!!!\n" + msg = "请各位道友稍作准备,拍卖即将开始...\n" msg += f"本场拍卖会共有{len(auction_items)}件物品,将依次拍卖,分别是:\n" for idx, (auction_id, item_quantity, start_price, is_user_auction) in enumerate(auction_items): item_name = items.get_data_by_item_id(auction_id)['name'] if is_user_auction: - owner_info = sql_message.get_user_info_with_id(get_user_auction_price_by_id(auction_id)['user_id']) + owner_info = await XiuxianDataManager().get_user_infos_by_ids(get_user_auction_price_by_id(auction_id)['user_id']) owner_name = owner_info['user_name'] msg += f"{idx + 1}号:{item_name}x{item_quantity}(由{owner_name}道友提供)\n" else: @@ -151,11 +150,7 @@ async def set_auction_by_scheduler_(): for gid in groups: bot = await assign_bot_group(group_id=gid) try: - if XiuConfig().img: - pic = await get_msg_pic(msg) - await bot.send_group_msg(group_id=int(gid), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(gid), message=msg) + await handle_send(bot, gid, msg) except ActionFailed: continue @@ -223,7 +218,7 @@ async def set_auction_by_scheduler_(): if auction['user_id'] == 0: msg = f"很可惜,{auction['name']}流拍了\n" if i + 1 == len(auction_items): - msg += f"本场拍卖会到此结束,开始整理拍卖会结果,感谢各位道友参与!" + msg += "本场拍卖会到此结束,开始整理拍卖会结果,感谢各位道友参与!" for gid in groups: bot = await assign_bot_group(group_id=gid) @@ -239,11 +234,11 @@ async def set_auction_by_scheduler_(): auction = {} continue - user_info = sql_message.get_user_info_with_id(auction['user_id']) - msg = f"(拍卖锤落下)!!!\n" + user_info = await XiuxianDataManager().get_user_infos_by_ids(auction['user_id']) + msg = "(拍卖锤落下)!!!\n" msg += f"恭喜来自群{auction['group_id']}的{user_info['user_name']}道友成功拍下:{auction['type']}-{auction['name']}x{auction['quantity']},将在拍卖会结算后送到您手中。\n" if i + 1 == len(auction_items): - msg += f"本场拍卖会到此结束,开始整理拍卖会结果,感谢各位道友参与!" + msg += "本场拍卖会到此结束,开始整理拍卖会结果,感谢各位道友参与!" auction_results.append((auction_id, user_info['user_id'], auction['group_id'], auction_info['type'], auction['now_price'], auction['quantity'])) @@ -264,31 +259,32 @@ async def set_auction_by_scheduler_(): await asyncio.sleep(random.randint(5, 30)) # 拍卖会结算 - logger.opt(colors=True).info(f"野生的大世界定时拍卖会结束了!!!") - end_msg = f"本场拍卖会结束!感谢各位道友的参与。\n拍卖结果整理如下:\n" + logger.opt(colors=True).info("野生的大世界定时拍卖会结束了!!!") + end_msg = "本场拍卖会结束!感谢各位道友的参与。\n拍卖结果整理如下:\n" for idx, (auction_id, user_id, group_id, item_type, final_price, quantity) in enumerate(auction_results): item_name = items.get_data_by_item_id(auction_id)['name'] - final_user_info = sql_message.get_user_info_with_id(user_id) - if user_id: - if final_user_info['stone'] < (int(final_price) * quantity): - end_msg += f"{idx + 1}号拍卖品:{item_name}x{quantity} - 道友{final_user_info['user_name']}的灵石不足,流拍了\n" - else: - sql_message.update_ls(user_id, int(final_price) * quantity, 2) - sql_message.send_back(user_id, auction_id, item_name, item_type, quantity) - end_msg += f"{idx + 1}号拍卖品:{item_name}x{quantity}由群{group_id}的{final_user_info['user_name']}道友成功拍下\n" + if user_id is None: + end_msg += f"{idx + 1}号拍卖品:{item_name}x{quantity} - 流拍了\n" + continue + + final_user_info = await XiuxianDataManager().get_user_infos_by_ids(user_id) + if final_user_info['stone'] < (int(final_price) * quantity): + end_msg += f"{idx + 1}号拍卖品:{item_name}x{quantity} - 道友{final_user_info['user_name']}的灵石不足,流拍了\n" + else: + await XiuxianDataManager().update_ls(user_id, int(final_price) * quantity, 1) + await XiuxianDataManager().send_back(user_id, auction_id, item_name, item_type, quantity) + end_msg += f"{idx + 1}号拍卖品:{item_name}x{quantity}由群{group_id}的{final_user_info['user_name']}道友成功拍下\n" - user_auction_info = get_user_auction_price_by_id(auction_id) - if user_auction_info: - seller_id = user_auction_info['user_id'] - auction_earnings = int(final_price) * quantity * 0.7 # 收个手续费 - sql_message.update_ls(seller_id, auction_earnings, 1) + user_auction_info = get_user_auction_price_by_id(auction_id) + if user_auction_info: + seller_id = user_auction_info['user_id'] + auction_earnings = int(final_price) * quantity * 0.7 # 收个手续费 + await XiuxianDataManager().update_ls(seller_id, auction_earnings, 0) - remove_auction_item(auction_id) + remove_auction_item(auction_id) - auction = {} - auction_offer_time_count = 0 - else: - end_msg += f"{idx + 1}号拍卖品:{item_name}x{quantity} - 流拍了\n" + auction = {} + auction_offer_time_count = 0 for gid in groups: bot = await assign_bot_group(group_id=gid) @@ -329,20 +325,12 @@ async def back_help_(bot: Bot, event: GroupMessageEvent, session_id: int = Comma async def xiuxian_sone_(bot: Bot, event: GroupMessageEvent): """我的灵石信息""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await xiuxian_sone.finish() msg = f"当前灵石:{user_info['stone']}({number_to(user_info['stone'])})" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await xiuxian_sone.finish() @@ -354,13 +342,9 @@ async def buy_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()) """购物""" bot, send_group_id = await assign_bot(bot=bot, event=event) async with buy_lock: - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await buy.finish() user_id = user_info['user_id'] group_id = str(event.group_id) @@ -368,21 +352,13 @@ async def buy_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()) if shop_data[group_id] == {}: msg = "坊市目前空空如也!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await buy.finish() input_args = args.extract_plain_text().strip().split() if len(input_args) < 1: # 没有输入任何参数 msg = "请输入正确指令!例如:坊市购买 物品编号 数量" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await buy.finish() else: try: @@ -403,7 +379,7 @@ async def buy_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()) except ValueError as e: msg = f"{str(e)}" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -413,34 +389,22 @@ async def buy_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()) goods_stock = goods_info.get('stock', 1) if user_info['stone'] < goods_price: msg = '没钱还敢来买东西!!' - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await buy.finish() elif int(user_id) == int(shop_data[group_id][str(arg)]['user_id']): msg = "道友自己的东西就不要自己购买啦!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await buy.finish() elif purchase_quantity > goods_stock and shop_user_id != 0: msg = "库存不足,无法购买所需数量!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) else: shop_goods_name = shop_data[group_id][str(arg)]['goods_name'] shop_user_name = shop_data[group_id][str(arg)]['user_name'] shop_goods_id = shop_data[group_id][str(arg)]['goods_id'] shop_goods_type = shop_data[group_id][str(arg)]['goods_type'] - sql_message.update_ls(user_id, goods_price, 2) - sql_message.send_back(user_id, shop_goods_id, shop_goods_name, shop_goods_type, purchase_quantity) + await XiuxianDataManager().update_ls(user_id, goods_price, 1) + await XiuxianDataManager().send_back(user_id, shop_goods_id, shop_goods_name, shop_goods_type, purchase_quantity) save_shop(shop_data) if shop_user_id == 0: # 0为系统 @@ -454,14 +418,10 @@ async def buy_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()) service_charge = int(goods_price * 0.1) # 手续费10% give_stone = goods_price - service_charge msg = f"道友成功购买{purchase_quantity}个{shop_user_name}道友寄售的{shop_goods_name},消耗灵石{goods_price}枚,坊市收取手续费:{service_charge}枚灵石!" - sql_message.update_ls(shop_user_id, give_stone, 1) + await XiuxianDataManager().update_ls(shop_user_id, give_stone, 0) shop_data[group_id] = reset_dict_num(shop_data[group_id]) save_shop(shop_data) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await buy.finish() @@ -469,13 +429,9 @@ async def buy_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()) async def shop_(bot: Bot, event: GroupMessageEvent): """坊市查看""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop.finish() group_id = str(event.group_id) @@ -483,11 +439,7 @@ async def shop_(bot: Bot, event: GroupMessageEvent): data_list = [] if shop_data[group_id] == {}: msg = "坊市目前空空如也!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop.finish() for k, v in shop_data[group_id].items(): @@ -498,8 +450,8 @@ async def shop_(bot: Bot, event: GroupMessageEvent): msg += f"拥有人:{v['user_name']}道友\n" msg += f"数量:{v['stock']}\n" else: - msg += f"系统出售\n" - msg += f"数量:无限\n" + msg += "系统出售\n" + msg += "数量:无限\n" data_list.append(msg) await send_msg_handler(bot, event, '坊市', bot.self_id, data_list) await shop.finish() @@ -509,14 +461,11 @@ async def shop_(bot: Bot, event: GroupMessageEvent): async def shop_added_by_admin_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """系统上架坊市""" bot, send_group_id = await assign_bot(bot=bot, event=event) + isUser, user_info, msg = await check_user(event) args = args.extract_plain_text().split() if not args: msg = "请输入正确指令!例如:系统坊市上架 物品 金额" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added_by_admin.finish() goods_name = args[0] goods_id = -1 @@ -528,50 +477,29 @@ async def shop_added_by_admin_(bot: Bot, event: GroupMessageEvent, args: Message continue if goods_id == -1: msg = "不存在物品:{goods_name}的信息,请检查名字是否输入正确!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added_by_admin.finish() price = None try: price = args[1] except LookupError: msg = "请输入正确指令!例如:系统坊市上架 物品 金额" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added_by_admin.finish() try: price = int(price) if price < 0: msg = "请不要设置负数!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added_by_admin.finish() except LookupError: msg = "请输入正确的金额!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added_by_admin.finish() try: - var = args[2] msg = "请输入正确指令!例如:系统坊市上架 物品 金额" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added_by_admin.finish() except LookupError: pass @@ -593,11 +521,7 @@ async def shop_added_by_admin_(bot: Bot, event: GroupMessageEvent, args: Message shop_data[group_id][id_]['user_name'] = '系统' save_shop(shop_data) msg = f"物品:{goods_name}成功上架坊市,金额:{price}枚灵石!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added_by_admin.finish() @@ -605,13 +529,9 @@ async def shop_added_by_admin_(bot: Bot, event: GroupMessageEvent, args: Message async def shop_added_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """用户上架坊市""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added.finish() user_id = user_info['user_id'] args = args.extract_plain_text().split() @@ -621,11 +541,7 @@ async def shop_added_(bot: Bot, event: GroupMessageEvent, args: Message = Comman if len(args) == 0: # 没有输入任何参数 msg = "请输入正确指令!例如:坊市上架 物品 可选参数为(金额 数量)" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added.finish() elif len(args) == 1: # 只提供了物品名称 @@ -639,14 +555,10 @@ async def shop_added_(bot: Bot, event: GroupMessageEvent, args: Message = Comman # 提供了物品名称、价格和数量 goods_name, price_str, quantity_str = args[0], args[1], args[2] - back_msg = sql_message.get_back_msg(user_id) # 背包sql信息,dict + back_msg = await XiuxianDataManager().get_back_msg(user_id) # 背包sql信息,dict if back_msg is None: msg = "道友的背包空空如也!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added.finish() in_flag = False # 判断指令是否正确,道具是否在背包内 goods_id = None @@ -665,11 +577,7 @@ async def shop_added_(bot: Bot, event: GroupMessageEvent, args: Message = Comman break if not in_flag: msg = f"请检查该道具 {goods_name} 是否在背包内!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added.finish() price = None @@ -680,11 +588,7 @@ async def shop_added_(bot: Bot, event: GroupMessageEvent, args: Message = Comman raise ValueError("价格必须为正数!") except ValueError as e: msg = f"请输入正确的金额: {str(e)}" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added.finish() # 解析数量 try: @@ -693,40 +597,24 @@ async def shop_added_(bot: Bot, event: GroupMessageEvent, args: Message = Comman raise ValueError("数量必须为正数或者小于等于你拥有的物品数!") except ValueError as e: msg = f"请输入正确的数量: {str(e)}" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added.finish() price = max(price, 500000) # 最低价格为50w if goods_type == "装备" and int(goods_state) == 1 and int(goods_num) == 1: msg = f"装备:{goods_name}已经被道友装备在身,无法上架!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added.finish() if int(goods_num) <= int(goods_bind_num): msg = "该物品是绑定物品,无法上架!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added.finish() if goods_type == "聚灵旗" or goods_type == "炼丹炉": if user_info['root'] == "器师" : pass else: msg = "道友职业无法上架!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added.finish() group_id = str(event.group_id) @@ -740,11 +628,7 @@ async def shop_added_(bot: Bot, event: GroupMessageEvent, args: Message = Comman pass if num >= 5 : msg = "每人只可上架五个物品!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added.finish() if shop_data == {}: @@ -760,14 +644,10 @@ async def shop_added_(bot: Bot, event: GroupMessageEvent, args: Message = Comman 'user_name': user_info['user_name'], 'stock': quantity, # 物品数量 } - sql_message.update_back_j(user_id, goods_id, num = quantity) + await XiuxianDataManager().update_back_j(user_id, goods_id, num = quantity) save_shop(shop_data) msg = f"物品:{goods_name}成功上架坊市,金额:{price}枚灵石,数量{quantity}!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_added.finish() @@ -775,33 +655,21 @@ async def shop_added_(bot: Bot, event: GroupMessageEvent, args: Message = Comman async def goods_re_root_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """炼金""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await goods_re_root.finish() user_id = user_info['user_id'] args = args.extract_plain_text().split() if args is None: msg = "请输入要炼化的物品!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await goods_re_root.finish() goods_name = args[0] - back_msg = sql_message.get_back_msg(user_id) # 背包sql信息,list(back) + back_msg = await XiuxianDataManager().get_back_msg(user_id) # 背包sql信息,list(back) if back_msg is None: msg = "道友的背包空空如也!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await goods_re_root.finish() in_flag = False # 判断指令是否正确,道具是否在背包内 goods_id = None @@ -818,53 +686,33 @@ async def goods_re_root_(bot: Bot, event: GroupMessageEvent, args: Message = Com break if not in_flag: msg = f"请检查该道具 {goods_name} 是否在背包内!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await goods_re_root.finish() if goods_type == "装备" and int(goods_state) == 1 and int(goods_num) == 1: msg = f"装备:{goods_name}已经被道友装备在身,无法炼金!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await goods_re_root.finish() - if get_item_msg_rank(goods_id) == 520: + if await get_item_msg_rank(goods_id) == 520: msg = "此类物品不支持!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await goods_re_root.finish() try: if 1 <= int(args[1]) <= int(goods_num): num = int(args[1]) - except: + except ValueError: num = 1 - price = int((convert_rank('江湖好手')[0] + 5) * 100000 - get_item_msg_rank(goods_id) * 100000) * num + price = int((convert_rank('江湖好手')[0] + 5) * 100000 - await get_item_msg_rank(goods_id) * 100000) * num if price <= 0: msg = f"物品:{goods_name}炼金失败,凝聚{price}枚灵石,记得通知晓楠!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await goods_re_root.finish() - sql_message.update_back_j(user_id, goods_id, num=num) - sql_message.update_ls(user_id, price, 1) + await XiuxianDataManager().update_back_j(user_id, goods_id, num=num) + await XiuxianDataManager().update_ls(user_id, price, 0) msg = f"物品:{goods_name} 数量:{num} 炼金成功,凝聚{price}枚灵石!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await goods_re_root.finish() @@ -872,24 +720,16 @@ async def goods_re_root_(bot: Bot, event: GroupMessageEvent, args: Message = Com async def shop_off_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """下架商品""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_off.finish() user_id = user_info['user_id'] group_id = str(event.group_id) shop_data = get_shop_data(group_id) if shop_data[group_id] == {}: msg = "坊市目前空空如也!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_off.finish() arg = args.extract_plain_text().strip() @@ -898,34 +738,22 @@ async def shop_off_(bot: Bot, event: GroupMessageEvent, args: Message = CommandA arg = int(arg) if arg <= 0 or arg > len(shop_data[group_id]): msg = "请输入正确的编号!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_off.finish() except ValueError: msg = "请输入正确的编号!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_off.finish() if shop_data[group_id][str(arg)]['user_id'] == user_id: - sql_message.send_back(user_id, shop_data[group_id][str(arg)]['goods_id'], + await XiuxianDataManager().send_back(user_id, shop_data[group_id][str(arg)]['goods_id'], shop_data[group_id][str(arg)]['goods_name'], shop_data[group_id][str(arg)]['goods_type'], shop_data[group_id][str(arg)]['stock']) msg = f"成功下架物品:{shop_data[group_id][str(arg)]['goods_name']}!" del shop_data[group_id][str(arg)] shop_data[group_id] = reset_dict_num(shop_data[group_id]) save_shop(shop_data) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_off.finish() elif event.sender.role == "admin" or event.sender.role == "owner" or event.get_user_id() in bot.config.superusers: @@ -934,14 +762,10 @@ async def shop_off_(bot: Bot, event: GroupMessageEvent, args: Message = CommandA del shop_data[group_id][str(arg)] shop_data[group_id] = reset_dict_num(shop_data[group_id]) save_shop(shop_data) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_off.finish() else: - sql_message.send_back(shop_data[group_id][str(arg)]['user_id'], shop_data[group_id][str(arg)]['goods_id'], + await XiuxianDataManager().send_back(shop_data[group_id][str(arg)]['user_id'], shop_data[group_id][str(arg)]['goods_id'], shop_data[group_id][str(arg)]['goods_name'], shop_data[group_id][str(arg)]['goods_type'], shop_data[group_id][str(arg)]['stock']) msg1 = f"道友上架的{shop_data[group_id][str(arg)]['stock']}个{shop_data[group_id][str(arg)]['goods_name']}已被管理员{user_info['user_name']}下架!" @@ -959,11 +783,7 @@ async def shop_off_(bot: Bot, event: GroupMessageEvent, args: Message = CommandA else: msg = "这东西不是你的!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_off.finish() @@ -971,20 +791,16 @@ async def shop_off_(bot: Bot, event: GroupMessageEvent, args: Message = CommandA async def auction_withdraw_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """用户撤回拍卖品""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await auction_withdraw.finish() group_id = str(event.group_id) if group_id not in groups: msg = '本群尚未开启拍卖会功能,请联系管理员开启!' if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(group_id), message=msg) @@ -994,47 +810,31 @@ async def auction_withdraw_(bot: Bot, event: GroupMessageEvent, args: Message = user_auctions = config.get('user_auctions', []) if not user_auctions: - msg = f"拍卖会目前没有道友提交的物品!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "拍卖会目前没有道友提交的物品!" + await handle_send(bot, event, send_group_id, msg) await auction_withdraw.finish() arg = args.extract_plain_text().strip() auction_index = int(arg) - 1 if auction_index < 0 or auction_index >= len(user_auctions): - msg = f"请输入正确的编号" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请输入正确的编号" + await handle_send(bot, event, send_group_id, msg) await auction_withdraw.finish() auction = user_auctions[auction_index] goods_name, details = list(auction.items())[0] if details['user_id'] != user_info['user_id']: - msg = f"这不是你的拍卖品!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "这不是你的拍卖品!" + await handle_send(bot, event, send_group_id, msg) await auction_withdraw.finish() - sql_message.send_back(details['user_id'], details['id'], goods_name, details['goods_type'], details['quantity']) + await XiuxianDataManager().send_back(details['user_id'], details['id'], goods_name, details['goods_type'], details['quantity']) user_auctions.pop(auction_index) config['user_auctions'] = user_auctions savef_auction(config) msg = f"成功撤回拍卖品:{goods_name}x{details['quantity']}!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await auction_withdraw.finish() @@ -1046,16 +846,12 @@ async def main_back_(bot: Bot, event: GroupMessageEvent): "remake", "day_num", "all_num", "action_time", "state"] """ bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await main_back.finish() user_id = user_info['user_id'] - msg = get_user_main_back_msg(user_id) + msg = await get_user_main_back_msg(user_id) if len(msg) >= 98: #背包更新 # 将第一条消息和第二条消息合并为一条消息 @@ -1083,25 +879,17 @@ async def no_use_zb_(bot: Bot, event: GroupMessageEvent, args: Message = Command "remake", "day_num", "all_num", "action_time", "state"] """ bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await no_use_zb.finish() user_id = user_info['user_id'] arg = args.extract_plain_text().strip() - back_msg = sql_message.get_back_msg(user_id) # 背包sql信息,list(back) + back_msg = await XiuxianDataManager().get_back_msg(user_id) # 背包sql信息,list(back) if back_msg is None: msg = "道友的背包空空如也!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await no_use_zb.finish() in_flag = False # 判断指令是否正确,道具是否在背包内 goods_id = None @@ -1114,44 +902,28 @@ async def no_use_zb_(bot: Bot, event: GroupMessageEvent, args: Message = Command break if not in_flag: msg = f"请检查道具 {arg} 是否在背包内!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await no_use_zb.finish() if goods_type == "装备": - if not check_equipment_can_use(user_id, goods_id): - sql_str, item_type = get_no_use_equipment_sql(user_id, goods_id) + if not await check_equipment_can_use(user_id, goods_id): + sql_str, item_type = await get_no_use_equipment_sql(user_id, goods_id) for sql in sql_str: - sql_message.update_back_equipment(sql) + await XiuxianDataManager().update_back_equipment(sql) if item_type == "法器": - sql_message.updata_user_faqi_buff(user_id, 0) + await XiuxianDataManager().updata_user_faqi_buff(user_id, 0) if item_type == "防具": - sql_message.updata_user_armor_buff(user_id, 0) + await XiuxianDataManager().updata_user_armor_buff(user_id, 0) msg = f"成功卸载装备{arg}!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await no_use_zb.finish() else: msg = "装备没有被使用,无法卸载!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await no_use_zb.finish() else: msg = "目前只支持卸载装备!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await no_use_zb.finish() @@ -1162,25 +934,17 @@ async def use_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()) "remake", "day_num", "all_num", "action_time", "state"] """ bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await use.finish() user_id = user_info['user_id'] args = args.extract_plain_text().split() arg = args[0] # - back_msg = sql_message.get_back_msg(user_id) # 背包sql信息,dict + back_msg = await XiuxianDataManager().get_back_msg(user_id) # 背包sql信息,dict if back_msg is None: msg = "道友的背包空空如也!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await use.finish() in_flag = False # 判断指令是否正确,道具是否在背包内 goods_id = None @@ -1195,70 +959,54 @@ async def use_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()) break if not in_flag: msg = f"请检查该道具 {arg} 是否在背包内!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await use.finish() if goods_type == "装备": - if not check_equipment_can_use(user_id, goods_id): + if not await check_equipment_can_use(user_id, goods_id): msg = "该装备已被装备,请勿重复装备!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await use.finish() else: # 可以装备 - sql_str, item_type = get_use_equipment_sql(user_id, goods_id) + sql_str, item_type = await get_use_equipment_sql(user_id, goods_id) for sql in sql_str: - sql_message.update_back_equipment(sql) + await XiuxianDataManager().update_back_equipment(sql) if item_type == "法器": - sql_message.updata_user_faqi_buff(user_id, goods_id) + await XiuxianDataManager().updata_user_faqi_buff(user_id, goods_id) if item_type == "防具": - sql_message.updata_user_armor_buff(user_id, goods_id) + await XiuxianDataManager().updata_user_armor_buff(user_id, goods_id) msg = f"成功装备{arg}!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await use.finish() elif goods_type == "技能": - user_buff_info = UserBuffDate(user_id).BuffInfo + user_buff_info = await UserBuffData(user_id).BuffInfo skill_info = items.get_data_by_item_id(goods_id) skill_type = skill_info['item_type'] if skill_type == "神通": - if int(user_buff_info['sec_buff']) == int(goods_id): + if int(user_buff_info['ultimate_skill']) == int(goods_id): msg = f"道友已学会该神通:{skill_info['name']},请勿重复学习!" else: # 学习sql - sql_message.update_back_j(user_id, goods_id) - sql_message.updata_user_sec_buff(user_id, goods_id) + await XiuxianDataManager().update_back_j(user_id, goods_id) + await XiuxianDataManager().updata_user_sec_buff(user_id, goods_id) msg = f"恭喜道友学会神通:{skill_info['name']}!" elif skill_type == "功法": - if int(user_buff_info['main_buff']) == int(goods_id): + if int(user_buff_info['main_skill']) == int(goods_id): msg = f"道友已学会该功法:{skill_info['name']},请勿重复学习!" else: # 学习sql - sql_message.update_back_j(user_id, goods_id) - sql_message.updata_user_main_buff(user_id, goods_id) + await XiuxianDataManager().update_back_j(user_id, goods_id) + await XiuxianDataManager().updata_user_main_buff(user_id, goods_id) msg = f"恭喜道友学会功法:{skill_info['name']}!" elif skill_type == "辅修功法": #辅修功法1 - if int(user_buff_info['sub_buff']) == int(goods_id): + if int(user_buff_info['support_skill']) == int(goods_id): msg = f"道友已学会该辅修功法:{skill_info['name']},请勿重复学习!" else:#学习sql - sql_message.update_back_j(user_id, goods_id) - sql_message.updata_user_sub_buff(user_id, goods_id) + await XiuxianDataManager().update_back_j(user_id, goods_id) + await XiuxianDataManager().updata_user_sub_buff(user_id, goods_id) msg = f"恭喜道友学会辅修功法:{skill_info['name']}!" else: msg = "发生未知错误!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await use.finish() elif goods_type == "丹药": num = 1 @@ -1268,7 +1016,7 @@ async def use_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()) elif len(args) > 1 and int(args[1]) > int(goods_num): msg = f"道友背包中的{arg}数量不足,当前仅有{goods_num}个!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -1276,11 +1024,7 @@ async def use_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()) except ValueError: num = 1 msg = check_use_elixir(user_id, goods_id, num) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await use.finish() elif goods_type =="神物": num = 1 @@ -1290,7 +1034,7 @@ async def use_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()) elif len(args) > 1 and int(args[1]) > int(goods_num): msg = f"道友背包中的{arg}数量不足,当前仅有{goods_num}个!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -1298,27 +1042,23 @@ async def use_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()) except ValueError: num = 1 goods_info = items.get_data_by_item_id(goods_id) - user_info = sql_message.get_user_info_with_id(user_id) + user_info = await XiuxianDataManager().get_user_infos_by_ids(user_id) user_rank = convert_rank(user_info['level'])[0] goods_rank = goods_info['rank'] goods_name = goods_info['name'] if goods_rank < user_rank: # 使用限制 msg = f"神物:{goods_name}的使用境界为{goods_info['境界']}以上,道友不满足使用条件!" else: - exp = goods_info['buff'] * num + exp = goods_info['buf'] * num user_hp = int(user_info['hp'] + (exp / 2)) user_mp = int(user_info['mp'] + exp) user_atk = int(user_info['atk'] + (exp / 10)) - sql_message.update_exp(user_id, exp) - sql_message.update_power2(user_id) # 更新战力 - sql_message.update_user_attribute(user_id, user_hp, user_mp, user_atk) # 这种事情要放在update_exp方法里 - sql_message.update_back_j(user_id, goods_id, num=num, use_key=1) + await XiuxianDataManager().update_exp(user_id, exp, 0) + await XiuxianDataManager().update_power2(user_id) # 更新战力 + await XiuxianDataManager().update_user_attribute(user_id, user_hp, user_mp, user_atk) # 这种事情要放在update_exp方法里 + await XiuxianDataManager().update_back_j(user_id, goods_id, num=num, use_key=1) msg = f"道友成功使用神物:{goods_name} {num}个 ,修为增加{exp}点!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await use.finish() elif goods_type =="礼包": @@ -1329,7 +1069,7 @@ async def use_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()) elif len(args) > 1 and int(args[1]) > int(goods_num): msg = f"道友背包中的{arg}数量不足,当前仅有{goods_num}个!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -1338,7 +1078,7 @@ async def use_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()) num = 1 goods_info = items.get_data_by_item_id(goods_id) - user_info = sql_message.get_user_info_with_id(user_id) + user_info = await XiuxianDataManager().get_user_infos_by_ids(user_id) goods_name = goods_info['name'] msg_parts = [] @@ -1356,8 +1096,8 @@ async def use_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()) goods_amount = goods_info.get(amount_key, 1) * num if goods_name == "灵石": - key = 1 if goods_amount > 0 else 2 - sql_message.update_ls(user_id, abs(goods_amount), key) + key = 0 if goods_amount > 0 else 1 + await XiuxianDataManager().update_ls(user_id, abs(goods_amount), key) if goods_amount > 0: msg_parts.append(f"获得灵石{number_to(goods_amount)}枚!\n") else: @@ -1366,56 +1106,40 @@ async def use_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()) buff_id = goods_info.get(buff_key) goods_type = goods_info.get(type_key) if buff_id is not None: - sql_message.send_back(user_id, buff_id, goods_name, goods_type, goods_amount, 1) + await XiuxianDataManager().send_back(user_id, buff_id, goods_name, goods_type, goods_amount, 1) msg_parts.append(f"获得{goods_name}{goods_amount}个\n") i += 1 - sql_message.update_back_j(user_id, goods_id, num, 0) + await XiuxianDataManager().update_back_j(user_id, goods_id, num, 0) msg = f"道友打开了{num}个{goods_info['name']}:\n" + "".join(msg_parts) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await use.finish() elif goods_type == "聚灵旗": - msg = get_use_jlq_msg(user_id, goods_id) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = await get_use_jlq_msg(user_id, goods_id) + await handle_send(bot, event, send_group_id, msg) await use.finish() else: msg = '该类型物品调试中,未开启!' - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await use.finish() @auction_view.handle(parameterless=[Cooldown(at_sender=False, isolate_level=CooldownIsolateLevel.GROUP)]) async def auction_view_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """查看拍卖会物品""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) group_id = str(event.group_id) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await auction_view.finish() if group_id not in groups: msg = '本群尚未开启拍卖会功能,请联系管理员开启!' if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(group_id), message=msg) @@ -1427,23 +1151,19 @@ async def auction_view_(bot: Bot, event: GroupMessageEvent, args: Message = Comm if not user_auctions: msg = "拍卖会目前没有道友提交的物品!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await auction_view.finish() auction_list_msg = "拍卖会物品列表:\n" for idx, auction in enumerate(user_auctions): for goods_name, details in auction.items(): - user_info = sql_message.get_user_info_with_id(details['user_id']) + user_info = await XiuxianDataManager().get_user_infos_by_ids(details['user_id']) auction_list_msg += f"编号: {idx + 1}\n物品名称: {goods_name}\n物品类型:{details['goods_type']}\n所有者:{user_info['user_name']}\n底价: {details['start_price']} 枚灵石\n数量: {details['quantity']}\n" auction_list_msg += "☆------------------------------☆\n" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + auction_list_msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + auction_list_msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=auction_list_msg) @@ -1456,10 +1176,10 @@ async def creat_auction_(bot: Bot, event: GroupMessageEvent): global auction, auction_offer_flag, auction_offer_all_count, auction_offer_time_count group_id = str(event.group_id) bot = await assign_bot_group(group_id=group_id) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(group_id), message=msg) @@ -1468,7 +1188,7 @@ async def creat_auction_(bot: Bot, event: GroupMessageEvent): if group_id not in groups: msg = '本群尚未开启拍卖会功能,请联系管理员开启!' if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(group_id), message=msg) @@ -1477,7 +1197,7 @@ async def creat_auction_(bot: Bot, event: GroupMessageEvent): if auction: msg = "本群已存在一场拍卖会,请等待拍卖会结束!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(group_id), message=msg) @@ -1502,9 +1222,9 @@ async def creat_auction_(bot: Bot, event: GroupMessageEvent): item_quantity = random.randint(1, 3) # 如果是丹药的话随机挑1-3个 auction_items.append((auction_id, item_quantity, get_auction_price_by_id(auction_id)['start_price'], False)) except LookupError: - msg = f"获取不到拍卖物品的信息,请检查配置文件!" + msg = "获取不到拍卖物品的信息,请检查配置文件!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(group_id), message=msg) @@ -1513,12 +1233,12 @@ async def creat_auction_(bot: Bot, event: GroupMessageEvent): # 打乱拍卖品顺序 random.shuffle(auction_items) - msg = f"请各位道友稍作准备,拍卖即将开始...\n" + msg = "请各位道友稍作准备,拍卖即将开始...\n" msg += f"本场拍卖会共有{len(auction_items)}件物品,将依次拍卖,分别是:\n" for idx, (auction_id, item_quantity, start_price, is_user_auction) in enumerate(auction_items): item_name = items.get_data_by_item_id(auction_id)['name'] if is_user_auction: - owner_info = sql_message.get_user_info_with_id(get_user_auction_price_by_id(auction_id)['user_id']) + owner_info = await XiuxianDataManager().get_user_infos_by_ids(get_user_auction_price_by_id(auction_id)['user_id']) owner_name = owner_info['user_name'] msg += f"{idx + 1}号:{item_name}x{item_quantity}(由{owner_name}道友提供)\n" else: @@ -1527,11 +1247,7 @@ async def creat_auction_(bot: Bot, event: GroupMessageEvent): for gid in groups: bot = await assign_bot_group(group_id=gid) try: - if XiuConfig().img: - pic = await get_msg_pic(msg) - await bot.send_group_msg(group_id=int(gid), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(gid), message=msg) + await handle_send(bot, event, gid, msg) except ActionFailed: continue @@ -1596,7 +1312,7 @@ async def creat_auction_(bot: Bot, event: GroupMessageEvent): if auction['user_id'] == 0: msg = f"很可惜,{auction['name']}流拍了\n" if i + 1 == len(auction_items): - msg += f"本场拍卖会到此结束,开始整理拍卖会结果,感谢各位道友参与!" + msg += "本场拍卖会到此结束,开始整理拍卖会结果,感谢各位道友参与!" for gid in groups: bot = await assign_bot_group(group_id=gid) @@ -1612,11 +1328,11 @@ async def creat_auction_(bot: Bot, event: GroupMessageEvent): auction = {} continue - user_info = sql_message.get_user_info_with_id(auction['user_id']) - msg = f"(拍卖锤落下)!!!\n" + user_info = await XiuxianDataManager().get_user_infos_by_ids(auction['user_id']) + msg = "(拍卖锤落下)!!!\n" msg += f"恭喜来自群{auction['group_id']}的{user_info['user_name']}道友成功拍下:{auction['type']}-{auction['name']}x{auction['quantity']},将在拍卖会结算后送到您手中。\n" if i + 1 == len(auction_items): - msg += f"本场拍卖会到此结束,开始整理拍卖会结果,感谢各位道友参与!" + msg += "本场拍卖会到此结束,开始整理拍卖会结果,感谢各位道友参与!" auction_results.append((auction_id, user_info['user_id'], auction['group_id'], auction_info['type'], auction['now_price'], auction['quantity'])) @@ -1634,30 +1350,31 @@ async def creat_auction_(bot: Bot, event: GroupMessageEvent): continue # 拍卖会结算 - end_msg = f"本场拍卖会结束!感谢各位道友的参与。\n拍卖结果整理如下:\n" + end_msg = "本场拍卖会结束!感谢各位道友的参与。\n拍卖结果整理如下:\n" for idx, (auction_id, user_id, group_id, item_type, final_price, quantity) in enumerate(auction_results): item_name = items.get_data_by_item_id(auction_id)['name'] - final_user_info = sql_message.get_user_info_with_id(user_id) - if user_id: - if final_user_info['stone'] < (int(final_price) * quantity): - end_msg += f"{idx + 1}号拍卖品:{item_name}x{quantity} - 道友{final_user_info['user_name']}的灵石不足,流拍了\n" - else: - sql_message.update_ls(user_id, int(final_price) * quantity, 2) - sql_message.send_back(user_id, auction_id, item_name, item_type, quantity) - end_msg += f"{idx + 1}号拍卖品:{item_name}x{quantity}由群{group_id}的{final_user_info['user_name']}道友成功拍下\n" + if user_id is None: + end_msg += f"{idx + 1}号拍卖品:{item_name}x{quantity} - 流拍了\n" + continue + + final_user_info = await XiuxianDataManager().get_user_infos_by_ids(user_id) + if final_user_info['stone'] < (int(final_price) * quantity): + end_msg += f"{idx + 1}号拍卖品:{item_name}x{quantity} - 道友{final_user_info['user_name']}的灵石不足,流拍了\n" + else: + await XiuxianDataManager().update_ls(user_id, int(final_price) * quantity, 1) + await XiuxianDataManager().send_back(user_id, auction_id, item_name, item_type, quantity) + end_msg += f"{idx + 1}号拍卖品:{item_name}x{quantity}由群{group_id}的{final_user_info['user_name']}道友成功拍下\n" - user_auction_info = get_user_auction_price_by_id(auction_id) - if user_auction_info: - seller_id = user_auction_info['user_id'] - auction_earnings = int(final_price * quantity * 0.7) # 收个手续费 - sql_message.update_ls(seller_id, auction_earnings, 1) + user_auction_info = get_user_auction_price_by_id(auction_id) + if user_auction_info: + seller_id = user_auction_info['user_id'] + auction_earnings = int(final_price) * quantity * 0.7 # 收个手续费 + await XiuxianDataManager().update_ls(seller_id, auction_earnings, 0) - remove_auction_item(auction_id) + remove_auction_item(auction_id) - auction = {} - auction_offer_time_count = 0 - else: - end_msg += f"{idx + 1}号拍卖品:{item_name}x{quantity} - 流拍了\n" + auction = {} + auction_offer_time_count = 0 for gid in groups: bot = await assign_bot_group(group_id=gid) @@ -1678,29 +1395,29 @@ async def offer_auction_(bot: Bot, event: GroupMessageEvent, args: Message = Com """拍卖""" group_id = str(event.group_id) bot = await assign_bot_group(group_id=group_id) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) global auction, auction_offer_flag, auction_offer_all_count, auction_offer_time_count if not isUser: if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(group_id), message=msg) await offer_auction.finish() if group_id not in groups: - msg = f"本群尚未开启拍卖会功能,请联系管理员开启!" + msg = "本群尚未开启拍卖会功能,请联系管理员开启!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(group_id), message=msg) await offer_auction.finish() if not auction: - msg = f"本群不存在拍卖会,请等待拍卖会开启!" + msg = "本群不存在拍卖会,请等待拍卖会开启!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(group_id), message=msg) @@ -1710,9 +1427,9 @@ async def offer_auction_(bot: Bot, event: GroupMessageEvent, args: Message = Com try: price = int(price) except ValueError: - msg = f"请发送正确的灵石数量" + msg = "请发送正确的灵石数量" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(group_id), message=msg) @@ -1721,9 +1438,9 @@ async def offer_auction_(bot: Bot, event: GroupMessageEvent, args: Message = Com now_price = auction['now_price'] min_price = int(now_price * 0.05) # 最低加价5% if price <= 0 or price <= auction['now_price'] or price > user_info['stone']: - msg = f"走开走开,别捣乱!小心清空你灵石捏" + msg = "走开走开,别捣乱!小心清空你灵石捏" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(group_id), message=msg) @@ -1731,7 +1448,7 @@ async def offer_auction_(bot: Bot, event: GroupMessageEvent, args: Message = Com if price - now_price < min_price: msg = f"拍卖不得少于当前竞拍价的5%,目前最少加价为:{min_price}灵石,目前竞拍价为:{now_price}!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(group_id), message=msg) @@ -1783,20 +1500,16 @@ async def offer_auction_(bot: Bot, event: GroupMessageEvent, args: Message = Com async def auction_added_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """用户提交拍卖品""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) group_id = str(event.group_id) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await auction_added.finish() if group_id not in groups: - msg = f"本群尚未开启拍卖会功能,请联系管理员开启!" + msg = "本群尚未开启拍卖会功能,请联系管理员开启!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(group_id), message=msg) @@ -1809,22 +1522,14 @@ async def auction_added_(bot: Bot, event: GroupMessageEvent, args: Message = Com quantity_str = args[2] if len(args) > 2 else "1" if not goods_name: - msg = f"请输入正确指令!例如:提交拍卖品 物品 可选参数为(金额 数量)" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请输入正确指令!例如:提交拍卖品 物品 可选参数为(金额 数量)" + await handle_send(bot, event, send_group_id, msg) await auction_added.finish() - back_msg = sql_message.get_back_msg(user_id) # 获取背包信息 + back_msg = await XiuxianDataManager().get_back_msg(user_id) # 获取背包信息 if back_msg is None: - msg = f"道友的背包空空如也!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友的背包空空如也!" + await handle_send(bot, event, send_group_id, msg) await auction_added.finish() # 物品是否存在于背包中 @@ -1846,11 +1551,7 @@ async def auction_added_(bot: Bot, event: GroupMessageEvent, args: Message = Com if not in_flag: msg = f"请检查该道具 {goods_name} 是否在背包内!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await auction_added.finish() try: @@ -1860,40 +1561,24 @@ async def auction_added_(bot: Bot, event: GroupMessageEvent, args: Message = Com raise ValueError("价格和数量必须为正数,或者超过了你拥有的数量!") except ValueError as e: msg = f"请输入正确的金额和数量: {str(e)}" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await auction_added.finish() if goods_type == "装备" and int(goods_state) == 1 and int(goods_num) == 1: msg = f"装备:{goods_name}已经被道友装备在身,无法提交!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await auction_added.finish() if int(goods_num) <= int(goods_bind_num): - msg = f"该物品是绑定物品,无法提交!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "该物品是绑定物品,无法提交!" + await handle_send(bot, event, send_group_id, msg) await auction_added.finish() if goods_type == "聚灵旗" or goods_type == "炼丹炉": if user_info['root'] == "器师": pass else: - msg = f"道友职业无法上架!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友职业无法上架!" + await handle_send(bot, event, send_group_id, msg) await auction_added.finish() config = get_auction_config() @@ -1910,15 +1595,11 @@ async def auction_added_(bot: Bot, event: GroupMessageEvent, args: Message = Com config['user_auctions'].append(user_auction) savef_auction(config) - sql_message.update_back_j(user_id, goods_id, num=quantity) + await XiuxianDataManager().update_back_j(user_id, goods_id, num=quantity) msg = f"道友的拍卖品:{goods_name}成功提交,底价:{price}枚灵石,数量:{quantity}" - msg += f"\n下次拍卖将优先拍卖道友的拍卖品!!!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg += "\n下次拍卖将优先拍卖道友的拍卖品!!!" + await handle_send(bot, event, send_group_id, msg) await auction_added.finish() @@ -1929,25 +1610,18 @@ async def set_auction_(bot: Bot, event: GroupMessageEvent, args: Message = Comma mode = args.extract_plain_text().strip() group_id = str(event.group_id) is_in_group = is_in_groups(event) # True在,False不在 + isUser, user_info, msg = await check_user(event) if mode == '开启': if is_in_group: msg = "本群已开启群拍卖会,请勿重复开启!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await set_auction.finish() else: config['open'].append(group_id) savef_auction(config) msg = "已开启群拍卖会" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await set_auction.finish() elif mode == '关闭': @@ -1955,28 +1629,16 @@ async def set_auction_(bot: Bot, event: GroupMessageEvent, args: Message = Comma config['open'].remove(group_id) savef_auction(config) msg = "已关闭本群拍卖会!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await set_auction.finish() else: msg = "本群未开启群拍卖会!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await set_auction.finish() else: msg = __back_help__ - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await set_auction.finish() @@ -1985,14 +1647,11 @@ async def chakan_wupin_(bot: Bot, event: GroupMessageEvent, args: Message = Comm """查看修仙界所有物品列表""" bot, send_group_id = await assign_bot(bot=bot, event=event) args = args.extract_plain_text().strip() + isUser, user_info, msg = await check_user(event) list_tp = [] if args not in ["功法", "辅修功法", "神通", "丹药", "合成丹药", "法器", "防具"]: msg = "请输入正确类型【功法|辅修功法|神通|丹药|合成丹药|法器|防具】!!!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await chakan_wupin.finish() else: if args == "功法": @@ -2064,11 +1723,7 @@ async def chakan_wupin_(bot: Bot, event: GroupMessageEvent, args: Message = Comm await send_msg_handler(bot, event, list_tp) except ActionFailed: msg = "未知原因,查看失败!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await chakan_wupin.finish() @@ -2076,31 +1731,19 @@ async def chakan_wupin_(bot: Bot, event: GroupMessageEvent, args: Message = Comm async def shop_off_all_(bot: Bot, event: GroupMessageEvent): """坊市清空""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_off_all.finish() group_id = str(event.group_id) shop_data = get_shop_data(group_id) if shop_data[group_id] == {}: msg = "坊市目前空空如也!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_off_all.finish() msg = "正在清空,稍等!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) list_msg = [] msg = "" @@ -2112,7 +1755,7 @@ async def shop_off_all_(bot: Bot, event: GroupMessageEvent): del shop_data[group_id][str(x)] save_shop(shop_data) else: - sql_message.send_back(shop_data[group_id][str(x)]['user_id'], shop_data[group_id][str(x)]['goods_id'], + await XiuxianDataManager().send_back(shop_data[group_id][str(x)]['user_id'], shop_data[group_id][str(x)]['goods_id'], shop_data[group_id][str(x)]['goods_name'], shop_data[group_id][str(x)]['goods_type'], shop_data[group_id][str(x)]['stock']) msg += f"成功下架{shop_data[group_id][str(x)]['user_name']}的{shop_data[group_id][str(x)]['stock']}个{shop_data[group_id][str(x)]['goods_name']}!\n" @@ -2126,11 +1769,7 @@ async def shop_off_all_(bot: Bot, event: GroupMessageEvent): try: await send_msg_handler(bot, event, list_msg) except ActionFailed: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await shop_off_all.finish() diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_back/back_util.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_back/back_util.py index 4d48b25b..f7285f82 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_back/back_util.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_back/back_util.py @@ -5,7 +5,7 @@ from ..xiuxian_utils.item_json import Items from ..xiuxian_utils.utils import number_to from ..xiuxian_utils.xiuxian2_handle import ( - XiuxianDateManage, UserBuffDate, + XiuxianDataManager, UserBuffData, get_weapon_info_msg, get_armor_info_msg, get_player_info, save_player_info, get_sec_msg, get_main_info_msg, get_sub_info_msg @@ -16,7 +16,6 @@ from ..xiuxian_config import convert_rank items = Items() -sql_message = XiuxianDateManage() YAOCAIINFOMSG = { "-1": "性寒", @@ -30,7 +29,7 @@ } -def check_equipment_can_use(user_id, goods_id): +async def check_equipment_can_use(user_id, goods_id): """ 装备数据库字段: good_type -> '装备' @@ -46,50 +45,50 @@ def check_equipment_can_use(user_id, goods_id): 顶用: """ flag = False - back_equipment = sql_message.get_item_by_good_id_and_user_id(user_id, goods_id) - if back_equipment['state'] == 0: + back_equipment = await XiuxianDataManager().get_item_by_good_id_and_user_id(user_id, goods_id) + if back_equipment['goods_state'] == 0: flag = True return flag -def get_use_equipment_sql(user_id, goods_id): +async def get_use_equipment_sql(user_id, goods_id): """ 使用装备 返回sql,和法器或防具 """ sql_str = [] item_info = items.get_data_by_item_id(goods_id) - user_buff_info = UserBuffDate(user_id).BuffInfo + user_buff_info = await UserBuffData(user_id).BuffInfo now_time = datetime.now() item_type = '' if item_info['item_type'] == "法器": item_type = "法器" - in_use_id = user_buff_info['faqi_buff'] + in_use_id = user_buff_info['weapon'] sql_str.append( - f"UPDATE back set update_time='{now_time}',action_time='{now_time}',state=1 WHERE user_id={user_id} and goods_id={goods_id}") # 装备 + f"UPDATE xiuxian_back set goods_update_time='{now_time}',goods_action_time='{now_time}',goods_state = 1 WHERE user_id={user_id} and goods_id = {goods_id}") # 装备 if in_use_id != 0: sql_str.append( - f"UPDATE back set update_time='{now_time}',action_time='{now_time}',state=0 WHERE user_id={user_id} and goods_id={in_use_id}") # 取下原有的 + f"UPDATE xiuxian_back set goods_update_time='{now_time}',goods_action_time='{now_time}',goods_state = 0 WHERE user_id = {user_id} and goods_id = {in_use_id}") # 取下原有的 if item_info['item_type'] == "防具": item_type = "防具" - in_use_id = user_buff_info['armor_buff'] + in_use_id = user_buff_info['armor'] sql_str.append( - f"UPDATE back set update_time='{now_time}',action_time='{now_time}',state=1 WHERE user_id={user_id} and goods_id={goods_id}") # 装备 + f"UPDATE xiuxian_back set goods_update_time='{now_time}',goods_action_time='{now_time}',goods_state = 1 WHERE user_id = {user_id} and goods_id = {goods_id}") # 装备 if in_use_id != 0: sql_str.append( - f"UPDATE back set update_time='{now_time}',action_time='{now_time}',state=0 WHERE user_id={user_id} and goods_id={in_use_id}") # 取下原有的 + f"UPDATE xiuxian_back set goods_update_time='{now_time}',goods_action_time='{now_time}',goods_state = 0 WHERE user_id = {user_id} and goods_id = {in_use_id}") # 取下原有的 return sql_str, item_type -def get_no_use_equipment_sql(user_id, goods_id): +async def get_no_use_equipment_sql(user_id, goods_id): """ 卸载装备 返回sql,和法器或防具 """ item_info = items.get_data_by_item_id(goods_id) - user_buff_info = UserBuffDate(user_id).BuffInfo + user_buff_info = await UserBuffData(user_id).BuffInfo now_time = datetime.now() sql_str = [] item_type = "" @@ -97,10 +96,10 @@ def get_no_use_equipment_sql(user_id, goods_id): # 检查装备类型,并确定要卸载的是哪种buff if item_info['item_type'] == "法器": item_type = "法器" - in_use_id = user_buff_info['faqi_buff'] + in_use_id = user_buff_info['weapon'] elif item_info['item_type'] == "防具": item_type = "防具" - in_use_id = user_buff_info['armor_buff'] + in_use_id = user_buff_info['armor'] else: return sql_str, item_type @@ -108,22 +107,22 @@ def get_no_use_equipment_sql(user_id, goods_id): if goods_id == in_use_id or in_use_id != 0: # 卸载当前装备 sql_str.append( - f"UPDATE back set update_time='{now_time}',action_time='{now_time}',state=0 WHERE user_id={user_id} and goods_id={goods_id}") + f"UPDATE xiuxian_back set update_time='{now_time}',action_time='{now_time}',state=0 WHERE user_id={user_id} and goods_id={goods_id}") # 如果还有其他装备需要卸载(对于法器和防具的情况) if in_use_id != 0 and goods_id != in_use_id: sql_str.append( - f"UPDATE back set update_time='{now_time}',action_time='{now_time}',state=0 WHERE user_id={user_id} and goods_id={in_use_id}") + f"UPDATE xiuxian_back set update_time='{now_time}',action_time='{now_time}',state=0 WHERE user_id={user_id} and goods_id={in_use_id}") return sql_str, item_type -def check_equipment_use_msg(user_id, goods_id): +async def check_equipment_use_msg(user_id, goods_id): """ 检测装备是否已用 """ - user_back = sql_message.get_item_by_good_id_and_user_id(user_id, goods_id) - state = user_back['state'] + user_back = await XiuxianDataManager().get_item_by_good_id_and_user_id(user_id, goods_id) + state = user_back['goods_state'] is_use = False if state == 0: is_use = False @@ -132,7 +131,7 @@ def check_equipment_use_msg(user_id, goods_id): return is_use -def get_user_main_back_msg(user_id): +async def get_user_main_back_msg(user_id): """ 获取背包内的所有物品信息 """ @@ -145,33 +144,33 @@ def get_user_main_back_msg(user_id): l_yaocai_msg = [] l_libao_msg = [] l_msg = [] - user_backs = sql_message.get_back_msg(user_id) # list(back) + user_backs = await XiuxianDataManager().get_back_msg(user_id) # list(back) if user_backs is None: return l_msg for user_back in user_backs: if user_back['goods_type'] == "装备": - l_equipment_msg = get_equipment_msg(l_equipment_msg, user_id, user_back['goods_id'], user_back['goods_num'], user_back['bind_num']) + l_equipment_msg = await get_equipment_msg(l_equipment_msg, user_id, user_back['goods_id'], user_back['goods_num'], user_back['goods_bind_num']) elif user_back['goods_type'] == "技能": - l_skill_msg = get_skill_msg(l_skill_msg, user_back['goods_id'], user_back['goods_num'], user_back['bind_num']) + l_skill_msg = await get_skill_msg(l_skill_msg, user_back['goods_id'], user_back['goods_num'], user_back['goods_bind_num']) elif user_back['goods_type'] == "丹药": - l_elixir_msg = get_elixir_msg(l_elixir_msg, user_back['goods_id'], user_back['goods_num'], user_back['bind_num']) - + l_elixir_msg = await get_elixir_msg(l_elixir_msg, user_back['goods_id'], user_back['goods_num'], user_back['goods_bind_num']) + elif user_back['goods_type'] == "神物": - l_shenwu_msg = get_shenwu_msg(l_shenwu_msg, user_back['goods_id'], user_back['goods_num'], user_back['bind_num']) + l_shenwu_msg = await get_shenwu_msg(l_shenwu_msg, user_back['goods_id'], user_back['goods_num'], user_back['goods_bind_num']) elif user_back['goods_type'] == "聚灵旗": - l_xiulianitem_msg = get_jlq_msg(l_xiulianitem_msg, user_back['goods_id'], user_back['goods_num'], user_back['bind_num']) + l_xiulianitem_msg = await get_jlq_msg(l_xiulianitem_msg, user_back['goods_id'], user_back['goods_num'], user_back['goods_bind_num']) elif user_back['goods_type'] == "炼丹炉": - l_ldl_msg = get_ldl_msg(l_ldl_msg, user_back['goods_id'], user_back['goods_num'], user_back['bind_num']) + l_ldl_msg = await get_ldl_msg(l_ldl_msg, user_back['goods_id'], user_back['goods_num'], user_back['goods_bind_num']) elif user_back['goods_type'] == "药材": - l_yaocai_msg = get_yaocai_msg(l_yaocai_msg, user_back['goods_id'], user_back['goods_num'], user_back['bind_num']) + l_yaocai_msg = await get_yaocai_msg(l_yaocai_msg, user_back['goods_id'], user_back['goods_num'], user_back['goods_bind_num']) elif user_back['goods_type'] == "礼包": - l_libao_msg = get_libao_msg(l_libao_msg, user_back['goods_id'], user_back['goods_num'], user_back['bind_num']) + l_libao_msg = await get_libao_msg(l_libao_msg, user_back['goods_id'], user_back['goods_num'], user_back['goods_bind_num']) if l_equipment_msg: l_msg.append("☆------我的装备------☆") @@ -279,7 +278,7 @@ def get_yaocai_info(yaocai_info): return msg -def get_equipment_msg(l_msg, user_id, goods_id, goods_num, bind_num): +async def get_equipment_msg(l_msg, user_id, goods_id, goods_num, bind_num): """ 获取背包内的装备信息 """ @@ -290,16 +289,16 @@ def get_equipment_msg(l_msg, user_id, goods_id, goods_num, bind_num): elif item_info['item_type'] == '法器': msg = get_weapon_info_msg(goods_id, item_info) msg += f"\n拥有数量:{goods_num},绑定数量:{bind_num}" - is_use = check_equipment_use_msg(user_id, goods_id) + is_use = await check_equipment_use_msg(user_id, goods_id) if is_use: - msg += f"\n已装备" + msg += "\n已装备" else: - msg += f"\n可装备" + msg += "\n可装备" l_msg.append(msg) return l_msg -def get_skill_msg(l_msg, goods_id, goods_num, bind_num): +async def get_skill_msg(l_msg, goods_id, goods_num, bind_num): """ 获取背包内的技能信息 """ @@ -319,7 +318,7 @@ def get_skill_msg(l_msg, goods_id, goods_num, bind_num): return l_msg -def get_elixir_msg(l_msg, goods_id, goods_num, bind_num): +async def get_elixir_msg(l_msg, goods_id, goods_num, bind_num): """ 获取背包内的丹药信息 """ @@ -330,7 +329,7 @@ def get_elixir_msg(l_msg, goods_id, goods_num, bind_num): l_msg.append(msg) return l_msg -def get_shenwu_msg(l_msg, goods_id, goods_num, bind_num): +async def get_shenwu_msg(l_msg, goods_id, goods_num, bind_num): """ 获取背包内的神物信息 """ @@ -347,7 +346,7 @@ def get_shenwu_msg(l_msg, goods_id, goods_num, bind_num): return l_msg -def get_item_msg(goods_id): +async def get_item_msg(goods_id): """ 获取单个物品的消息 """ @@ -363,26 +362,26 @@ def get_item_msg(goods_id): elif item_info['item_type'] == '神通': msg = f"名字:{item_info['name']}\n" msg += f"品阶:{item_info['level']}\n" - msg += f"效果:{get_sec_msg(item_info)}" + msg += f"效果:{await get_sec_msg(item_info)}" elif item_info['item_type'] == '功法': msg = f"名字:{item_info['name']}\n" msg += f"品阶:{item_info['level']}\n" - msg += f"效果:{get_main_info_msg(goods_id)[1]}" + msg += f"效果:{await get_main_info_msg(goods_id)[1]}" elif item_info['item_type'] == '辅修功法':#辅修功法11 msg = f"名字:{item_info['name']}\n" msg += f"品阶:{item_info['level']}\n" - msg += f"效果:{get_sub_info_msg(goods_id)[1]}" + msg += f"效果:{await get_sub_info_msg(goods_id)[1]}" elif item_info['item_type'] == '防具': - msg = get_armor_info_msg(goods_id, item_info) + msg = await get_armor_info_msg(goods_id, item_info) elif item_info['item_type'] == '法器': - msg = get_weapon_info_msg(goods_id, item_info) + msg = await get_weapon_info_msg(goods_id, item_info) elif item_info['item_type'] == "药材": - msg = get_yaocai_info_msg(goods_id, item_info) + msg = await get_yaocai_info_msg(goods_id, item_info) elif item_info['item_type'] == "聚灵旗": msg = f"名字:{item_info['name']}\n" @@ -410,7 +409,7 @@ def get_item_msg(goods_id): return msg -def get_item_msg_rank(goods_id): +async def get_item_msg_rank(goods_id): """ 获取单个物品的rank """ @@ -436,20 +435,20 @@ def get_item_msg_rank(goods_id): return int(msg) -def get_yaocai_info_msg(goods_id, item_info): +async def get_yaocai_info_msg(goods_id, item_info): msg = f"名字:{item_info['name']}\n" msg += f"品级:{item_info['level']}\n" msg += get_yaocai_info(item_info) return msg -def check_use_elixir(user_id, goods_id, num): - user_info = sql_message.get_user_info_with_id(user_id) +async def check_use_elixir(user_id, goods_id, num): + user_info = await XiuxianDataManager().get_user_infos_by_ids(user_id) user_rank = convert_rank(user_info['level'])[0] goods_info = items.get_data_by_item_id(goods_id) goods_rank = goods_info['rank'] goods_name = goods_info['name'] - back = sql_message.get_item_by_good_id_and_user_id(user_id, goods_id) + back = await XiuxianDataManager().get_item_by_good_id_and_user_id(user_id, goods_id) goods_all_num = back['all_num'] # 数据库里的使用数量 remaining_limit = goods_info['all_num'] - goods_all_num # 剩余可用数量 @@ -459,9 +458,9 @@ def check_use_elixir(user_id, goods_id, num): elif goods_rank - user_rank > 18: # 最高使用限制 msg = f"道友当前境界为:{user_info['level']},丹药:{goods_name}已不能满足道友,请寻找适合道友的丹药吧!" else: # 检查完毕 - sql_message.update_back_j(user_id, goods_id, num, 1) - sql_message.update_levelrate(user_id, user_info['level_up_rate'] + goods_info['buff'] * num) - msg = f"道友成功使用丹药:{goods_name}{num}颗,下一次突破的成功概率提高{goods_info['buff'] * num}%!" + await XiuxianDataManager().update_back_j(user_id, goods_id, num, 1) + await XiuxianDataManager().update_levelrate(user_id, user_info['level_up_rate'] + goods_info['buff'] * num) + msg = f"道友成功使用丹药:{goods_name}{num}颗,下一次突破的成功概率提高{goods_info['buf'] * num}%!" elif goods_info['buff_type'] == "level_up_big": # 增加大境界突破概率的丹药 if goods_rank != user_rank: # 使用限制 @@ -476,17 +475,17 @@ def check_use_elixir(user_id, goods_id, num): else: msg = f"道友成功使用丹药:{goods_name}{num}颗, 下一次突破的成功概率提高{goods_info['buff'] * num}%!" - sql_message.update_back_j(user_id, goods_id, num, 1) - sql_message.update_levelrate(user_id, user_info['level_up_rate'] + goods_info['buff'] * num) + await XiuxianDataManager().update_back_j(user_id, goods_id, num, 1) + await XiuxianDataManager().update_levelrate(user_id, user_info['level_up_rate'] + goods_info['buf'] * num) elif goods_info['buff_type'] == "hp": # 回复状态的丹药 if user_info['root'] == "器师": user_max_hp = int(user_info['exp'] / 2) user_max_mp = int(user_info['exp']) if user_info['hp'] == user_max_hp and user_info['mp'] == user_max_mp: - msg = f"道友的状态是满的,用不了哦!" + msg = "道友的状态是满的,用不了哦!" else: - buff = goods_info['buff'] + buff = goods_info['buf'] buff = round((0.016 * user_rank + 0.104) * buff , 2) recover_hp = int(buff * user_max_hp * num) recover_mp = int(buff * user_max_mp * num) @@ -499,8 +498,8 @@ def check_use_elixir(user_id, goods_id, num): else: new_mp = user_info['mp'] + recover_mp msg = f"道友成功使用丹药:{goods_name}{num}颗,经过境界转化状态恢复了{int(buff * 100 * num)}%!" - sql_message.update_back_j(user_id, goods_id, num=num ,use_key=1) - sql_message.update_user_hp_mp(user_id, new_hp, new_mp) + await XiuxianDataManager().update_back_j(user_id, goods_id, num=num ,use_key=1) + await XiuxianDataManager().update_user_hp_mp(user_id, new_hp, new_mp) else: if goods_rank < user_rank: # 使用限制 msg = f"丹药:{goods_name}的使用境界为{goods_info['境界']}以上,道友不满足使用条件!" @@ -508,9 +507,9 @@ def check_use_elixir(user_id, goods_id, num): user_max_hp = int(user_info['exp'] / 2) user_max_mp = int(user_info['exp']) if user_info['hp'] == user_max_hp and user_info['mp'] == user_max_mp: - msg = f"道友的状态是满的,用不了哦!" + msg = "道友的状态是满的,用不了哦!" else: - buff = goods_info['buff'] + buff = goods_info['buf'] buff = round((0.016 * user_rank + 0.104) * buff , 2) recover_hp = int(buff * user_max_hp * num) recover_mp = int(buff * user_max_mp * num) @@ -523,18 +522,18 @@ def check_use_elixir(user_id, goods_id, num): else: new_mp = user_info['mp'] + recover_mp msg = f"道友成功使用丹药:{goods_name}{num}颗,经过境界转化状态恢复了{int(buff * 100 * num)}%!" - sql_message.update_back_j(user_id, goods_id, num=num ,use_key=1) - sql_message.update_user_hp_mp(user_id, new_hp, new_mp) + await XiuxianDataManager().update_back_j(user_id, goods_id, num=num ,use_key=1) + await XiuxianDataManager().update_user_hp_mp(user_id, new_hp, new_mp) elif goods_info['buff_type'] == "all": # 回满状态的丹药 if user_info['root'] == "器师": user_max_hp = int(user_info['exp'] / 2) user_max_mp = int(user_info['exp']) if user_info['hp'] == user_max_hp and user_info['mp'] == user_max_mp: - msg = f"道友的状态是满的,用不了哦!" + msg = "道友的状态是满的,用不了哦!" else: - sql_message.update_back_j(user_id, goods_id, use_key=1) - sql_message.update_user_hp(user_id) + await XiuxianDataManager().update_back_j(user_id, goods_id, use_key=1) + await XiuxianDataManager().update_user_hp(user_id) msg = f"道友成功使用丹药:{goods_name}1颗,状态已全部恢复!" else: if goods_rank < user_rank: # 使用限制 @@ -543,74 +542,74 @@ def check_use_elixir(user_id, goods_id, num): user_max_hp = int(user_info['exp'] / 2) user_max_mp = int(user_info['exp']) if user_info['hp'] == user_max_hp and user_info['mp'] == user_max_mp: - msg = f"道友的状态是满的,用不了哦!" + msg = "道友的状态是满的,用不了哦!" else: - sql_message.update_back_j(user_id, goods_id, use_key=1) - sql_message.update_user_hp(user_id) + await XiuxianDataManager().update_back_j(user_id, goods_id, use_key=1) + await XiuxianDataManager().update_user_hp(user_id) msg = f"道友成功使用丹药:{goods_name}1颗,状态已全部恢复!" - elif goods_info['buff_type'] == "atk_buff": # 永久加攻击buff的丹药 + elif goods_info['buff_type'] == "atk_buf": # 永久加攻击buff的丹药 if user_info['root'] == "器师": buff = goods_info['buff'] * num - sql_message.updata_user_atk_buff(user_id, buff) - sql_message.update_back_j(user_id, goods_id,num=num, use_key=1) + await XiuxianDataManager().updata_user_atk_buff(user_id, buff) + await XiuxianDataManager().update_back_j(user_id, goods_id,num=num, use_key=1) msg = f"道友成功使用丹药:{goods_name}{num}颗,攻击力永久增加{buff}点!" else: if goods_rank < user_rank: # 使用限制 msg = f"丹药:{goods_name}的使用境界为{goods_info['境界']}以上,道友不满足使用条件!" else: buff = goods_info['buff'] * num - sql_message.updata_user_atk_buff(user_id, buff) - sql_message.update_back_j(user_id, goods_id,num=num, use_key=1) + await XiuxianDataManager().updata_user_atk_buff(user_id, buff) + await XiuxianDataManager().update_back_j(user_id, goods_id,num=num, use_key=1) msg = f"道友成功使用丹药:{goods_name}{num}颗,攻击力永久增加{buff}点!" elif goods_info['buff_type'] == "exp_up": # 加固定经验值的丹药 if goods_rank < user_rank: # 使用限制 msg = f"丹药:{goods_name}的使用境界为{goods_info['境界']}以上,道友不满足使用条件!" else: - exp = goods_info['buff'] * num + exp = goods_info['buf'] * num user_hp = int(user_info['hp'] + (exp / 2)) user_mp = int(user_info['mp'] + exp) user_atk = int(user_info['atk'] + (exp / 10)) - sql_message.update_exp(user_id, exp) - sql_message.update_power2(user_id) # 更新战力 - sql_message.update_user_attribute(user_id, user_hp, user_mp, user_atk) # 这种事情要放在update_exp方法里 - sql_message.update_back_j(user_id, goods_id, num=num, use_key=1) + await XiuxianDataManager().update_exp(user_id, exp, 0) + await XiuxianDataManager().update_power2(user_id) # 更新战力 + await XiuxianDataManager().update_user_attribute(user_id, user_hp, user_mp, user_atk) # 这种事情要放在update_exp方法里 + await XiuxianDataManager().update_back_j(user_id, goods_id, num=num, use_key=1) msg = f"道友成功使用丹药:{goods_name}{num}颗,修为增加{exp}点!" else: - msg = f"该类型的丹药目前暂时不支持使用!" + msg = "该类型的丹药目前暂时不支持使用!" return msg -def get_use_jlq_msg(user_id, goods_id): - user_info = sql_message.get_user_info_with_id(user_id) +async def get_use_jlq_msg(user_id, goods_id): + user_info = await XiuxianDataManager().get_user_infos_by_ids(user_id) if user_info['blessed_spot_flag'] == 0: - msg = f"道友还未拥有洞天福地,无法使用该物品" + msg = "道友还未拥有洞天福地,无法使用该物品" else: item_info = items.get_data_by_item_id(goods_id) - user_buff_data = UserBuffDate(user_id).BuffInfo + user_buff_data = await UserBuffData(user_id).BuffInfo if int(user_buff_data['blessed_spot']) >= item_info['修炼速度']: - msg = f"该聚灵旗的等级不能满足道友的福地了,使用了也没效果" + msg = "该聚灵旗的等级不能满足道友的福地了,使用了也没效果" else: mix_elixir_info = get_player_info(user_id, "mix_elixir_info") mix_elixir_info['药材速度'] = item_info['药材速度'] save_player_info(user_id, mix_elixir_info, 'mix_elixir_info') - sql_message.update_back_j(user_id, goods_id) - sql_message.updata_user_blessed_spot(user_id, item_info['修炼速度']) + await XiuxianDataManager().update_back_j(user_id, goods_id) + await XiuxianDataManager().updata_user_blessed_spot(user_id, item_info['修炼速度']) msg = f"道友洞天福地的聚灵旗已经替换为:{item_info['name']}" return msg -def get_shop_data(group_id): +async def get_shop_data(group_id): try: - data = read_shop() - except: + data = await read_shop() + except ValueError: data = {} try: data[group_id] - except: + except ValueError: data[group_id] = {} - save_shop(data) + await save_shop(data) return data @@ -618,13 +617,13 @@ def get_shop_data(group_id): FILEPATH = PATH / 'shop.json' -def read_shop(): +async def read_shop(): with open(FILEPATH, "r", encoding="UTF-8") as f: data = f.read() return json.loads(data) -def save_shop(data): +async def save_shop(data): data = json.dumps(data, ensure_ascii=False, indent=4) savemode = "w" if os.path.exists(FILEPATH) else "x" with open(FILEPATH, mode=savemode, encoding="UTF-8") as f: diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_back/backconfig.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_back/backconfig.py index 82d7e023..a76374e4 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_back/backconfig.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_back/backconfig.py @@ -182,7 +182,7 @@ def get_auction_config(): if 'user_auctions' not in config: config['user_auctions'] = [] savef_auction(config) - except: + except FileNotFoundError: config = CONFIG config['user_auctions'] = [] savef_auction(config) diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_bank/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_bank/__init__.py index c212cc8e..a86d6e64 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_bank/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_bank/__init__.py @@ -15,7 +15,7 @@ MessageSegment, ) from ..xiuxian_utils.lay_out import assign_bot, Cooldown -from ..xiuxian_utils.xiuxian2_handle import XiuxianDateManage +from ..xiuxian_utils.xiuxian2_handle import XiuxianDataManager from datetime import datetime from .bankconfig import get_config from ..xiuxian_utils.utils import check_user, get_msg_pic @@ -23,7 +23,7 @@ config = get_config() BANKLEVEL = config["BANKLEVEL"] -sql_message = XiuxianDateManage() # sql类 + # sql类 PLAYERSDATA = Path() / "data" / "xiuxian" / "players" bank = on_regex( @@ -33,11 +33,11 @@ block=True ) -__bank_help__ = f""" +__bank_help__ = """ 灵庄帮助信息: 指令: 1、灵庄:查看灵庄帮助信息 -2、灵庄存灵石:指令后加存入的金额,获取利息 +2、灵庄存灵石:指令后加存入的金额,获取利息(复利计算) 3、灵庄取灵石:指令后加取出的金额,会先结算利息,再取出灵石 4、灵庄升级会员:灵庄利息倍率与灵庄会员等级有关,升级会员会提升利息倍率 5、灵庄信息:查询自己当前的灵庄信息 @@ -48,13 +48,10 @@ @bank.handle(parameterless=[Cooldown(at_sender=False)]) async def bank_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = RegexGroup()): bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) + from ..xiuxian_utils.utils import number_to, handle_send if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await bank.finish() mode = args[0] # 存灵石、取灵石、升级会员、信息查看 num = args[1] # 数值 @@ -71,25 +68,17 @@ async def bank_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = Rege try: num = int(num) if num <= 0: - msg = f"请输入正确的金额!" - if XiuConfig().img: - pic = await get_msg_pic(msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请输入正确的金额!" + await handle_send(bot, event, send_group_id, msg) await bank.finish() except ValueError: - msg = f"请输入正确的金额!" - if XiuConfig().img: - pic = await get_msg_pic(msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请输入正确的金额!" + await handle_send(bot, event, send_group_id, msg) await bank.finish() user_id = user_info['user_id'] try: bankinfo = readf(user_id) - except: + except ValueError: bankinfo = { 'savestone': 0, 'savetime': str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')), @@ -98,7 +87,7 @@ async def bank_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = Rege if mode == '存灵石': # 存灵石逻辑 if int(user_info['stone']) < num: - msg = f"道友所拥有的灵石为{user_info['stone']}枚,金额不足,请重新输入!" + msg = f"道友所拥有的灵石为{number_to(user_info['stone'])}枚,金额不足,请重新输入!" if XiuConfig().img: pic = await get_msg_pic(msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) @@ -106,11 +95,32 @@ async def bank_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = Rege await bot.send_group_msg(group_id=int(send_group_id), message=msg) await bank.finish() + # 先结算之前的利息,采用复利计算 + bankinfo, give_stone, days_diff = get_give_stone(bankinfo) + max = BANKLEVEL[bankinfo['banklevel']]['savemax'] + # 更新存款金额,加上利息 + bankinfo['savestone'] += give_stone + # 检查是否超过最大存款额度 + if bankinfo['savestone'] > max: + # 如果超过了,将超出部分加到用户灵石中 + overflow = bankinfo['savestone'] - max + await XiuxianDataManager().update_ls(user_id, overflow, 0) + msg = f"道友本次结息时间为:{days_diff:.1f}天,获得灵石:{number_to(give_stone)}枚!\n已达到存款上限,多余的{number_to(overflow)}灵石已返还给道友。" + bankinfo['savestone'] = max + savef(user_id, bankinfo) + if XiuConfig().img: + pic = await get_msg_pic(msg) + await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) + else: + await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await bank.finish() + + # 确认剩余可存储空间 nowmax = max - bankinfo['savestone'] if num > nowmax: - msg = f"道友当前灵庄会员等级为{BANKLEVEL[bankinfo['banklevel']]['level']},可存储的最大灵石为{max}枚,当前已存{bankinfo['savestone']}枚灵石,可以继续存{nowmax}枚灵石!" + msg = f"道友当前灵庄会员等级为{BANKLEVEL[bankinfo['banklevel']]['level']},可存储的最大灵石为{number_to(max)}枚,当前已存{number_to(bankinfo['savestone'])}枚灵石,可以继续存{number_to(nowmax)}枚灵石!" if XiuConfig().img: pic = await get_msg_pic(msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) @@ -118,14 +128,15 @@ async def bank_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = Rege await bot.send_group_msg(group_id=int(send_group_id), message=msg) await bank.finish() - bankinfo, give_stone, timedeff = get_give_stone(bankinfo) userinfonowstone = int(user_info['stone']) - num + # 更新利息后的存款金额再加上新存款 bankinfo['savestone'] += num - sql_message.update_ls(user_id, num, 2) - sql_message.update_ls(user_id, give_stone, 1) + await XiuxianDataManager().update_ls(user_id, num, 1) + # 将之前结算的利息加给用户 + await XiuxianDataManager().update_ls(user_id, give_stone, 0) bankinfo['savetime'] = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) savef(user_id, bankinfo) - msg = f"道友本次结息时间为:{timedeff}小时,获得灵石:{give_stone}枚!\n道友存入灵石{num}枚,当前所拥有灵石{userinfonowstone + give_stone}枚,灵庄存有灵石{bankinfo['savestone']}枚" + msg = f"道友本次结息时间为:{days_diff:.1f}天,获得灵石:{number_to(give_stone)}枚!\n道友存入灵石{number_to(num)}枚,当前所拥有灵石{number_to(userinfonowstone + give_stone)}枚,灵庄存有灵石{number_to(bankinfo['savestone'])}枚" if XiuConfig().img: pic = await get_msg_pic(msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) @@ -134,8 +145,13 @@ async def bank_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = Rege await bank.finish() elif mode == '取灵石': # 取灵石逻辑 + # 先结算利息,采用复利计算 + bankinfo, give_stone, days_diff = get_give_stone(bankinfo) + # 更新存款金额,加上利息 + bankinfo['savestone'] += give_stone + if int(bankinfo['savestone']) < num: - msg = f"道友当前灵庄所存有的灵石为{bankinfo['savestone']}枚,金额不足,请重新输入!" + msg = f"道友当前灵庄所存有的灵石为{number_to(bankinfo['savestone'])}枚,金额不足,请重新输入!" if XiuConfig().img: pic = await get_msg_pic(msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) @@ -143,14 +159,11 @@ async def bank_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = Rege await bot.send_group_msg(group_id=int(send_group_id), message=msg) await bank.finish() - # 先结算利息 - bankinfo, give_stone, timedeff = get_give_stone(bankinfo) - - userinfonowstone = int(user_info['stone']) + num + give_stone + userinfonowstone = int(user_info['stone']) + num bankinfo['savestone'] -= num - sql_message.update_ls(user_id, num + give_stone, 1) + await XiuxianDataManager().update_ls(user_id, num, 0) savef(user_id, bankinfo) - msg = f"道友本次结息时间为:{timedeff}小时,获得灵石:{give_stone}枚!\n取出灵石{num}枚,当前所拥有灵石{userinfonowstone}枚,灵庄存有灵石{bankinfo['savestone']}枚!" + msg = f"道友本次结息时间为:{days_diff:.1f}天,获得灵石:{number_to(give_stone)}枚!\n取出灵石{number_to(num)}枚,当前所拥有灵石{number_to(userinfonowstone)}枚,灵庄存有灵石{number_to(bankinfo['savestone'])}枚!" if XiuConfig().img: pic = await get_msg_pic(msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) @@ -158,10 +171,11 @@ async def bank_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = Rege await bot.send_group_msg(group_id=int(send_group_id), message=msg) await bank.finish() + elif mode == '升级会员': # 升级会员逻辑 userlevel = bankinfo["banklevel"] if userlevel == str(len(BANKLEVEL)): - msg = f"道友已经是本灵庄最大的会员啦!" + msg = "道友已经是本灵庄最大的会员啦!" if XiuConfig().img: pic = await get_msg_pic(msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) @@ -171,7 +185,7 @@ async def bank_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = Rege stonecost = BANKLEVEL[f"{int(userlevel)}"]['levelup'] if int(user_info['stone']) < stonecost: - msg = f"道友所拥有的灵石为{user_info['stone']}枚,当前升级会员等级需求灵石{stonecost}枚金额不足,请重新输入!" + msg = f"道友所拥有的灵石为{number_to(user_info['stone'])}枚,当前升级会员等级需求灵石{number_to(stonecost)}枚,金额不足,请重新输入!" if XiuConfig().img: pic = await get_msg_pic(msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) @@ -179,10 +193,10 @@ async def bank_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = Rege await bot.send_group_msg(group_id=int(send_group_id), message=msg) await bank.finish() - sql_message.update_ls(user_id, stonecost, 2) + await XiuxianDataManager().update_ls(user_id, stonecost, 1) bankinfo['banklevel'] = f"{int(userlevel) + 1}" savef(user_id, bankinfo) - msg = f"道友成功升级灵庄会员等级,消耗灵石{stonecost}枚,当前为:{BANKLEVEL[str(int(userlevel) + 1)]['level']},灵庄可存有灵石上限{BANKLEVEL[str(int(userlevel) + 1)]['savemax']}枚" + msg = f"道友成功升级灵庄会员等级,消耗灵石{number_to(stonecost)}枚,当前为:{BANKLEVEL[str(int(userlevel) + 1)]['level']},灵庄可存有灵石上限{number_to(BANKLEVEL[str(int(userlevel) + 1)]['savemax'])}枚" if XiuConfig().img: pic = await get_msg_pic(msg) @@ -192,12 +206,13 @@ async def bank_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = Rege await bank.finish() elif mode == '信息': # 查询灵庄信息 - msg = f'''道友的灵庄信息: -已存:{bankinfo['savestone']}灵石 + msg = '''道友的灵庄信息: +已存:{number_to(bankinfo['savestone'])}灵石 存入时间:{bankinfo['savetime']} 灵庄会员等级:{BANKLEVEL[bankinfo['banklevel']]['level']} -当前拥有灵石:{user_info['stone']} -当前等级存储灵石上限:{BANKLEVEL[bankinfo['banklevel']]['savemax']}枚 +当前拥有灵石:{number_to(user_info['stone'])} +当前等级存储灵石上限:{number_to(BANKLEVEL[bankinfo['banklevel']]['savemax'])}枚 +利息计算方式:0.1%/天(复利) ''' if XiuConfig().img: pic = await get_msg_pic(msg) @@ -207,11 +222,24 @@ async def bank_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = Rege await bank.finish() elif mode == '结算': - - bankinfo, give_stone, timedeff = get_give_stone(bankinfo) - sql_message.update_ls(user_id, give_stone, 1) - savef(user_id, bankinfo) - msg = f"道友本次结息时间为:{timedeff}小时,获得灵石:{give_stone}枚!" + # 结算利息,采用复利计算 + bankinfo, give_stone, days_diff = get_give_stone(bankinfo) + + # 检查是否会超过最大存款额度 + max = BANKLEVEL[bankinfo['banklevel']]['savemax'] + if bankinfo['savestone'] + give_stone > max: + # 如果超过了,将超出部分加到用户灵石中 + overflow = (bankinfo['savestone'] + give_stone) - max + await XiuxianDataManager().update_ls(user_id, give_stone, 0) + bankinfo['savestone'] = max + savef(user_id, bankinfo) + msg = f"道友本次结息时间为:{days_diff:.1f}天,获得灵石:{number_to(give_stone)}枚!\n已达到存款上限,多余的{number_to(overflow)}灵石已返还给道友。" + else: + # 未超过上限,将全部利息加入存款 + bankinfo['savestone'] += give_stone + savef(user_id, bankinfo) + msg = f"道友本次结息时间为:{days_diff:.1f}天,获得灵石:{number_to(give_stone)}枚!" + if XiuConfig().img: pic = await get_msg_pic(msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) @@ -221,15 +249,37 @@ async def bank_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = Rege def get_give_stone(bankinfo): - """获取利息:利息=give_stone,结算时间=timedeff""" + """获取利息:利息 = give_stone,结算时间 = days_dif""" savetime = bankinfo['savetime'] # str nowtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # str - timedeff = round((datetime.strptime(nowtime, '%Y-%m-%d %H:%M:%S') - - datetime.strptime(savetime, '%Y-%m-%d %H:%M:%S')).total_seconds() / 3600, 2) - give_stone = int(bankinfo['savestone'] * timedeff * BANKLEVEL[bankinfo['banklevel']]['interest']) + days_diff = round((datetime.strptime(nowtime, '%Y-%m-%d %H:%M:%S') - + datetime.strptime(savetime, '%Y-%m-%d %H:%M:%S')).total_seconds() / 86400, 2) + + # 计算复利,1天为一个周期 + days = int(days_diff) + remaining_time = days_diff - days + + # 初始本金 + principal = bankinfo['savestone'] + interest_rate = BANKLEVEL[bankinfo['banklevel']]['interest'] + + # 按天计算复利 + for _ in range(days): + interest = int(principal * interest_rate) + principal += interest + + # 计算剩余时间的利息(按单利) + if remaining_time > 0: + final_interest = int(principal * remaining_time * interest_rate) + principal += final_interest + + # 计算总利息 + give_stone = principal - bankinfo['savestone'] + + # 更新存款时间,但不改变存款金额,在调用函数后处理 bankinfo['savetime'] = nowtime - return bankinfo, give_stone, timedeff + return bankinfo, give_stone, days_diff def readf(user_id): @@ -243,7 +293,7 @@ def readf(user_id): def savef(user_id, data): user_id = str(user_id) if not os.path.exists(PLAYERSDATA / user_id): - logger.opt(colors=True).info(f"用户目录不存在,创建目录") + logger.opt(colors=True).info("用户目录不存在,创建目录") os.makedirs(PLAYERSDATA / user_id) FILEPATH = PLAYERSDATA / user_id / "bankinfo.json" data = json.dumps(data, ensure_ascii=False, indent=3) diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_bank/bankconfig.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_bank/bankconfig.py index 43303c53..5e4366d8 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_bank/bankconfig.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_bank/bankconfig.py @@ -9,13 +9,54 @@ CONFIG = { "BANKLEVEL": { # 钱庄等级参数。savemax:当前等级可以存储上限,levelup:升级钱庄等级消耗的灵石数量,interest:每小时给与的利息,level:当前等级会员的名称 - "1": {"savemax": 1000000, "levelup": 200000, 'interest': 0.002, "level": "普通会员"}, - "2": {"savemax": 2000000, "levelup": 400000, 'interest': 0.0021, "level": "小会员"}, - "3": {"savemax": 4000000, "levelup": 800000, 'interest': 0.0022, "level": "大会员"}, - "4": {"savemax": 8000000, "levelup": 1600000, 'interest': 0.0023, "level": "优质会员"}, - "5": {"savemax": 16000000, "levelup": 3200000, 'interest': 0.0024, "level": "黄金会员"}, - "6": {"savemax": 32000000, "levelup": 6400000, 'interest': 0.0025, "level": "钻石会员"}, - "7": {"savemax": 64000000, "levelup": 0, 'interest': 0.0030, "level": "终极会员"}, + "1": {"savemax": 1000000, "levelup": 200000, 'interest': 0.001, "level": "凡铜会员"}, + "2": {"savemax": 2000000, "levelup": 400000, 'interest': 0.001, "level": "凡银会员"}, + "3": {"savemax": 4000000, "levelup": 800000, 'interest': 0.001, "level": "凡金会员"}, + "4": {"savemax": 8000000, "levelup": 1600000, 'interest': 0.001, "level": "玄铜会员"}, + "5": {"savemax": 16000000, "levelup": 3200000, 'interest': 0.001, "level": "玄银会员"}, + "6": {"savemax": 32000000, "levelup": 6400000, 'interest': 0.001, "level": "玄金会员"}, + "7": {"savemax": 64000000, "levelup": 12800000, 'interest': 0.001, "level": "灵铜会员"}, + "8": {"savemax": 128000000, "levelup": 25600000, 'interest': 0.001, "level": "灵银会员"}, + "9": {"savemax": 256000000, "levelup": 51200000, 'interest': 0.001, "level": "灵金会员"}, + "10": {"savemax": 512000000, "levelup": 102400000, 'interest': 0.001, "level": "仙铜会员"}, + "11": {"savemax": 1024000000, "levelup": 204800000, 'interest': 0.001, "level": "仙银会员"}, + "12": {"savemax": 2048000000, "levelup": 409600000, 'interest': 0.001, "level": "仙金会员"}, + "13": {"savemax": 4096000000, "levelup": 819200000, 'interest': 0.001, "level": "天铜会员"}, + "14": {"savemax": 8192000000, "levelup": 1638400000, 'interest': 0.001, "level": "天银会员"}, + "15": {"savemax": 16384000000, "levelup": 3276800000, 'interest': 0.001, "level": "天金会员"}, + "16": {"savemax": 32768000000, "levelup": 6553600000, 'interest': 0.001, "level": "玉铜会员"}, + "17": {"savemax": 65536000000, "levelup": 13107200000, 'interest': 0.001, "level": "玉银会员"}, + "18": {"savemax": 131072000000, "levelup": 26214400000, 'interest': 0.001, "level": "玉金会员"}, + "19": {"savemax": 262144000000, "levelup": 52428800000, 'interest': 0.001, "level": "圣铜会员"}, + "20": {"savemax": 524288000000, "levelup": 104857600000, 'interest': 0.001, "level": "圣银会员"}, + "21": {"savemax": 1048576000000, "levelup": 209715200000, 'interest': 0.001, "level": "圣金会员"}, + "22": {"savemax": 2097152000000, "levelup": 419430400000, 'interest': 0.001, "level": "道铜会员"}, + "23": {"savemax": 4194304000000, "levelup": 838860800000, 'interest': 0.001, "level": "道银会员"}, + "24": {"savemax": 8388608000000, "levelup": 1677721600000, 'interest': 0.001, "level": "道金会员"}, + "25": {"savemax": 16777216000000, "levelup": 3355443200000, 'interest': 0.001, "level": "混元铜会员"}, + "26": {"savemax": 33554432000000, "levelup": 6710886400000, 'interest': 0.001, "level": "混元银会员"}, + "27": {"savemax": 67108864000000, "levelup": 13421772800000, 'interest': 0.001, "level": "混元金会员"}, + "28": {"savemax": 134217728000000, "levelup": 26843545600000, 'interest': 0.001, "level": "太乙铜会员"}, + "29": {"savemax": 268435456000000, "levelup": 53687091200000, 'interest': 0.001, "level": "太乙银会员"}, + "30": {"savemax": 536870912000000, "levelup": 107374182400000, 'interest': 0.001, "level": "太乙金会员"}, + "31": {"savemax": 1073741824000000, "levelup": 214748364800000, 'interest': 0.001, "level": "太虚铜会员"}, + "32": {"savemax": 2147483648000000, "levelup": 429496729600000, 'interest': 0.001, "level": "太虚银会员"}, + "33": {"savemax": 4294967296000000, "levelup": 858993459200000, 'interest': 0.001, "level": "太虚金会员"}, + "34": {"savemax": 8589934592000000, "levelup": 1717986918400000, 'interest': 0.001, "level": "鸿蒙铜会员"}, + "35": {"savemax": 17179869184000000, "levelup": 3435973836800000, 'interest': 0.001, "level": "鸿蒙银会员"}, + "36": {"savemax": 34359738368000000, "levelup": 6871947673600000, 'interest': 0.001, "level": "鸿蒙金会员"}, + "37": {"savemax": 68719476736000000, "levelup": 13743895347200000, 'interest': 0.001, "level": "盘古铜会员"}, + "38": {"savemax": 137438953472000000, "levelup": 27487790694400000, 'interest': 0.001, "level": "盘古银会员"}, + "39": {"savemax": 274877906944000000, "levelup": 54975581388800000, 'interest': 0.001, "level": "盘古金会员"}, + "40": {"savemax": 549755813888000000, "levelup": 109951162777600000, 'interest': 0.001, "level": "洪荒铜会员"}, + "41": {"savemax": 1099511627776000000, "levelup": 219902325555200000, 'interest': 0.001, "level": "洪荒银会员"}, + "42": {"savemax": 2199023255552000000, "levelup": 439804651110400000, 'interest': 0.001, "level": "洪荒金会员"}, + "43": {"savemax": 4398046511104000000, "levelup": 879609302220800000, 'interest': 0.001, "level": "开天铜会员"}, + "44": {"savemax": 8796093022208000000, "levelup": 1759218604441600000, 'interest': 0.001, "level": "开天银会员"}, + "45": {"savemax": 17592186044416000000, "levelup": 3518437208883200000, 'interest': 0.001, "level": "开天金会员"}, + "46": {"savemax": 35184372088832000000, "levelup": 7036874417766400000, 'interest': 0.001, "level": "太初铜会员"}, + "47": {"savemax": 70368744177664000000, "levelup": 14073748835532800000, 'interest': 0.001, "level": "太初银会员"}, + "48": {"savemax": 140737488355328000000, "levelup": 0, 'interest': 0.001, "level": "太初金会员"}, } } @@ -27,7 +68,7 @@ def get_config(): if key not in list(config.keys()): config[key] = CONFIG[key] savef(config) - except: + except FileNotFoundError: config = CONFIG savef(config) return config diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_base/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_base/__init__.py index c9bb416e..36258814 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_base/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_base/__init__.py @@ -20,25 +20,23 @@ from nonebot.params import CommandArg from ..xiuxian_utils.data_source import jsondata from ..xiuxian_utils.xiuxian2_handle import ( - XiuxianDateManage, XiuxianJsonDate, OtherSet, - UserBuffDate, XIUXIAN_IMPART_BUFF, leave_harm_time + XiuxianDataManager, XiuxianJsonData, OtherSet, + UserBuffData, leave_harm_time ) -from ..xiuxian_config import XiuConfig, JsonConfig, convert_rank +from ..xiuxian_config import XiuConfig, JsonConfig from ..xiuxian_utils.utils import ( check_user, get_msg_pic, number_to, CommandObjectID, - Txt2Img, send_msg_handler + Txt2Img, send_msg_handler, handle_send ) -from ..xiuxian_utils.item_json import Items +from ..xiuxian_utils.item_json import Items, FANTASYNAMEDATAPATH items = Items() # 定时任务 scheduler = require("nonebot_plugin_apscheduler").scheduler cache_help = {} cache_level_help = {} -sql_message = XiuxianDateManage() # sql类 -xiuxian_impart = XIUXIAN_IMPART_BUFF() run_xiuxian = on_fullmatch("我要修仙", priority=8, permission=GROUP, block=True) restart = on_fullmatch("重入仙途", permission=GROUP, priority=7, block=True) @@ -56,16 +54,16 @@ gm_command = on_command("神秘力量", permission=SUPERUSER, priority=10, block=True) gmm_command = on_command("轮回力量", permission=SUPERUSER, priority=10, block=True) cz = on_command('创造力量', permission=SUPERUSER, priority=15,block=True) -rob_stone = on_command("抢劫", aliases={"拿来吧你"}, priority=5, permission=GROUP, block=True) +rob_stone = on_command("抢灵石", aliases={"拿来吧你"}, priority=5, permission=GROUP, block=True) restate = on_command("重置状态", permission=SUPERUSER, priority=12, block=True) set_xiuxian = on_command("启用修仙功能", aliases={'禁用修仙功能'}, permission=GROUP and (SUPERUSER | GROUP_ADMIN | GROUP_OWNER), priority=5, block=True) user_leveluprate = on_command('我的突破概率', aliases={'突破概率'}, priority=5, permission=GROUP, block=True) -user_stamina = on_command('我的体力', aliases={'体力'}, priority=5, permission=GROUP, block=True) +stamina = on_command('我的体力', aliases={'体力'}, priority=5, permission=GROUP, block=True) xiuxian_updata_level = on_fullmatch('修仙适配', priority=15, permission=GROUP, block=True) xiuxian_uodata_data = on_fullmatch('更新记录', priority=15, permission=GROUP, block=True) level_help = on_command('境界帮助', aliases={"灵根帮助", "品阶帮助"}, priority=15, permission=GROUP,block=True) -__xiuxian_notes__ = f""" +__xiuxian_notes__ = """ 详情: 1、我要修仙:进入修仙模式 2、我的修仙信息:获取修仙数据 @@ -98,7 +96,7 @@ -__xiuxian_updata_data__ = f""" +__xiuxian_updata_data__ = """ 详情: #更新2023.6.14 1.修复已知bug @@ -132,7 +130,7 @@ 10.重构合成系统 """.strip() -__level_help__ = f""" +__level_help__ = """ 详情: --灵根帮助-- 轮回——异界——机械——混沌 @@ -168,20 +166,17 @@ # 重置每日签到 @scheduler.scheduled_job("cron", hour=0, minute=0) async def xiuxian_sing_(): - sql_message.sign_remake() - logger.opt(colors=True).info(f"每日修仙签到重置成功!") + await XiuxianDataManager().sign_remake() + logger.opt(colors=True).info("每日修仙签到重置成功!") @xiuxian_uodata_data.handle(parameterless=[Cooldown(at_sender=False)]) async def mix_elixir_help_(bot: Bot, event: GroupMessageEvent): """更新记录""" + isUser, user_info, msg = await check_user(event) bot, send_group_id = await assign_bot(bot=bot, event=event) msg = __xiuxian_updata_data__ - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await xiuxian_uodata_data.finish() @@ -189,40 +184,37 @@ async def mix_elixir_help_(bot: Bot, event: GroupMessageEvent): async def run_xiuxian_(bot: Bot, event: GroupMessageEvent): """加入修仙""" bot, send_group_id = await assign_bot(bot=bot, event=event) - user_id = event.get_user_id() - user_name = ( - event.sender.card if event.sender.card else event.sender.nickname - ) # 获取为用户名 - root, root_type = XiuxianJsonDate().linggen_get() # 获取灵根,灵根类型 - rate = sql_message.get_root_rate(root_type) # 灵根倍率 + isUser, user_info, msg = await check_user(event) + user_id = int(event.get_user_id()) + user_name = event.sender.nickname + + # 官机的话随机生成道号 + if not user_name or user_name.strip() == "": + try: + from ..xiuxian_utils.xiuxian2_handle import XiuXianNameGenerator + name_generator = XiuXianNameGenerator(data_dir=FANTASYNAMEDATAPATH) + user_name = name_generator.get_name(1, {})[0] + except Exception: + user_name = "无名之人" + + root, root_type = XiuxianJsonData().linggen_get() # 获取灵根,灵根类型 + rate = await XiuxianDataManager().get_root_rate(root_type) # 灵根倍率 power = 100 * float(rate) # 战力=境界的power字段 * 灵根的rate字段 - create_time = str(datetime.now()) - is_new_user, msg = sql_message.create_user( + create_time = datetime.now() + is_new_user, msg = await XiuxianDataManager().create_user( user_id, root, root_type, int(power), create_time, user_name ) try: if is_new_user: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - isUser, user_msg, msg = check_user(event) + await handle_send(bot, event, send_group_id, msg) + isUser, user_msg, msg = await check_user(event) if user_msg['hp'] is None or user_msg['hp'] == 0 or user_msg['hp'] == 0: - sql_message.update_user_hp(user_id) + await XiuxianDataManager().update_user_hp(user_id) await asyncio.sleep(1) - if XiuConfig().img: - msg = "耳边响起一个神秘人的声音:不要忘记仙途奇缘!!\n不知道怎么玩的话可以发送 修仙帮助 喔!!" - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "耳边响起一个神秘人的声音:不要忘记仙途奇缘!!\n不知道怎么玩的话可以发送 修仙帮助 喔!!" + await handle_send(bot, event, send_group_id, msg) else: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) except ActionFailed: await run_xiuxian.finish("修仙界网络堵塞,发送失败!", reply_message=True) @@ -231,23 +223,15 @@ async def run_xiuxian_(bot: Bot, event: GroupMessageEvent): async def sign_in_(bot: Bot, event: GroupMessageEvent): """修仙签到""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sign_in.finish() user_id = user_info['user_id'] - result = sql_message.get_sign(user_id) + result = await XiuxianDataManager().get_sign(user_id) msg = result try: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sign_in.finish() except ActionFailed: await sign_in.finish("修仙界网络堵塞,发送失败!", reply_message=True) @@ -298,44 +282,34 @@ async def level_help_(bot: Bot, event: GroupMessageEvent, session_id: int = Comm async def restart_(bot: Bot, event: GroupMessageEvent, state: T_State): """刷新灵根信息""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await restart.finish() if user_info['stone'] < XiuConfig().remake: msg = "你的灵石还不够呢,快去赚点灵石吧!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await restart.finish() state["user_id"] = user_info['user_id'] # 将用户信息存储在状态中 linggen_options = [] for _ in range(10): - name, root_type = XiuxianJsonDate().linggen_get() + name, root_type = XiuxianJsonData().linggen_get() linggen_options.append((name, root_type)) linggen_list_msg = "\n".join([f"{i+1}. {name} ({root_type})" for i, (name, root_type) in enumerate(linggen_options)]) msg = f"请从以下灵根中选择一个:\n{linggen_list_msg}\n请输入对应的数字选择 (1-10):" state["linggen_options"] = linggen_options - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) @restart.receive() async def handle_user_choice(bot: Bot, event: GroupMessageEvent, state: T_State): + isUser, user_info, msg = await check_user(event) + bot, send_group_id = await assign_bot(bot=bot, event=event) user_choice = event.get_plaintext().strip() linggen_options = state["linggen_options"] user_id = state["user_id"] # 从状态中获取用户ID @@ -349,14 +323,10 @@ async def handle_user_choice(bot: Bot, event: GroupMessageEvent, state: T_State) else: msg = "输入有误,帮你自动选择最佳灵根了嗷!\n" - msg += sql_message.ramaker(selected_name, selected_root_type, user_id) + msg += await XiuxianDataManager().ramaker(selected_name, selected_root_type, user_id) try: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=event.group_id, message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=event.group_id, message=msg) + await handle_send(bot, event, send_group_id, msg) except ActionFailed: await bot.send_group_msg(group_id=event.group_id, message="修仙界网络堵塞,发送失败!") await restart.finish() @@ -366,64 +336,49 @@ async def handle_user_choice(bot: Bot, event: GroupMessageEvent, state: T_State) async def rank_(bot: Bot, event: GroupMessageEvent): """排行榜""" bot, send_group_id = await assign_bot(bot=bot, event=event) + isUser, user_info, msg = await check_user(event) message = str(event.message) rank_msg = r'[\u4e00-\u9fa5]+' message = re.findall(rank_msg, message) if message: message = message[0] if message in ["排行榜", "修仙排行榜", "境界排行榜", "修为排行榜"]: - p_rank = sql_message.realm_top() - msg = f"✨位面境界排行榜TOP50✨\n" + p_rank = await XiuxianDataManager().realm_top() + msg = "✨位面境界排行榜TOP50✨\n" num = 0 for i in p_rank: num += 1 msg += f"第{num}位 {i[0]} {i[1]},修为{number_to(i[2])}\n" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await rank.finish() elif message == "灵石排行榜": - a_rank = sql_message.stone_top() - msg = f"✨位面灵石排行榜TOP50✨\n" + a_rank = await XiuxianDataManager().stone_top() + msg = "✨位面灵石排行榜TOP50✨\n" num = 0 for i in a_rank: num += 1 msg += f"第{num}位 {i[0]} 灵石:{number_to(i[1])}枚\n" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await rank.finish() elif message == "战力排行榜": - c_rank = sql_message.power_top() - msg = f"✨位面战力排行榜TOP50✨\n" + c_rank = await XiuxianDataManager().power_top() + msg = "✨位面战力排行榜TOP50✨\n" num = 0 for i in c_rank: num += 1 msg += f"第{num}位 {i[0]} 战力:{number_to(i[1])}\n" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await rank.finish() elif message in ["宗门排行榜", "宗门建设度排行榜"]: - s_rank = sql_message.scale_top() - msg = f"✨位面宗门建设排行榜TOP50✨\n" + s_rank = await XiuxianDataManager().scale_top() + msg = "✨位面宗门建设排行榜TOP50✨\n" num = 0 for i in s_rank: num += 1 msg += f"第{num}位 {i[1]} 建设度:{number_to(i[2])}\n" if num == 50: break - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await rank.finish() @@ -431,37 +386,25 @@ async def rank_(bot: Bot, event: GroupMessageEvent): async def remaname_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """修改道号""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await remaname.finish() user_id = user_info['user_id'] user_name = args.extract_plain_text().strip() len_username = len(user_name.encode('gbk')) if len_username > 20: msg = "道号长度过长,请修改后重试!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await remaname.finish() elif len_username < 1: if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + "道友确定要改名无名?还请三思。") + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + "道友确定要改名无名?还请三思。") await bot.send_group_msg(group_id=event.group_id, message=MessageSegment.image(pic)) await remaname.finish() else: - msg = sql_message.update_user_name(user_id, user_name) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = await XiuxianDataManager().update_user_name(user_id, user_name) + await handle_send(bot, event, send_group_id, msg) await remaname.finish() @@ -469,41 +412,37 @@ async def remaname_(bot: Bot, event: GroupMessageEvent, args: Message = CommandA async def level_up_(bot: Bot, event: GroupMessageEvent): """突破""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await level_up.finish() user_id = user_info['user_id'] if user_info['hp'] is None: # 判断用户气血是否为空 - sql_message.update_user_hp(user_id) - user_msg = sql_message.get_user_info_with_id(user_id) # 用户信息 + await XiuxianDataManager().update_user_hp(user_id) + user_msg = await XiuxianDataManager().get_user_infos_by_ids(user_id) # 用户信息 user_leveluprate = int(user_msg['level_up_rate']) # 用户失败次数加成 - level_cd = user_msg['level_up_cd'] + user_time = await XiuxianDataManager().get_user_time(user_id) + level_cd = user_time['level_up_time'] + if level_cd is None: + await XiuxianDataManager().updata_level_cd(user_id) + level_cd = datetime.now() if level_cd: # 校验是否存在CD time_now = datetime.now() cd = OtherSet().date_diff(time_now, level_cd) # 获取second - if cd < XiuConfig().level_up_cd * 60: + if cd < XiuConfig().level_up_time * 60: # 如果cd小于配置的cd,返回等待时间 - msg = f"目前无法突破,还需要{XiuConfig().level_up_cd - (cd // 60)}分钟" - sql_message.update_user_stamina(user_id, 12, 1) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = f"目前无法突破,还需要{XiuConfig().level_up_time - (cd // 60)}分钟" + await XiuxianDataManager().update_user_stamina(user_id, 12, 1) + await handle_send(bot, event, send_group_id, msg) await level_up.finish() else: pass level_name = user_msg['level'] # 用户境界 level_rate = jsondata.level_rate_data()[level_name] # 对应境界突破的概率 - user_backs = sql_message.get_back_msg(user_id) # list(back) + user_backs = await XiuxianDataManager().get_back_msg(user_id) # list(back) items = Items() pause_flag = False elixir_name = None @@ -515,23 +454,15 @@ async def level_up_(bot: Bot, event: GroupMessageEvent): elixir_name = back['goods_name'] elixir_desc = items.get_data_by_item_id(1999)['desc'] break - main_rate_buff = UserBuffDate(user_id).get_user_main_buff_data()#功法突破概率提升,别忘了还有渡厄突破 + main_rate_buff = await UserBuffData(user_id).get_user_main_buff_data()#功法突破概率提升,别忘了还有渡厄突破 number = main_rate_buff['number'] if main_rate_buff is not None else 0 if pause_flag: msg = f"由于检测到背包有丹药:{elixir_name},效果:{elixir_desc},突破已经准备就绪\n请发送 ,【渡厄突破】 或 【直接突破】来选择是否使用丹药突破!\n本次突破概率为:{level_rate + user_leveluprate + number}% " - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await level_up.finish() else: msg = f"由于检测到背包没有【渡厄丹】,突破已经准备就绪\n请发送,【直接突破】来突破!请注意,本次突破失败将会损失部分修为!\n本次突破概率为:{level_rate + user_leveluprate + number}% " - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await level_up.finish() @@ -539,33 +470,29 @@ async def level_up_(bot: Bot, event: GroupMessageEvent): async def level_up_zj_(bot: Bot, event: GroupMessageEvent): """直接突破""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await level_up_zj.finish() user_id = user_info['user_id'] if user_info['hp'] is None: # 判断用户气血是否为空 - sql_message.update_user_hp(user_id) - user_msg = sql_message.get_user_info_with_id(user_id) # 用户信息 - level_cd = user_msg['level_up_cd'] + await XiuxianDataManager().update_user_hp(user_id) + user_msg = await XiuxianDataManager().get_user_infos_by_ids(user_id) # 用户信息 + user_time = await XiuxianDataManager().get_user_time(user_id) + level_cd = user_time['level_up_time'] + if level_cd is None: + await XiuxianDataManager().updata_level_cd(user_id) + level_cd = datetime.now() if level_cd: # 校验是否存在CD time_now = datetime.now() cd = OtherSet().date_diff(time_now, level_cd) # 获取second - if cd < XiuConfig().level_up_cd * 60: + if cd < XiuConfig().level_up_time * 60: # 如果cd小于配置的cd,返回等待时间 - msg = f"目前无法突破,还需要{XiuConfig().level_up_cd - (cd // 60)}分钟" - sql_message.update_user_stamina(user_id, 6, 1) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = f"目前无法突破,还需要{XiuConfig().level_up_time - (cd // 60)}分钟" + await XiuxianDataManager().update_user_stamina(user_id, 6, 1) + await handle_send(bot, event, send_group_id, msg) await level_up_zj.finish() else: pass @@ -573,56 +500,44 @@ async def level_up_zj_(bot: Bot, event: GroupMessageEvent): exp = user_msg['exp'] # 用户修为 level_rate = jsondata.level_rate_data()[level_name] # 对应境界突破的概率 leveluprate = int(user_msg['level_up_rate']) # 用户失败次数加成 - main_rate_buff = UserBuffDate(user_id).get_user_main_buff_data()#功法突破概率提升,别忘了还有渡厄突破 - main_exp_buff = UserBuffDate(user_id).get_user_main_buff_data()#功法突破扣修为减少 + main_rate_buff = await UserBuffData(user_id).get_user_main_buff_data()#功法突破概率提升,别忘了还有渡厄突破 + main_exp_buff = await UserBuffData(user_id).get_user_main_buff_data()#功法突破扣修为减少 exp_buff = main_exp_buff['exp_buff'] if main_exp_buff is not None else 0 number = main_rate_buff['number'] if main_rate_buff is not None else 0 - le = OtherSet().get_type(exp, level_rate + leveluprate + number, level_name) + le = await OtherSet().get_type(exp, level_rate + leveluprate + number, level_name) if le == "失败": # 突破失败 - sql_message.updata_level_cd(user_id) # 更新突破CD + await XiuxianDataManager().updata_level_cd(user_id) # 更新突破CD # 失败惩罚,随机扣减修为 percentage = random.randint( XiuConfig().level_punishment_floor, XiuConfig().level_punishment_limit ) now_exp = int(int(exp) * ((percentage / 100) * (1 - exp_buff))) #功法突破扣修为减少 - sql_message.update_j_exp(user_id, now_exp) # 更新用户修为 - nowhp = user_msg['hp'] - (now_exp / 2) if (user_msg['hp'] - (now_exp / 2)) > 0 else 1 - nowmp = user_msg['mp'] - now_exp if (user_msg['mp'] - now_exp) > 0 else 1 - sql_message.update_user_hp_mp(user_id, nowhp, nowmp) # 修为掉了,血量、真元也要掉 + await XiuxianDataManager().update_exp(user_id, now_exp, 1) # 更新用户修为 + nowhp = float(user_msg['hp']) - (float(now_exp) / 2) if (float(user_msg['hp']) - (float(now_exp) / 2)) > 0 else 1 + nowmp = float(user_msg['mp']) - float(now_exp) if (float(user_msg['mp']) - float(now_exp)) > 0 else 1 + await XiuxianDataManager().update_user_hp_mp(user_id, nowhp, nowmp) # 修为掉了,血量、真元也要掉 update_rate = 1 if int(level_rate * XiuConfig().level_up_probability) <= 1 else int( level_rate * XiuConfig().level_up_probability) # 失败增加突破几率 - sql_message.update_levelrate(user_id, leveluprate + update_rate) - msg = f"道友突破失败,境界受损,修为减少{now_exp},下次突破成功率增加{update_rate}%,道友不要放弃!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await XiuxianDataManager().update_levelrate(user_id, leveluprate + update_rate) + msg = f"道友突破失败,境界受损,修为减少{number_to(now_exp)},下次突破成功率增加{update_rate}%,道友不要放弃!" + await handle_send(bot, event, send_group_id, msg) await level_up_zj.finish() - elif type(le) == list: + elif type(le) is list: # 突破成功 - sql_message.updata_level(user_id, le[0]) # 更新境界 - sql_message.update_power2(user_id) # 更新战力 - sql_message.updata_level_cd(user_id) # 更新CD - sql_message.update_levelrate(user_id, 0) - sql_message.update_user_hp(user_id) # 重置用户HP,mp,atk状态 + await XiuxianDataManager().updata_level(user_id, le[0]) # 更新境界 + await XiuxianDataManager().update_power2(user_id) # 更新战力 + await XiuxianDataManager().updata_level_cd(user_id) # 更新CD + await XiuxianDataManager().update_levelrate(user_id, 0) + await XiuxianDataManager().update_user_hp(user_id) # 重置用户HP,mp,atk状态 msg = f"恭喜道友突破{le[0]}成功!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await level_up_zj.finish() else: # 最高境界 msg = le - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await level_up_zj.finish() @@ -630,33 +545,29 @@ async def level_up_zj_(bot: Bot, event: GroupMessageEvent): async def level_up_drjd_(bot: Bot, event: GroupMessageEvent): """渡厄 金丹 突破""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await level_up_drjd.finish() user_id = user_info['user_id'] if user_info['hp'] is None: # 判断用户气血是否为空 - sql_message.update_user_hp(user_id) - user_msg = sql_message.get_user_info_with_id(user_id) # 用户信息 - level_cd = user_msg['level_up_cd'] + await XiuxianDataManager().update_user_hp(user_id) + user_msg = await XiuxianDataManager().get_user_infos_by_ids(user_id) # 用户信息 + user_time = await XiuxianDataManager().get_user_time(user_id) + level_cd = user_time['level_up_time'] + if level_cd is None: + await XiuxianDataManager().updata_level_cd(user_id) + level_cd = datetime.now() if level_cd: # 校验是否存在CD time_now = datetime.now() cd = OtherSet().date_diff(time_now, level_cd) # 获取second - if cd < XiuConfig().level_up_cd * 60: + if cd < XiuConfig().level_up_time * 60: # 如果cd小于配置的cd,返回等待时间 - msg = f"目前无法突破,还需要{XiuConfig().level_up_cd - (cd // 60)}分钟" - sql_message.update_user_stamina(user_id, 4, 1) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = f"目前无法突破,还需要{XiuConfig().level_up_time - (cd // 60)}分钟" + await XiuxianDataManager().update_user_stamina(user_id, 4, 1) + await handle_send(bot, event, send_group_id, msg) await level_up_drjd.finish() else: pass @@ -665,10 +576,10 @@ async def level_up_drjd_(bot: Bot, event: GroupMessageEvent): exp = user_msg['exp'] # 用户修为 level_rate = jsondata.level_rate_data()[level_name] # 对应境界突破的概率 user_leveluprate = int(user_msg['level_up_rate']) # 用户失败次数加成 - main_rate_buff = UserBuffDate(user_id).get_user_main_buff_data()#功法突破概率提升 + main_rate_buff = await UserBuffData(user_id).get_user_main_buff_data()#功法突破概率提升 number = main_rate_buff['number'] if main_rate_buff is not None else 0 - le = OtherSet().get_type(exp, level_rate + user_leveluprate + number, level_name) - user_backs = sql_message.get_back_msg(user_id) # list(back) + le = await OtherSet().get_type(exp, level_rate + user_leveluprate + number, level_name) + user_backs = await XiuxianDataManager().get_back_msg(user_id) # list(back) pause_flag = False if user_backs is not None: for back in user_backs: @@ -679,73 +590,57 @@ async def level_up_drjd_(bot: Bot, event: GroupMessageEvent): if not pause_flag: msg = f"道友突破需要使用{elixir_name},但您的背包中没有该丹药!" - sql_message.update_user_stamina(user_id, 4, 1) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await XiuxianDataManager().update_user_stamina(user_id, 4, 1) + await handle_send(bot, event, send_group_id, msg) await level_up_drjd.finish() if le == "失败": # 突破失败 - sql_message.updata_level_cd(user_id) # 更新突破CD + await XiuxianDataManager().updata_level_cd(user_id) # 更新突破CD if pause_flag: # 使用丹药减少的sql - sql_message.update_back_j(user_id, 1998, use_key=1) + await XiuxianDataManager().update_back_j(user_id, 1998, use_key=1) now_exp = int(int(exp) * 0.1) - sql_message.update_exp(user_id, now_exp) # 渡厄金丹增加用户修为 + await XiuxianDataManager().update_exp(user_id, now_exp, 0) # 渡厄金丹增加用户修为 update_rate = 1 if int(level_rate * XiuConfig().level_up_probability) <= 1 else int( level_rate * XiuConfig().level_up_probability) # 失败增加突破几率 - sql_message.update_levelrate(user_id, user_leveluprate + update_rate) + await XiuxianDataManager().update_levelrate(user_id, user_leveluprate + update_rate) msg = f"道友突破失败,但是使用了丹药{elixir_name},本次突破失败不扣除修为反而增加了一成,下次突破成功率增加{update_rate}%!!" else: # 失败惩罚,随机扣减修为 percentage = random.randint( XiuConfig().level_punishment_floor, XiuConfig().level_punishment_limit ) - main_exp_buff = UserBuffDate(user_id).get_user_main_buff_data()#功法突破扣修为减少 + main_exp_buff = await UserBuffData(user_id).get_user_main_buff_data()#功法突破扣修为减少 exp_buff = main_exp_buff['exp_buff'] if main_exp_buff is not None else 0 now_exp = int(int(exp) * ((percentage / 100) * exp_buff)) - sql_message.update_j_exp(user_id, now_exp) # 更新用户修为 + await XiuxianDataManager().update_exp(user_id, now_exp, 1) # 更新用户修为 nowhp = user_msg['hp'] - (now_exp / 2) if (user_msg['hp'] - (now_exp / 2)) > 0 else 1 nowmp = user_msg['mp'] - now_exp if (user_msg['mp'] - now_exp) > 0 else 1 - sql_message.update_user_hp_mp(user_id, nowhp, nowmp) # 修为掉了,血量、真元也要掉 + await XiuxianDataManager().update_user_hp_mp(user_id, nowhp, nowmp) # 修为掉了,血量、真元也要掉 update_rate = 1 if int(level_rate * XiuConfig().level_up_probability) <= 1 else int( level_rate * XiuConfig().level_up_probability) # 失败增加突破几率 - sql_message.update_levelrate(user_id, user_leveluprate + update_rate) - msg = f"没有检测到{elixir_name},道友突破失败,境界受损,修为减少{now_exp},下次突破成功率增加{update_rate}%,道友不要放弃!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await XiuxianDataManager().update_levelrate(user_id, user_leveluprate + update_rate) + msg = f"没有检测到{elixir_name},道友突破失败,境界受损,修为减少{number_to(now_exp)},下次突破成功率增加{update_rate}%,道友不要放弃!" + await handle_send(bot, event, send_group_id, msg) await level_up_drjd.finish() - elif type(le) == list: + elif type(le) is list: # 突破成功 - sql_message.updata_level(user_id, le[0]) # 更新境界 - sql_message.update_power2(user_id) # 更新战力 - sql_message.updata_level_cd(user_id) # 更新CD - sql_message.update_levelrate(user_id, 0) - sql_message.update_user_hp(user_id) # 重置用户HP,mp,atk状态 + await XiuxianDataManager().updata_level(user_id, le[0]) # 更新境界 + await XiuxianDataManager().update_power2(user_id) # 更新战力 + await XiuxianDataManager().updata_level_cd(user_id) # 更新CD + await XiuxianDataManager().update_levelrate(user_id, 0) + await XiuxianDataManager().update_user_hp(user_id) # 重置用户HP,mp,atk状态 now_exp = int(int(exp) * 0.1) - sql_message.update_exp(user_id, now_exp) # 渡厄金丹增加用户修为 + await XiuxianDataManager().update_exp(user_id, now_exp, 0) # 渡厄金丹增加用户修为 msg = f"恭喜道友突破{le[0]}成功,因为使用了渡厄金丹,修为也增加了一成!!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await level_up_drjd.finish() else: # 最高境界 msg = le - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await level_up_drjd.finish() @@ -753,33 +648,26 @@ async def level_up_drjd_(bot: Bot, event: GroupMessageEvent): async def level_up_dr_(bot: Bot, event: GroupMessageEvent): """渡厄 突破""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await level_up_dr.finish() user_id = user_info['user_id'] if user_info['hp'] is None: # 判断用户气血是否为空 - sql_message.update_user_hp(user_id) - user_msg = sql_message.get_user_info_with_id(user_id) # 用户信息 - level_cd = user_msg['level_up_cd'] + await XiuxianDataManager().update_user_hp(user_id) + user_msg = await XiuxianDataManager().get_user_infos_by_ids(user_id) # 用户信息 + user_time = await XiuxianDataManager().get_user_time(user_id) + level_cd = user_time['level_up_time'] or datetime.now() if level_cd: # 校验是否存在CD time_now = datetime.now() cd = OtherSet().date_diff(time_now, level_cd) # 获取second - if cd < XiuConfig().level_up_cd * 60: + if cd < XiuConfig().level_up_time * 60: # 如果cd小于配置的cd,返回等待时间 - msg = f"目前无法突破,还需要{XiuConfig().level_up_cd - (cd // 60)}分钟" - sql_message.update_user_stamina(user_id, 8, 1) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = f"目前无法突破,还需要{XiuConfig().level_up_time - (cd // 60)}分钟" + await XiuxianDataManager().update_user_stamina(user_id, 8, 1) + await handle_send(bot, event, send_group_id, msg) await level_up_dr.finish() else: pass @@ -788,10 +676,10 @@ async def level_up_dr_(bot: Bot, event: GroupMessageEvent): exp = user_msg['exp'] # 用户修为 level_rate = jsondata.level_rate_data()[level_name] # 对应境界突破的概率 user_leveluprate = int(user_msg['level_up_rate']) # 用户失败次数加成 - main_rate_buff = UserBuffDate(user_id).get_user_main_buff_data()#功法突破概率提升 + main_rate_buff = await UserBuffData(user_id).get_user_main_buff_data()#功法突破概率提升 number = main_rate_buff['number'] if main_rate_buff is not None else 0 - le = OtherSet().get_type(exp, level_rate + user_leveluprate + number, level_name) - user_backs = sql_message.get_back_msg(user_id) # list(back) + le = await OtherSet().get_type(exp, level_rate + user_leveluprate + number, level_name) + user_backs = await XiuxianDataManager().get_back_msg(user_id) # list(back) pause_flag = False if user_backs is not None: for back in user_backs: @@ -802,69 +690,55 @@ async def level_up_dr_(bot: Bot, event: GroupMessageEvent): if not pause_flag: msg = f"道友突破需要使用{elixir_name},但您的背包中没有该丹药!" - sql_message.update_user_stamina(user_id, 8, 1) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await XiuxianDataManager().update_user_stamina(user_id, 8, 1) + await handle_send(bot, event, send_group_id, msg) await level_up_dr.finish() if le == "失败": # 突破失败 - sql_message.updata_level_cd(user_id) # 更新突破CD + await XiuxianDataManager().updata_level_cd(user_id) # 更新突破CD if pause_flag: # todu,丹药减少的sql - sql_message.update_back_j(user_id, 1999, use_key=1) + await XiuxianDataManager().update_back_j(user_id, 1999, use_key=1) update_rate = 1 if int(level_rate * XiuConfig().level_up_probability) <= 1 else int( level_rate * XiuConfig().level_up_probability) # 失败增加突破几率 - sql_message.update_levelrate(user_id, user_leveluprate + update_rate) + await XiuxianDataManager().update_levelrate(user_id, user_leveluprate + update_rate) msg = f"道友突破失败,但是使用了丹药{elixir_name},本次突破失败不扣除修为下次突破成功率增加{update_rate}%,道友不要放弃!" else: # 失败惩罚,随机扣减修为 percentage = random.randint( XiuConfig().level_punishment_floor, XiuConfig().level_punishment_limit ) - main_exp_buff = UserBuffDate(user_id).get_user_main_buff_data()#功法突破扣修为减少 + main_exp_buff = await UserBuffData(user_id).get_user_main_buff_data() # 功法突破扣修为减少 exp_buff = main_exp_buff['exp_buff'] if main_exp_buff is not None else 0 now_exp = int(int(exp) * ((percentage / 100) * (1 - exp_buff))) - sql_message.update_j_exp(user_id, now_exp) # 更新用户修为 - nowhp = user_msg['hp'] - (now_exp / 2) if (user_msg['hp'] - (now_exp / 2)) > 0 else 1 - nowmp = user_msg['mp'] - now_exp if (user_msg['mp'] - now_exp) > 0 else 1 - sql_message.update_user_hp_mp(user_id, nowhp, nowmp) # 修为掉了,血量、真元也要掉 + await XiuxianDataManager().update_exp(user_id, now_exp, 1) # 更新用户修为 + nowhp = float(user_msg['hp']) - (float(now_exp) / 2) if (float(user_msg['hp']) - (float(now_exp) / 2)) > 0 else 1 + nowmp = float(user_msg['mp']) - float(now_exp) if (float(user_msg['mp']) - float(now_exp)) > 0 else 1 + await XiuxianDataManager().update_user_hp_mp(user_id, nowhp, nowmp) # 修为掉了,血量、真元也要掉 update_rate = 1 if int(level_rate * XiuConfig().level_up_probability) <= 1 else int( level_rate * XiuConfig().level_up_probability) # 失败增加突破几率 - sql_message.update_levelrate(user_id, user_leveluprate + update_rate) - msg = f"没有检测到{elixir_name},道友突破失败,境界受损,修为减少{now_exp},下次突破成功率增加{update_rate}%,道友不要放弃!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await XiuxianDataManager().update_levelrate(user_id, user_leveluprate + update_rate) + msg = f"没有检测到{elixir_name},道友突破失败,境界受损,修为减少{number_to(now_exp)},下次突破成功率增加{update_rate}%,道友不要放弃!" + await handle_send(bot, event, send_group_id, msg) await level_up_dr.finish() - elif type(le) == list: + elif type(le) is list: # 突破成功 - sql_message.updata_level(user_id, le[0]) # 更新境界 - sql_message.update_power2(user_id) # 更新战力 - sql_message.updata_level_cd(user_id) # 更新CD - sql_message.update_levelrate(user_id, 0) - sql_message.update_user_hp(user_id) # 重置用户HP,mp,atk状态 + await asyncio.gather( + XiuxianDataManager().updata_level(user_id, le[0]), # 更新境界 + XiuxianDataManager().update_power2(user_id), # 更新战力 + XiuxianDataManager().updata_level_cd(user_id), # 更新CD + XiuxianDataManager().update_levelrate(user_id, 0), + XiuxianDataManager().update_user_hp(user_id) # 重置用户HP,mp,atk状态 + ) msg = f"恭喜道友突破{le[0]}成功" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await level_up_dr.finish() else: # 最高境界 msg = le - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await level_up_dr.finish() @@ -872,162 +746,124 @@ async def level_up_dr_(bot: Bot, event: GroupMessageEvent): async def user_leveluprate_(bot: Bot, event: GroupMessageEvent): """我的突破概率""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await user_leveluprate.finish() user_id = user_info['user_id'] - user_msg = sql_message.get_user_info_with_id(user_id) # 用户信息 + user_msg = await XiuxianDataManager().get_user_infos_by_ids(user_id) # 用户信息 leveluprate = int(user_msg['level_up_rate']) # 用户失败次数加成 level_name = user_msg['level'] # 用户境界 level_rate = jsondata.level_rate_data()[level_name] # - main_rate_buff = UserBuffDate(user_id).get_user_main_buff_data()#功法突破概率提升 + main_rate_buff = await UserBuffData(user_id).get_user_main_buff_data()#功法突破概率提升 number = main_rate_buff['number'] if main_rate_buff is not None else 0 msg = f"道友下一次突破成功概率为{level_rate + leveluprate + number}%" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await user_leveluprate.finish() -@user_stamina.handle(parameterless=[Cooldown(at_sender=False)]) +@stamina.handle(parameterless=[Cooldown(at_sender=False)]) async def user_stamina_(bot: Bot, event: GroupMessageEvent): """我的体力信息""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await user_stamina.finish() - msg = f"当前体力:{user_info['user_stamina']}" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await user_stamina.finish() + await handle_send(bot, event, send_group_id, msg) + await stamina.finish() + msg = f"当前体力:{user_info['stamina']}" + await handle_send(bot, event, send_group_id, msg) + await stamina.finish() @give_stone.handle(parameterless=[Cooldown(at_sender=False)]) async def give_stone_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """送灵石""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await give_stone.finish() user_id = user_info['user_id'] user_stone_num = user_info['stone'] give_qq = None # 艾特的时候存到这里 msg = args.extract_plain_text().strip() - stone_num = re.findall(r"\d+", msg) # 灵石数 - nick_name = re.findall(r"\d+", msg) # 道号 - if stone_num: - pass - else: - msg = f"请输入正确的灵石数量!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + stone_num = re.findall(r"\d+", msg) + if not stone_num: + msg = "请输入正确的灵石数量!" + await handle_send(bot, event, send_group_id, msg) await give_stone.finish() + give_stone_num = stone_num[0] if int(give_stone_num) > int(user_stone_num): - msg = f"道友的灵石不够,请重新输入!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友的灵石不够,请重新输入!" + await handle_send(bot, event, send_group_id, msg) await give_stone.finish() + remaining_text = re.sub(r"\d+", "", msg).strip() + for arg in args: if arg.type == "at": give_qq = arg.data.get("qq", "") + if give_qq: if str(give_qq) == str(user_id): - msg = f"请不要送灵石给自己!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请不要送灵石给自己!" + await handle_send(bot, event, send_group_id, msg) await give_stone.finish() else: - give_user = sql_message.get_user_info_with_id(give_qq) + give_user = await XiuxianDataManager().get_user_infos_by_ids(give_qq) if give_user: - sql_message.update_ls(user_id, give_stone_num, 2) # 减少用户灵石 + await XiuxianDataManager().update_ls(user_id, give_stone_num, 1) give_stone_num2 = int(give_stone_num) * 0.1 num = int(give_stone_num) - int(give_stone_num2) - sql_message.update_ls(give_qq, num, 1) # 增加用户灵石 - msg = f"共赠送{number_to(int(give_stone_num))}枚灵石给{give_user['user_name']}道友!收取手续费{int(give_stone_num2)}枚" + await XiuxianDataManager().update_ls(give_qq, num, 0) + msg = f"共赠送{number_to(int(give_stone_num))}枚灵石给{give_user['user_name']}道友!\n收取手续费{number_to(int(give_stone_num2))}枚" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await give_stone.finish() else: - msg = f"对方未踏入修仙界,不可赠送!" + msg = "对方未踏入修仙界,不可赠送!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await give_stone.finish() - if nick_name: - give_message = sql_message.get_user_info_with_name(nick_name[0]) + # 道号 + if remaining_text: + give_message = await XiuxianDataManager().get_user_info_with_name(remaining_text) if give_message: if give_message['user_name'] == user_info['user_name']: - msg = f"请不要送灵石给自己!" + msg = "请不要送灵石给自己!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await give_stone.finish() else: - sql_message.update_ls(user_id, give_stone_num, 2) # 减少用户灵石 + await XiuxianDataManager().update_ls(user_id, give_stone_num, 1) give_stone_num2 = int(give_stone_num) * 0.1 num = int(give_stone_num) - int(give_stone_num2) - sql_message.update_ls(give_message['user_id'], num, 1) # 增加用户灵石 - msg = f"共赠送{number_to(int(give_stone_num))}枚灵石给{give_message['user_name']}道友!收取手续费{int(give_stone_num2)}枚" + await XiuxianDataManager().update_ls(give_message['user_id'], num, 0) + msg = f"共赠送{number_to(int(give_stone_num))}枚灵石给{give_message['user_name']}道友!收取手续费{number_to(int(give_stone_num2))}枚" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await give_stone.finish() else: - msg = f"对方未踏入修仙界,不可赠送!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "对方未踏入修仙界,不可赠送!" + await handle_send(bot, event, send_group_id, msg) await give_stone.finish() else: - msg = f"未获到对方信息,请输入正确的道号!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "未获到对方信息,请输入正确的道号!" + await handle_send(bot, event, send_group_id, msg) await give_stone.finish() @@ -1035,13 +871,9 @@ async def give_stone_(bot: Bot, event: GroupMessageEvent, args: Message = Comman @steal_stone.handle(parameterless=[Cooldown(stamina_cost = 10, at_sender=False)]) async def steal_stone_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await steal_stone.finish() user_id = user_info['user_id'] steal_user = None @@ -1050,43 +882,52 @@ async def steal_stone_(bot: Bot, event: GroupMessageEvent, args: Message = Comma steal_qq = None # 艾特的时候存到这里, 要偷的人 coststone_num = XiuConfig().tou if int(coststone_num) > int(user_stone_num): - msg = f"道友的偷窃准备(灵石)不足,请打工之后再切格瓦拉!" - sql_message.update_user_stamina(user_id, 10, 1) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友的偷窃准备(灵石)不足,请打工之后再切格瓦拉!" + await XiuxianDataManager().update_user_stamina(user_id, 10, 1) + await handle_send(bot, event, send_group_id, msg) await steal_stone.finish() + msg_text = args.extract_plain_text().strip() + remaining_text = re.sub(r"\d+", "", msg_text).strip() + for arg in args: if arg.type == "at": steal_qq = arg.data.get('qq', '') + if steal_qq: if steal_qq == user_id: - msg = f"请不要偷自己刷成就!" - sql_message.update_user_stamina(user_id, 10, 1) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请不要偷自己刷成就!" + await XiuxianDataManager().update_user_stamina(user_id, 10, 1) + await handle_send(bot, event, send_group_id, msg) await steal_stone.finish() else: - steal_user = sql_message.get_user_info_with_id(steal_qq) + steal_user = await XiuxianDataManager().get_user_infos_by_ids(steal_qq) if steal_user: steal_user_stone = steal_user['stone'] else: steal_user is None + elif remaining_text: + steal_message = await XiuxianDataManager().get_user_info_with_name(remaining_text) + if steal_message: + if steal_message['user_name'] == user_info['user_name']: + msg = "请不要偷自己刷成就!" + await XiuxianDataManager().update_user_stamina(user_id, 10, 1) + await handle_send(bot, event, send_group_id, msg) + await steal_stone.finish() + else: + steal_user = steal_message + steal_user_stone = steal_user['stone'] + steal_qq = steal_user['user_id'] + if steal_user: steal_success = random.randint(0, 100) result = OtherSet().get_power_rate(user_info['power'], steal_user['power']) if isinstance(result, int): if int(steal_success) > result: - sql_message.update_ls(user_id, coststone_num, 2) # 减少手续费 - sql_message.update_ls(steal_qq, coststone_num, 1) # 增加被偷的人的灵石 - msg = f"道友偷窃失手了,被对方发现并被派去华哥厕所义务劳工!赔款{coststone_num}灵石" + await XiuxianDataManager().update_ls(user_id, coststone_num, 1) + await XiuxianDataManager().update_ls(steal_qq, coststone_num, 0) + msg = "道友偷窃失手了,被对方发现并被派去华哥厕所义务劳工!\n赔款{coststone_num}灵石" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -1094,40 +935,32 @@ async def steal_stone_(bot: Bot, event: GroupMessageEvent, args: Message = Comma get_stone = random.randint(int(XiuConfig().tou_lower_limit * steal_user_stone), int(XiuConfig().tou_upper_limit * steal_user_stone)) if int(get_stone) > int(steal_user_stone): - sql_message.update_ls(user_id, steal_user_stone, 1) # 增加偷到的灵石 - sql_message.update_ls(steal_qq, steal_user_stone, 2) # 减少被偷的人的灵石 + await XiuxianDataManager().update_ls(user_id, steal_user_stone, 0) + await XiuxianDataManager().update_ls(steal_qq, steal_user_stone, 1) msg = f"{steal_user['user_name']}道友已经被榨干了~" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await steal_stone.finish() else: - sql_message.update_ls(user_id, get_stone, 1) # 增加偷到的灵石 - sql_message.update_ls(steal_qq, get_stone, 2) # 减少被偷的人的灵石 + await XiuxianDataManager().update_ls(user_id, get_stone, 0) + await XiuxianDataManager().update_ls(steal_qq, get_stone, 1) msg = f"共偷取{steal_user['user_name']}道友{number_to(get_stone)}枚灵石!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await steal_stone.finish() else: msg = result - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await steal_stone.finish() else: - msg = f"对方未踏入修仙界,不要对杂修出手!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "对方未踏入修仙界,不要对杂修出手!" + await handle_send(bot, event, send_group_id, msg) await steal_stone.finish() @@ -1135,6 +968,7 @@ async def steal_stone_(bot: Bot, event: GroupMessageEvent, args: Message = Comma @gm_command.handle(parameterless=[Cooldown(at_sender=False)]) async def gm_command_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): bot, send_group_id = await assign_bot(bot=bot, event=event) + isUser, user_info, msg = await check_user(event) give_qq = None # 艾特的时候存到这里 msg_text = args.extract_plain_text().strip().strip() stone_num_match = re.findall(r"\d+", msg_text) # 提取数字 @@ -1148,45 +982,29 @@ async def gm_command_(bot: Bot, event: GroupMessageEvent, args: Message = Comman if arg.type == "at": give_qq = arg.data.get("qq", "") if give_qq: - give_user = sql_message.get_user_info_with_id(give_qq) + give_user = await XiuxianDataManager().get_user_infos_by_ids(give_qq) if give_user: - sql_message.update_ls(give_qq, give_stone_num, 1) # 增加用户灵石 + await XiuxianDataManager().update_ls(give_qq, give_stone_num, 0) # 增加用户灵石 msg = f"共赠送{number_to(give_stone_num)}枚灵石给{give_user['user_name']}道友!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await gm_command.finish() else: - msg = f"对方未踏入修仙界,不可赠送!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "对方未踏入修仙界,不可赠送!" + await handle_send(bot, event, send_group_id, msg) await gm_command.finish() elif nick_name: - give_message = sql_message.get_user_info_with_name(nick_name[0]) + give_message = await XiuxianDataManager().get_user_info_with_name(nick_name[0]) if give_message: - sql_message.update_ls(give_message['user_id'], give_stone_num, 1) # 增加用户灵石 + await XiuxianDataManager().update_ls(give_message['user_id'], give_stone_num, 0) # 增加用户灵石 msg = f"共赠送{number_to(give_stone_num)}枚灵石给{give_message['user_name']}道友!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await gm_command.finish() else: - msg = f"对方未踏入修仙界,不可赠送!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "对方未踏入修仙界,不可赠送!" + await handle_send(bot, event, send_group_id, msg) await gm_command.finish() else: - sql_message.update_ls_all(give_stone_num) + await XiuxianDataManager().update_ls_all(give_stone_num) msg = f"全服通告:赠送所有用户{give_stone_num}灵石,请注意查收!" enabled_groups = JsonConfig().get_enabled_groups() @@ -1206,15 +1024,12 @@ async def gm_command_(bot: Bot, event: GroupMessageEvent, args: Message = Comman async def cz_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """创造力量""" bot, send_group_id = await assign_bot(bot=bot, event=event) + isUser, user_info, msg = await check_user(event) give_qq = None # 艾特的时候存到这里 msg = args.extract_plain_text().split() if not args: - msg = f"请输入正确指令!例如:创造力量 物品 数量" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请输入正确指令!例如:创造力量 物品 数量" + await handle_send(bot, event, send_group_id, msg) await cz.finish() goods_name = msg[0] goods_id = -1 @@ -1235,28 +1050,20 @@ async def cz_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): if arg.type == "at": give_qq = arg.data.get("qq", "") if give_qq: - give_user = sql_message.get_user_info_with_id(give_qq) + give_user = await XiuxianDataManager().get_user_infos_by_ids(give_qq) if give_user: - sql_message.send_back(give_qq, goods_id, goods_name, goods_type, goods_num, 1) + await XiuxianDataManager().send_back(give_qq, int(goods_id), goods_name, goods_type, goods_num, 1) msg = f"{give_user['user_name']}道友获得了系统赠送的{goods_num}个{goods_name}!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await cz.finish() else: - msg = f"对方未踏入修仙界,不可赠送!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "对方未踏入修仙界,不可赠送!" + await handle_send(bot, event, send_group_id, msg) await cz.finish() else: - all_users = sql_message.get_all_user_id() + all_users = await XiuxianDataManager().get_all_user_id() for user_id in all_users: - sql_message.send_back(user_id, goods_id, goods_name, goods_type, goods_num, 1) # 给每个用户发送物品 + await XiuxianDataManager().send_back(user_id, goods_id, goods_name, goods_type, goods_num, 1) # 给每个用户发送物品 msg = f"全服通告:赠送所有用户{goods_num}个{goods_name},请注意查收!" enabled_groups = JsonConfig().get_enabled_groups() for group_id in enabled_groups: @@ -1276,40 +1083,29 @@ async def cz_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): @gmm_command.handle(parameterless=[Cooldown(at_sender=False)]) async def gmm_command_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): bot, send_group_id = await assign_bot(bot=bot, event=event) + isUser, user_info, msg = await check_user(event) give_qq = None # 艾特的时候存到这里 msg = args.extract_plain_text().strip() if not args: - msg = f"请输入正确指令!例如:轮回力量 x(1为混沌,2为融合,3为超,4为龙,5为天,6为千世,7为万世)" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请输入正确指令!例如:轮回力量 x(1为混沌,2为融合,3为超,4为龙,5为天,6为千世,7为万世)" + await handle_send(bot, event, send_group_id, msg) await gmm_command.finish() for arg in args: if arg.type == "at": give_qq = arg.data.get("qq", "") - give_user = sql_message.get_user_info_with_id(give_qq) + give_user = await XiuxianDataManager().get_user_infos_by_ids(give_qq) if give_user: - root_name = sql_message.update_root(give_qq, msg) - sql_message.update_power2(give_qq) + root_name = await XiuxianDataManager().update_root(give_qq, msg) + await XiuxianDataManager().update_power2(give_qq) msg = f"{give_user['user_name']}道友的灵根已变更为{root_name}!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await gmm_command.finish(MessageSegment.image(pic)) + await handle_send(bot, event, send_group_id, msg) + await gmm_command.finish() else: - msg = f"对方未踏入修仙界,不可修改!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await gmm_command.finish(MessageSegment.image(pic)) + msg = "对方未踏入修仙界,不可修改!" + await handle_send(bot, event, send_group_id, msg) + await gmm_command.finish() @rob_stone.handle(parameterless=[Cooldown(stamina_cost = 15, at_sender=False)]) @@ -1322,50 +1118,61 @@ async def rob_stone_(bot: Bot, event: GroupMessageEvent, args: Message = Command "COMBO": COMBO }""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await rob_stone.finish() user_id = user_info["user_id"] - user_mes = sql_message.get_user_info_with_id(user_id) + user_mes = await XiuxianDataManager().get_user_infos_by_ids(user_id) give_qq = None # 艾特的时候存到这里 + + # 获取消息文本 + msg_text = args.extract_plain_text().strip() + + # 提取道号:移除所有数字,剩余的文本可能是道号 + remaining_text = re.sub(r"\d+", "", msg_text).strip() + for arg in args: if arg.type == "at": give_qq = arg.data.get("qq", "") + player1 = {"user_id": None, "道号": None, "气血": None, "攻击": None, "真元": None, '会心': None, '爆伤': None, '防御': 0} player2 = {"user_id": None, "道号": None, "气血": None, "攻击": None, "真元": None, '会心': None, '爆伤': None, '防御': 0} - user_2 = sql_message.get_user_info_with_id(give_qq) + + # 获取目标用户信息 + user_2 = None + if give_qq: + user_2 = await XiuxianDataManager().get_user_infos_by_ids(give_qq) + # 如果没有艾特,尝试使用道号搜索 + elif remaining_text: + user_2_info = await XiuxianDataManager().get_user_info_with_name(remaining_text) + if user_2_info: + user_2 = user_2_info + give_qq = user_2['user_id'] + if user_mes and user_2: if user_info['root'] == "器师": - msg = f"目前职业无法抢劫!" - sql_message.update_user_stamina(user_id, 15, 1) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "目前职业无法抢劫!" + await XiuxianDataManager().update_user_stamina(user_id, 15, 1) + await handle_send(bot, event, send_group_id, msg) await rob_stone.finish() if give_qq: if str(give_qq) == str(user_id): - msg = f"请不要抢自己刷成就!" - sql_message.update_user_stamina(user_id, 15, 1) + msg = "请不要抢自己刷成就!" + await XiuxianDataManager().update_user_stamina(user_id, 15, 1) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await rob_stone.finish() if user_2['root'] == "器师": - msg = f"对方职业无法被抢劫!" - sql_message.update_user_stamina(user_id, 15, 1) + msg = "对方职业无法被抢劫!" + await XiuxianDataManager().update_user_stamina(user_id, 15, 1) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -1374,95 +1181,95 @@ async def rob_stone_(bot: Bot, event: GroupMessageEvent, args: Message = Command if user_2: if user_info['hp'] is None: # 判断用户气血是否为None - sql_message.update_user_hp(user_id) - user_info = sql_message.get_user_info_with_id(user_id) + await XiuxianDataManager().update_user_hp(user_id) + user_info = await XiuxianDataManager().get_user_infos_by_ids(user_id) if user_2['hp'] is None: - sql_message.update_user_hp(give_qq) - user_2 = sql_message.get_user_info_with_id(give_qq) + await XiuxianDataManager().update_user_hp(give_qq) + user_2 = await XiuxianDataManager().get_user_infos_by_ids(give_qq) if user_2['hp'] <= user_2['exp'] / 10: - time_2 = leave_harm_time(give_qq) + time_2 = await leave_harm_time(give_qq) msg = f"对方重伤藏匿了,无法抢劫!距离对方脱离生命危险还需要{time_2}分钟!" - sql_message.update_user_stamina(user_id, 15, 1) + await XiuxianDataManager().update_user_stamina(user_id, 15, 1) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await rob_stone.finish() if user_info['hp'] <= user_info['exp'] / 10: - time_msg = leave_harm_time(user_id) + time_msg = await leave_harm_time(user_id) msg = f"重伤未愈,动弹不得!距离脱离生命危险还需要{time_msg}分钟!" - msg += f"请道友进行闭关,或者使用药品恢复气血,不要干等,没有自动回血!!!" - sql_message.update_user_stamina(user_id, 15, 1) + msg += "请道友进行闭关,或者使用药品恢复气血,不要干等,没有自动回血!!!" + await XiuxianDataManager().update_user_stamina(user_id, 15, 1) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await rob_stone.finish() - impart_data_1 = xiuxian_impart.get_user_impart_info_with_id(user_id) + impart_data_1 = await XiuxianDataManager().get_user_impart_info_with_id(user_id) player1['user_id'] = user_info['user_id'] player1['道号'] = user_info['user_name'] player1['气血'] = user_info['hp'] player1['攻击'] = user_info['atk'] player1['真元'] = user_info['mp'] player1['会心'] = int( - (0.01 + impart_data_1['impart_know_per'] if impart_data_1 is not None else 0) * 100) + (0.01 + float(impart_data_1['impart_crit_addition']) if impart_data_1 is not None else 0) * 100) player1['爆伤'] = int( - 1.5 + impart_data_1['impart_burst_per'] if impart_data_1 is not None else 0) - user_buff_data = UserBuffDate(user_id) - user_armor_data = user_buff_data.get_user_armor_buff_data() + 1.5 + float(impart_data_1['impart_crit_dmg_addition']) if impart_data_1 is not None else 0) + user_buff_data = UserBuffData(user_id) + user_armor_data = await user_buff_data.get_user_armor_buff_data() if user_armor_data is not None: - def_buff = int(user_armor_data['def_buff']) + def_buff = int(user_armor_data['def_buf']) else: def_buff = 0 player1['防御'] = def_buff - impart_data_2 = xiuxian_impart.get_user_impart_info_with_id(user_2['user_id']) + impart_data_2 = await XiuxianDataManager().get_user_impart_info_with_id(user_2['user_id']) player2['user_id'] = user_2['user_id'] player2['道号'] = user_2['user_name'] player2['气血'] = user_2['hp'] player2['攻击'] = user_2['atk'] player2['真元'] = user_2['mp'] player2['会心'] = int( - (0.01 + impart_data_2['impart_know_per'] if impart_data_2 is not None else 0) * 100) + (0.01 + float(impart_data_2['impart_crit_addition']) if impart_data_2 is not None else 0) * 100) player2['爆伤'] = int( - 1.5 + impart_data_2['impart_burst_per'] if impart_data_2 is not None else 0) - user_buff_data = UserBuffDate(user_2['user_id']) - user_armor_data = user_buff_data.get_user_armor_buff_data() + 1.5 + float(impart_data_2['impart_crit_dmg_addition']) if impart_data_2 is not None else 0) + user_buff_data = UserBuffData(user_2['user_id']) + user_armor_data = await user_buff_data.get_user_armor_buff_data() if user_armor_data is not None: - def_buff = int(user_armor_data['def_buff']) + def_buff = int(user_armor_data['def_buf']) else: def_buff = 0 player2['防御'] = def_buff - result, victor = OtherSet().player_fight(player1, player2) + result, victor = await OtherSet().player_fight(player1, player2) await send_msg_handler(bot, event, '决斗场', bot.self_id, result) if victor == player1['道号']: foe_stone = user_2['stone'] if foe_stone > 0: - sql_message.update_ls(user_id, int(foe_stone * 0.1), 1) - sql_message.update_ls(give_qq, int(foe_stone * 0.1), 2) - exps = int(user_2['exp'] * 0.005) - sql_message.update_exp(user_id, exps) - sql_message.update_j_exp(give_qq, exps / 2) + await XiuxianDataManager().update_ls(user_id, int(float(foe_stone) * 0.1), 0) + await XiuxianDataManager().update_ls(give_qq, int(float(foe_stone) * 0.1), 1) + exps = int(float(user_2['exp']) * 0.005) + await XiuxianDataManager().update_exp(user_id, exps, 0) + await XiuxianDataManager().update_exp(give_qq, exps / 2, 1) msg = f"大战一番,战胜对手,获取灵石{number_to(foe_stone * 0.1)}枚,修为增加{number_to(exps)},对手修为减少{number_to(exps / 2)}" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await rob_stone.finish() else: - exps = int(user_2['exp'] * 0.005) - sql_message.update_exp(user_id, exps) - sql_message.update_j_exp(give_qq, exps / 2) + exps = int(float(user_2['exp']) * 0.005) + await XiuxianDataManager().update_exp(user_id, exps, 0) + await XiuxianDataManager().update_exp(give_qq, exps / 2, 1) msg = f"大战一番,战胜对手,结果对方是个穷光蛋,修为增加{number_to(exps)},对手修为减少{number_to(exps / 2)}" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -1471,46 +1278,42 @@ async def rob_stone_(bot: Bot, event: GroupMessageEvent, args: Message = Command elif victor == player2['道号']: mind_stone = user_info['stone'] if mind_stone > 0: - sql_message.update_ls(user_id, int(mind_stone * 0.1), 2) - sql_message.update_ls(give_qq, int(mind_stone * 0.1), 1) - exps = int(user_info['exp'] * 0.005) - sql_message.update_j_exp(user_id, exps) - sql_message.update_exp(give_qq, exps / 2) - msg = f"大战一番,被对手反杀,损失灵石{number_to(mind_stone * 0.1)}枚,修为减少{number_to(exps)},对手获取灵石{number_to(mind_stone * 0.1)}枚,修为增加{number_to(exps / 2)}" + await XiuxianDataManager().update_ls(user_id, int(float(mind_stone) * 0.1), 1) + await XiuxianDataManager().update_ls(give_qq, int(float(mind_stone) * 0.1), 0) + exps = int(float(user_info['exp']) * 0.005) + await XiuxianDataManager().update_exp(user_id, exps, 1) + await XiuxianDataManager().update_exp(give_qq, exps / 2, 0) + msg = f"大战一番,被对手反杀,损失灵石{number_to(float(mind_stone) * 0.1)}枚,修为减少{number_to(exps)},对手获取灵石{number_to(float(mind_stone) * 0.1)}枚,修为增加{number_to(exps / 2)}" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await rob_stone.finish() else: - exps = int(user_info['exp'] * 0.005) - sql_message.update_j_exp(user_id, exps) - sql_message.update_exp(give_qq, exps / 2) + exps = int(float(user_info['exp']) * 0.005) + await XiuxianDataManager().update_exp(user_id, exps, 1) + await XiuxianDataManager().update_exp(give_qq, exps / 2, 0) msg = f"大战一番,被对手反杀,修为减少{number_to(exps)},对手修为增加{number_to(exps / 2)}" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await rob_stone.finish() else: - msg = f"发生错误,请检查后台!" + msg = "发生错误,请检查后台!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await rob_stone.finish() else: - msg = f"对方未踏入修仙界,不可抢劫!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "对方未踏入修仙界,不可抢劫!" + await handle_send(bot, event, send_group_id, msg) await rob_stone.finish() @@ -1520,35 +1323,23 @@ async def restate_(bot: Bot, event: GroupMessageEvent, args: Message = CommandAr 单用户:重置状态@xxx 多用户:重置状态""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await restate.finish() give_qq = None # 艾特的时候存到这里 for arg in args: if arg.type == "at": give_qq = arg.data.get("qq", "") if give_qq: - sql_message.restate(give_qq) + await XiuxianDataManager().restate(give_qq) msg = f"{give_qq}用户信息重置成功!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await restate.finish() else: - sql_message.restate() - msg = f"所有用户信息重置成功!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await XiuxianDataManager().restate() + msg = "所有用户信息重置成功!" + await handle_send(bot, event, send_group_id, msg) await restate.finish() @@ -1559,49 +1350,30 @@ async def open_xiuxian_(bot: Bot, event: GroupMessageEvent): group_msg = str(event.message) group_id = str(event.group_id) conf_data = JsonConfig().read_data() + isUser, user_info, msg = await check_user(event) if "启用" in group_msg: if group_id in conf_data["group"]: msg = "当前群聊修仙模组已启用,请勿重复操作!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await set_xiuxian.finish() JsonConfig().write_data(1, group_id) msg = "当前群聊修仙基础模组已启用,快发送 我要修仙 加入修仙世界吧!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await set_xiuxian.finish() elif "禁用" in group_msg: if group_id not in conf_data["group"]: msg = "当前群聊修仙模组已禁用,请勿重复操作!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await set_xiuxian.finish() JsonConfig().write_data(2, group_id) msg = "当前群聊修仙基础模组已禁用!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await set_xiuxian.finish() else: msg = "指令错误,请输入:启用修仙功能/禁用修仙功能" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await set_xiuxian.finish() @@ -1609,13 +1381,9 @@ async def open_xiuxian_(bot: Bot, event: GroupMessageEvent): async def xiuxian_updata_level_(bot: Bot, event: GroupMessageEvent): """将修仙1的境界适配到修仙2""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await xiuxian_updata_level.finish() level_dict={ "练气境":"搬血境", @@ -1639,13 +1407,9 @@ async def xiuxian_updata_level_(bot: Bot, event: GroupMessageEvent): else: try: level = level_dict.get(level[:3]) + level[-2:] - except: + except ValueError: level = level - sql_message.updata_level(user_id=user_id,level_name=level) + await XiuxianDataManager().updata_level(user_id=user_id,level_name=level) msg = '境界适配成功成功!' - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await xiuxian_updata_level.finish() \ No newline at end of file diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_beg/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_beg/__init__.py index bdba04ba..9a9ed1a8 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_beg/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_beg/__init__.py @@ -1,150 +1,130 @@ -import random -from datetime import datetime -from ..xiuxian_utils.lay_out import assign_bot, Cooldown -from nonebot import require, on_command -from nonebot.adapters.onebot.v11 import ( - Bot, - GROUP, - GroupMessageEvent, - MessageSegment -) -from nonebot.log import logger -from ..xiuxian_utils.xiuxian2_handle import XiuxianDateManage -from ..xiuxian_config import XiuConfig -from ..xiuxian_utils.item_json import Items -from ..xiuxian_utils.data_source import jsondata -from ..xiuxian_utils.utils import ( - check_user,Txt2Img, - get_msg_pic, - CommandObjectID, -) - -items = Items() -cache_level_help = {} -scheduler = require("nonebot_plugin_apscheduler").scheduler -cache_beg_help = {} -sql_message = XiuxianDateManage() # sql类 - -# 重置奇缘 -@scheduler.scheduled_job("cron", hour=0, minute=0) -async def xiuxian_beg_(): - sql_message.beg_remake() - logger.opt(colors=True).info(f"仙途奇缘重置成功!") - -__beg_help__ = f""" -详情: -为了让初入仙途的道友们更顺利地踏上修炼之路,特别开辟了额外的机缘 -天降灵石,助君一臂之力。 -若有心人借此谋取不正之利,必将遭遇天道轮回,异象降临,后果自负。 -诸位道友,若不信此言,可自行一试,便知天机不可泄露,天道不容欺。 -""".strip() - -beg_stone = on_command("仙途奇缘", permission=GROUP, priority=7, block=True) -beg_help = on_command("仙途奇缘帮助", permission=GROUP, priority=7, block=True) - -@beg_help.handle(parameterless=[Cooldown(at_sender=False)]) -async def beg_help_(bot: Bot, event: GroupMessageEvent, session_id: int = CommandObjectID()): - bot, send_group_id = await assign_bot(bot=bot, event=event) - if session_id in cache_beg_help: - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(cache_beg_help[session_id])) - await beg_help.finish() - else: - msg = __beg_help__ - if XiuConfig().img: - pic = await get_msg_pic(msg) - cache_beg_help[session_id] = pic - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await beg_help.finish() - -@beg_stone.handle(parameterless=[Cooldown(at_sender=False)]) -async def beg_stone(bot: Bot, event: GroupMessageEvent): - bot, send_group_id = await assign_bot(bot=bot, event=event) - user_id = event.get_user_id() - isUser, user_info, _ = check_user(event) - user_msg = sql_message.get_user_info_with_id(user_id) - user_root = user_msg['root_type'] - sect = user_info['sect_id'] - level = user_info['level'] - list_level_all = list(jsondata.level_data().keys()) - - create_time = datetime.strptime(user_info['create_time'], "%Y-%m-%d %H:%M:%S.%f") - now_time = datetime.now() - diff_time = now_time - create_time - diff_days = diff_time.days # 距离创建账号时间的天数 - - if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await beg_stone.finish() - - sql_message.update_last_check_info_time(user_id) # 更新查看修仙信息时间 - if sect != None and user_root == "伪灵根": - if XiuConfig().img: - msg = f"道友已有宗门庇佑,又何必来此寻求机缘呢?" - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=event.group_id, message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=event.group_id, message=msg) - - elif user_root in {"轮回道果", "真·轮回道果"}: - if XiuConfig().img: - msg = f"道友已是轮回大能,又何必来此寻求机缘呢?" - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=event.group_id, message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=event.group_id, message=msg) - - elif list_level_all.index(level) >= list_level_all.index(XiuConfig().beg_max_level): - msg = f"道友已跻身于{user_info['level']}层次的修行之人,可徜徉于四海八荒,自寻机缘与造化矣。" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=event.group_id, message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=event.group_id, message=msg) - - elif diff_days > XiuConfig().beg_max_days: - if XiuConfig().img: - msg = f"道友已经过了新手期,不能再来此寻求机缘了。" - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=event.group_id, message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=event.group_id, message=msg) - - else: - stone = sql_message.get_beg(user_id) - if stone is None: - msg = '贪心的人是不会有好运的!' - else: - msg = random.choice( - [ - f"在一次深入古老森林的修炼旅程中,你意外地遇到了一位神秘的前辈高人。这位前辈不仅给予了你宝贵的修炼指导,还在临别时赠予了你 {stone} 枚灵石,以表达对你的认可和鼓励。", - f"某日,在一个清澈的小溪边,一只珍稀的灵兽突然出现在你面前。它似乎对你的气息感到亲切,竟然留下了 {stone} 枚灵石,好像是在对你展示它的友好和感激。", - f"在一次勇敢的探险中,你发现了一片被遗忘的灵石矿脉。通过采矿获得了 {stone} 枚灵石,这不仅是一次意外的惊喜,也是对你勇气和坚持的奖赏。", - f"在一个宁静的夜晚,你抬头夜观星象,突然一颗流星划破夜空,落在你的附近。你跟随流星落下的轨迹找到了 {stone} 枚灵石,就像是来自天际的礼物。", - f"在一次偶然的机会下,你在一座古老的山洞深处发现了一块充满灵气的巨大灵石,将它收入囊中并获得了 {stone} 枚灵石。这块灵石似乎蕴含着古老的力量,让你的修为有了不小的提升。", - f"在一次探索未知禁地时,你解开了一个古老的阵法,这个阵法守护着数世纪的秘密。当最后一个符文点亮时,阵法缓缓散开,露出了其中藏有的 {stone} 枚灵石。", - f"在一次河床淘金的经历中,你意外发现了一些隐藏在水流淤泥中的 {stone} 枚灵石。这些灵石对于修炼者来说极为珍贵,而你却在这样一个不经意的时刻发现了它们。这次发现让你更加相信,修炼之路上的每一次机缘都是命运的安排,值得你去珍惜和感激", - f"在一次偶然的机会下,你在一座古墓的深处发现了一个隐藏的宝藏,其中藏有 {stone} 枚灵石。这些灵石可能是古时某位大能为后人留下的财富,而你,正是那位幸运的发现者。这次发现不仅大大增加了你的修为,也让你对探索古墓和古老传说充满了无尽的好奇和兴趣。", - f"参加门派举办的比武大会,你凭借着出色的实力和智慧,一路过关斩将,但在最终对决中惜败萧炎。虽败犹荣,作为奖励,门派赠予了你 {stone} 枚灵石,这不仅是对你实力的认可,也是对你未来修炼的支持。", - f"在一次对古老遗迹的探索中,你解开了一道埋藏已久的谜题。随着最后一个谜题的解开,一个密室缓缓打开,里面藏有的 {stone} 枚灵石作为奖励呈现在你面前。这些灵石对你来说,不仅是物质上的奖励,更是对你智慧和毅力的肯定。", - f"修炼时,你意外地遇到了一次天降祥瑞的奇观,一朵灵花从天而降,化作了 {stone} 枚灵石落入你的背包中。这次祥瑞不仅让你的修为有了不小的提升,也让你深感天地之大,自己仍需不断努力,探索修炼的更高境界。", - f"在一次门派分配的任务中,你表现出色,解决了一个困扰门派多时的难题。作为对你贡献的认可,门派特别奖励了你 {stone} 枚灵石。", - f"一位神秘旅行者传授给你一张古老的地图,据说地图上标记的宝藏正是数量可观的灵石。经过一番冒险和探索,你终于找到了宝藏所在,获得了 {stone} 枚灵石!", - f"在你帮助一位受伤的异兽后,作为感谢,它送给了你 {stone} 枚灵石。随后踏云而去,修炼之路上的每一个生命都值得尊重和帮助,而善行和仁心,往往能收获意想不到的回报。", - f"在一次与妖兽的激战中胜出后,你发现了妖兽巢穴中藏有的 {stone} 枚灵石。这些灵石对你的修炼大有裨益,也让你对面对挑战时的勇气和决心有了更深的理解。", - f"你在一次随机的交易中获得了一个外表不起眼的神秘盒子。当你好奇心驱使下打开它时,发现里面竟是一枚装满灵石的纳戒,收获了 {stone} 枚灵石!", - ] -) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=event.group_id, message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=event.group_id, message=msg) - - - +import random +from datetime import datetime +from ..xiuxian_utils.lay_out import assign_bot, Cooldown +from nonebot import require, on_command +from nonebot.adapters.onebot.v11 import ( + Bot, + GROUP, + GroupMessageEvent, + MessageSegment +) +from nonebot.log import logger +from ..xiuxian_utils.xiuxian2_handle import XiuxianDataManager +from ..xiuxian_config import XiuConfig +from ..xiuxian_utils.item_json import Items +from ..xiuxian_utils.data_source import jsondata +from ..xiuxian_utils.utils import ( + check_user, + get_msg_pic, + CommandObjectID, + handle_send +) + +items = Items() +cache_level_help = {} +scheduler = require("nonebot_plugin_apscheduler").scheduler +cache_beg_help = {} + # sql类 + +# 重置奇缘 +@scheduler.scheduled_job("cron", hour=0, minute=0) +async def xiuxian_beg_(): + await XiuxianDataManager().beg_remake() + logger.opt(colors=True).info("仙途奇缘重置成功!") + +__beg_help__ = """ +详情: +为了让初入仙途的道友们更顺利地踏上修炼之路,特别开辟了额外的机缘 +天降灵石,助君一臂之力。 +若有心人借此谋取不正之利,必将遭遇天道轮回,异象降临,后果自负。 +诸位道友,若不信此言,可自行一试,便知天机不可泄露,天道不容欺。 +""".strip() + +beg_stone = on_command("仙途奇缘", permission=GROUP, priority=7, block=True) +beg_help = on_command("仙途奇缘帮助", permission=GROUP, priority=7, block=True) + +@beg_help.handle(parameterless=[Cooldown(at_sender=False)]) +async def beg_help_(bot: Bot, event: GroupMessageEvent, session_id: int = CommandObjectID()): + bot, send_group_id = await assign_bot(bot=bot, event=event) + if session_id in cache_beg_help: + await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(cache_beg_help[session_id])) + await beg_help.finish() + else: + msg = __beg_help__ + if XiuConfig().img: + pic = await get_msg_pic(msg) + cache_beg_help[session_id] = pic + await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) + else: + await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await beg_help.finish() + +@beg_stone.handle(parameterless=[Cooldown(at_sender=False)]) +async def beg_stone_(bot: Bot, event: GroupMessageEvent): + bot, send_group_id = await assign_bot(bot=bot, event=event) + user_id = int(event.get_user_id()) + isUser, user_info, msg = await check_user(event) + user_msg = await XiuxianDataManager().get_user_infos_by_ids(user_id) + user_root = user_msg['root_type'] + sect = user_info['sect_id'] + level = user_info['level'] + list_level_all = list(jsondata.level_data().keys()) + + create_time = user_info['user_create_time'] + now_time = datetime.now() + diff_time = now_time - create_time + diff_days = diff_time.days # 距离创建账号时间的天数 + + if not isUser: + await handle_send(bot, event, send_group_id, msg) + await beg_stone.finish() + + await XiuxianDataManager().update_last_check_info_time(user_id) # 更新查看修仙信息时间 + if sect is not None and user_root == "伪灵根": + msg = "道友已有宗门庇佑,又何必来此寻求机缘呢?" + await handle_send(bot, event, send_group_id, msg) + await beg_stone.finish() + + elif user_root in {"轮回道果", "真·轮回道果"}: + msg = "道友已是轮回大能,又何必来此寻求机缘呢?" + await handle_send(bot, event, send_group_id, msg) + await beg_stone.finish() + + elif list_level_all.index(level) >= list_level_all.index(XiuConfig().beg_max_level): + msg = f"道友已跻身于{user_info['level']}层次的修行之人,可徜徉于四海八荒,自寻机缘与造化矣。" + await handle_send(bot, event, send_group_id, msg) + await beg_stone.finish() + + elif diff_days > XiuConfig().beg_max_days: + msg = "道友已经过了新手期,不能再来此寻求机缘了。" + await handle_send(bot, event, send_group_id, msg) + await beg_stone.finish() + + else: + stone = await XiuxianDataManager().get_beg(user_id) + if stone is None: + msg = '贪心的人是不会有好运的!' + else: + msg = random.choice( + [ + f"在一次深入古老森林的修炼旅程中,你意外地遇到了一位神秘的前辈高人。这位前辈不仅给予了你宝贵的修炼指导,还在临别时赠予了你 {stone} 枚灵石,以表达对你的认可和鼓励。", + f"某日,在一个清澈的小溪边,一只珍稀的灵兽突然出现在你面前。它似乎对你的气息感到亲切,竟然留下了 {stone} 枚灵石,好像是在对你展示它的友好和感激。", + f"在一次勇敢的探险中,你发现了一片被遗忘的灵石矿脉。通过采矿获得了 {stone} 枚灵石,这不仅是一次意外的惊喜,也是对你勇气和坚持的奖赏。", + f"在一个宁静的夜晚,你抬头夜观星象,突然一颗流星划破夜空,落在你的附近。你跟随流星落下的轨迹找到了 {stone} 枚灵石,就像是来自天际的礼物。", + f"在一次偶然的机会下,你在一座古老的山洞深处发现了一块充满灵气的巨大灵石,将它收入囊中并获得了 {stone} 枚灵石。这块灵石似乎蕴含着古老的力量,让你的修为有了不小的提升。", + f"在一次探索未知禁地时,你解开了一个古老的阵法,这个阵法守护着数世纪的秘密。当最后一个符文点亮时,阵法缓缓散开,露出了其中藏有的 {stone} 枚灵石。", + f"在一次河床淘金的经历中,你意外发现了一些隐藏在水流淤泥中的 {stone} 枚灵石。这些灵石对于修炼者来说极为珍贵,而你却在这样一个不经意的时刻发现了它们。这次发现让你更加相信,修炼之路上的每一次机缘都是命运的安排,值得你去珍惜和感激", + f"在一次偶然的机会下,你在一座古墓的深处发现了一个隐藏的宝藏,其中藏有 {stone} 枚灵石。这些灵石可能是古时某位大能为后人留下的财富,而你,正是那位幸运的发现者。这次发现不仅大大增加了你的修为,也让你对探索古墓和古老传说充满了无尽的好奇和兴趣。", + f"参加门派举办的比武大会,你凭借着出色的实力和智慧,一路过关斩将,但在最终对决中惜败萧炎。虽败犹荣,作为奖励,门派赠予了你 {stone} 枚灵石,这不仅是对你实力的认可,也是对你未来修炼的支持。", + f"在一次对古老遗迹的探索中,你解开了一道埋藏已久的谜题。随着最后一个谜题的解开,一个密室缓缓打开,里面藏有的 {stone} 枚灵石作为奖励呈现在你面前。这些灵石对你来说,不仅是物质上的奖励,更是对你智慧和毅力的肯定。", + f"修炼时,你意外地遇到了一次天降祥瑞的奇观,一朵灵花从天而降,化作了 {stone} 枚灵石落入你的背包中。这次祥瑞不仅让你的修为有了不小的提升,也让你深感天地之大,自己仍需不断努力,探索修炼的更高境界。", + f"在一次门派分配的任务中,你表现出色,解决了一个困扰门派多时的难题。作为对你贡献的认可,门派特别奖励了你 {stone} 枚灵石。", + f"一位神秘旅行者传授给你一张古老的地图,据说地图上标记的宝藏正是数量可观的灵石。经过一番冒险和探索,你终于找到了宝藏所在,获得了 {stone} 枚灵石!", + f"在你帮助一位受伤的异兽后,作为感谢,它送给了你 {stone} 枚灵石。随后踏云而去,修炼之路上的每一个生命都值得尊重和帮助,而善行和仁心,往往能收获意想不到的回报。", + f"在一次与妖兽的激战中胜出后,你发现了妖兽巢穴中藏有的 {stone} 枚灵石。这些灵石对你的修炼大有裨益,也让你对面对挑战时的勇气和决心有了更深的理解。", + f"你在一次随机的交易中获得了一个外表不起眼的神秘盒子。当你好奇心驱使下打开它时,发现里面竟是一枚装满灵石的纳戒,收获了 {stone} 枚灵石!", + ] +) + await handle_send(bot, event, send_group_id, msg) + await beg_stone.finish() + diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_boss/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_boss/__init__.py index 0d2884d7..e2c78885 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_boss/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_boss/__init__.py @@ -19,13 +19,18 @@ ActionFailed, MessageSegment ) +from nonebot_plugin_apscheduler import scheduler from ..xiuxian_utils.lay_out import assign_bot, put_bot, layout_bot_dict, Cooldown from nonebot.permission import SUPERUSER from nonebot.log import logger from ..xiuxian_utils.xiuxian2_handle import ( - XiuxianDateManage ,OtherSet, UserBuffDate, - XIUXIAN_IMPART_BUFF, leave_harm_time + XiuxianDataManager ,OtherSet, UserBuffData, leave_harm_time +) +from ..xiuxian_utils.utils import ( + check_user, get_msg_pic, CommandObjectID, + send_msg_handler, handle_send ) +from .. import DRIVER from ..xiuxian_config import convert_rank, XiuConfig, JsonConfig from .makeboss import createboss, createboss_jj from .bossconfig import get_boss_config, savef_boss @@ -33,15 +38,10 @@ from ..xiuxian_utils.player_fight import Boss_fight from ..xiuxian_utils.item_json import Items items = Items() -from ..xiuxian_utils.utils import ( - number_to, check_user, - get_msg_pic, CommandObjectID, - pic_msg_format, send_msg_handler -) -from .. import DRIVER + # boss定时任务 require('nonebot_plugin_apscheduler') -from nonebot_plugin_apscheduler import scheduler + conf_data = JsonConfig().read_data() config = get_boss_config() @@ -51,8 +51,6 @@ group_boss = {} groups = config['open'] battle_flag = {} -sql_message = XiuxianDateManage() # sql类 -xiuxian_impart = XIUXIAN_IMPART_BUFF() def check_rule_bot_boss() -> Rule: # 消息检测,是超管,群主或者指定的qq号传入的消息就响应,其他的不响应 @@ -82,7 +80,7 @@ async def _check_bot_(bot: Bot, event: GroupMessageEvent) -> bool: rule=check_rule_bot_boss_s(), block=True) create_appoint = on_command("生成指定世界boss", aliases={"生成指定世界boss", "生成指定世界BOSS", "生成指定BOSS", "生成指定boss"}, priority=5, rule=check_rule_bot_boss_s()) -boss_info = on_command("查询世界boss", aliases={"查询世界Boss", "查询世界BOSS", "查询boss", "世界Boss查询", "世界BOSS查询", "boss查询"}, priority=6, permission=GROUP, block=True) +boss_info = on_command("查询世界boss", aliases={"查询世界Boss", "查询世界BOSS", "查看世界boss", "查看boss", "查看世界BOSS", "世界Boss查询", "世界BOSS查询", "boss查询"}, priority=6, permission=GROUP, block=True) set_group_boss = on_command("世界boss", aliases={"世界Boss", "世界BOSS"}, priority=13, permission=GROUP and (SUPERUSER | GROUP_ADMIN | GROUP_OWNER), block=True) battle = on_command("讨伐boss", aliases={"讨伐世界boss", "讨伐Boss", "讨伐BOSS", "讨伐世界Boss", "讨伐世界BOSS"}, priority=6, @@ -97,7 +95,7 @@ async def _check_bot_(bot: Bot, event: GroupMessageEvent) -> bool: boss_integral_use = on_command("世界积分兑换", priority=6, permission=GROUP, block=True) boss_time = config["Boss生成时间参数"] -__boss_help__ = f""" +__boss_help__ = """ 世界Boss帮助信息: 指令: 1、生成世界boss:生成一只随机大境界的世界Boss,超管权限 @@ -117,7 +115,7 @@ async def _check_bot_(bot: Bot, event: GroupMessageEvent) -> bool: async def read_boss_(): global group_boss group_boss.update(old_boss_info.read_boss_info()) - logger.opt(colors=True).info(f"历史boss数据读取成功") + logger.opt(colors=True).info("历史boss数据读取成功") @DRIVER.on_startup @@ -141,7 +139,7 @@ async def set_boss_(): async def send_bot(group_id:str): #初始化 - if not group_id in group_boss: + if group_id not in group_boss: group_boss[group_id] = [] if group_id not in groups: @@ -157,18 +155,18 @@ async def send_bot(group_id:str): api = 'send_group_msg' #要调用的函数 data = {'group_id': int(group_id)} #要发送的群 - bossinfo = createboss() + bossinfo = await createboss() group_boss[group_id].append(bossinfo) msg = f"野生的{bossinfo['jj']}Boss:{bossinfo['name']}出现了,诸位道友请击败Boss获得奖励吧!" if XiuConfig().img: - pic = await get_msg_pic(f"@全体修仙者\n" + msg) + pic = await get_msg_pic("@全体修仙者\n" + msg) data['message'] = MessageSegment.image(pic) else: data['message'] = MessageSegment.text(msg) try: bot_id = layout_bot_dict[group_id] if group_id in layout_bot_dict else put_bot[0] - except: + except ValueError: bot = get_bot() bot_id = bot.self_id @@ -180,7 +178,7 @@ async def send_bot(group_id:str): else: await get_bots()[put_bot[0]].call_api(api, **data) - except: + except ValueError: if group_id not in bot.get_group_list(): logger.opt(colors=True).warning(f"群{group_id}不存在,请检查配置文件!") return @@ -194,7 +192,7 @@ async def send_bot(group_id:str): async def save_boss_(): global group_boss old_boss_info.save_boss(group_boss) - logger.opt(colors=True).info(f"boss数据已保存") + logger.opt(colors=True).info("boss数据已保存") @boss_help.handle(parameterless=[Cooldown(at_sender=False)]) @@ -226,63 +224,39 @@ async def boss_delete_(bot: Bot, event: GroupMessageEvent, args: Message = Comma boss_num = re.findall(r"\d+", msg) # boss编号 isInGroup = isInGroups(event) if not isInGroup: # 不在配置表内 - msg = f"本群尚未开启世界Boss,请联系管理员开启!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "本群尚未开启世界Boss,请联系管理员开启!" + await handle_send(bot, event, send_group_id, msg) await boss_delete.finish() if boss_num: boss_num = int(boss_num[0]) else: - msg = f"请输入正确的世界Boss编号!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请输入正确的世界Boss编号!" + await handle_send(bot, event, send_group_id, msg) await boss_delete.finish() bosss = None try: bosss = group_boss[group_id] - except: - msg = f"本群尚未生成世界Boss,请等待世界boss刷新!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + except ValueError: + msg = "本群尚未生成世界Boss,请等待世界boss刷新!" + await handle_send(bot, event, send_group_id, msg) await boss_delete.finish() if not bosss: - msg = f"本群尚未生成世界Boss,请等待世界boss刷新!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "本群尚未生成世界Boss,请等待世界boss刷新!" + await handle_send(bot, event, send_group_id, msg) await boss_delete.finish() index = len(group_boss[group_id]) if not (0 < boss_num <= index): - msg = f"请输入正确的世界Boss编号!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请输入正确的世界Boss编号!" + await handle_send(bot, event, send_group_id, msg) await boss_delete.finish() group_boss[group_id].remove(group_boss[group_id][boss_num - 1]) - msg = f"该世界Boss被突然从天而降的神雷劈中,烟消云散了" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "该世界Boss被突然从天而降的神雷劈中,烟消云散了" + await handle_send(bot, event, send_group_id, msg) await boss_delete.finish() @@ -294,41 +268,25 @@ async def boss_delete_all_(bot: Bot, event: GroupMessageEvent, args: Message = C group_id = str(event.group_id) isInGroup = isInGroups(event) if not isInGroup: # 不在配置表内 - msg = f"本群尚未开启世界Boss,请联系管理员开启!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "本群尚未开启世界Boss,请联系管理员开启!" + await handle_send(bot, event, send_group_id, msg) await boss_delete_all.finish() bosss = None try: bosss = group_boss[group_id] - except: - msg = f"本群尚未生成世界Boss,请等待世界boss刷新!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + except ValueError: + msg = "本群尚未生成世界Boss,请等待世界boss刷新!" + await handle_send(bot, event, send_group_id, msg) await boss_delete_all.finish() if not bosss: - msg = f"本群尚未生成世界Boss,请等待世界boss刷新!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "本群尚未生成世界Boss,请等待世界boss刷新!" + await handle_send(bot, event, send_group_id, msg) await boss_delete_all.finish() group_boss[group_id] = [] - msg = f"所有的世界Boss都烟消云散了~~" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "所有的世界Boss都烟消云散了~~" + await handle_send(bot, event, send_group_id, msg) await boss_delete_all.finish() @@ -336,124 +294,96 @@ async def boss_delete_all_(bot: Bot, event: GroupMessageEvent, args: Message = C async def battle_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """讨伐世界boss""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await battle.finish() user_id = user_info['user_id'] - sql_message.update_last_check_info_time(user_id) # 更新查看修仙信息时间 + await XiuxianDataManager().update_last_check_info_time(user_id) # 更新查看修仙信息时间 msg = args.extract_plain_text().strip() group_id = str(event.group_id) boss_num = re.findall(r"\d+", msg) # boss编号 isInGroup = isInGroups(event) if not isInGroup: # 不在配置表内 - msg = f"本群尚未开启世界Boss,请联系管理员开启!" - sql_message.update_user_stamina(user_id, 20, 1) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "本群尚未开启世界Boss,请联系管理员开启!" + await XiuxianDataManager().update_user_stamina(user_id, 20, 1) + await handle_send(bot, event, send_group_id, msg) await battle.finish() if boss_num: boss_num = int(boss_num[0]) else: - msg = f"请输入正确的世界Boss编号!" - sql_message.update_user_stamina(user_id, 20, 1) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请输入正确的世界Boss编号!" + await XiuxianDataManager().update_user_stamina(user_id, 20, 1) + await handle_send(bot, event, send_group_id, msg) await battle.finish() bosss = None try: bosss = group_boss[group_id] - except: - msg = f"本群尚未生成世界Boss,请等待世界boss刷新!" - sql_message.update_user_stamina(user_id, 20, 1) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + except ValueError: + msg = "本群尚未生成世界Boss,请等待世界boss刷新!" + await XiuxianDataManager().update_user_stamina(user_id, 20, 1) + await handle_send(bot, event, send_group_id, msg) await battle.finish() if not bosss: - msg = f"本群尚未生成世界Boss,请等待世界boss刷新!" - sql_message.update_user_stamina(user_id, 20, 1) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "本群尚未生成世界Boss,请等待世界boss刷新!" + await XiuxianDataManager().update_user_stamina(user_id, 20, 1) + await handle_send(bot, event, send_group_id, msg) await battle.finish() index = len(group_boss[group_id]) if not (0 < boss_num <= index): - msg = f"请输入正确的世界Boss编号!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请输入正确的世界Boss编号!" + await handle_send(bot, event, send_group_id, msg) await battle.finish() if user_info['hp'] is None or user_info['hp'] == 0: # 判断用户气血是否为空 - sql_message.update_user_hp(user_id) + await XiuxianDataManager().update_user_hp(user_id) if user_info['hp'] <= user_info['exp'] / 10: - time = leave_harm_time(user_id) + time = await leave_harm_time(user_id) msg = f"重伤未愈,动弹不得!距离脱离危险还需要{time}分钟!\n" - msg += f"请道友进行闭关,或者使用药品恢复气血,不要干等,没有自动回血!!!" - sql_message.update_user_stamina(user_id, 20, 1) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg += "请道友进行闭关,或者使用药品恢复气血,不要干等,没有自动回血!!!" + await XiuxianDataManager().update_user_stamina(user_id, 20, 1) + await handle_send(bot, event, send_group_id, msg) await battle.finish() player = {"user_id": None, "道号": None, "气血": None, "攻击": None, "真元": None, '会心': None, '防御': 0} - userinfo = sql_message.get_user_real_info(user_id) - user_weapon_data = UserBuffDate(userinfo['user_id']).get_user_weapon_data() - - impart_data = xiuxian_impart.get_user_impart_info_with_id(user_id) - boss_atk = impart_data['boss_atk'] if impart_data['boss_atk'] is not None else 0 - user_armor_data = UserBuffDate(userinfo['user_id']).get_user_armor_buff_data() #boss战防具会心 - user_main_data = UserBuffDate(userinfo['user_id']).get_user_main_buff_data() #boss战功法会心 - user1_sub_buff_data = UserBuffDate(userinfo['user_id']).get_user_sub_buff_data() #boss战辅修功法信息 - integral_buff = user1_sub_buff_data['integral'] if user1_sub_buff_data is not None else 0 #boss战积分加成 + userinfo = await XiuxianDataManager().get_user_real_info(user_id) + user_weapon_data = await UserBuffData(userinfo['user_id']).get_user_weapon_data() + + impart_data = await XiuxianDataManager().get_user_impart_info_with_id(user_id) + impart_boss_atk_addition = impart_data['impart_boss_atk_addition'] if impart_data['impart_boss_atk_addition'] is not None else 0 + user_armor_data = await UserBuffData(userinfo['user_id']).get_user_armor_buff_data() #boss战防具会心 + user_main_data = await UserBuffData(userinfo['user_id']).get_user_main_buff_data() #boss战功法会心 + user1_sub_buff_data = await UserBuffData(userinfo['user_id']).get_user_sub_buff_data() #boss战辅修功法信息 + # integral_buff = user1_sub_buff_data['integral'] if user1_sub_buff_data is not None else 0 #boss战积分加成 exp_buff = user1_sub_buff_data['exp'] if user1_sub_buff_data is not None else 0 - if user_main_data != None: #boss战功法会心 - main_crit_buff = user_main_data['crit_buff'] + if user_main_data is not None: #boss战功法会心 + main_crit_buff = user_main_data['crit_buf'] else: main_crit_buff = 0 - if user_armor_data != None: #boss战防具会心 - armor_crit_buff = user_armor_data['crit_buff'] + if user_armor_data is not None: #boss战防具会心 + armor_crit_buff = user_armor_data['crit_buf'] else: armor_crit_buff = 0 - if user_weapon_data != None: #boss战武器会心 - player['会心'] = int(((user_weapon_data['crit_buff']) + (armor_crit_buff) + (main_crit_buff)) * 100) + if user_weapon_data is not None: #boss战武器会心 + player['会心'] = int(((user_weapon_data['crit_buf']) + (armor_crit_buff) + (main_crit_buff)) * 100) else: player['会心'] = (armor_crit_buff + main_crit_buff) * 100 player['user_id'] = userinfo['user_id'] player['道号'] = userinfo['user_name'] player['气血'] = userinfo['hp'] - player['攻击'] = int(userinfo['atk'] * (1 + boss_atk)) + player['攻击'] = int(userinfo['atk'] * (1 + impart_boss_atk_addition)) player['真元'] = userinfo['mp'] player['exp'] = userinfo['exp'] @@ -465,11 +395,7 @@ async def battle_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg user_rank = convert_rank(userinfo['level'])[0] if boss_rank - user_rank >= 12: msg = f"道友已是{userinfo['level']}之人,妄图抢小辈的Boss,可耻!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await battle.finish() boss_old_hp = bossinfo['气血'] # 打之前的血量 more_msg = '' @@ -477,21 +403,21 @@ async def battle_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg result, victor, bossinfo_new, get_stone = await Boss_fight(player, bossinfo, bot_id=bot.self_id) if victor == "Boss赢了": group_boss[group_id][boss_num - 1] = bossinfo_new - sql_message.update_ls(user_id, get_stone, 1) + await XiuxianDataManager().update_ls(user_id, get_stone, 0) # 新增boss战斗积分点数 boss_now_hp = bossinfo_new['气血'] # 打之后的血量 boss_all_hp = bossinfo['总血量'] # 总血量 boss_integral = int(((boss_old_hp - boss_now_hp) / boss_all_hp) * 240) - if boss_integral < 5: # 摸一下不给 + if boss_integral < 2: # 摸一下不给 boss_integral = 0 if user_info['root'] == "器师": boss_integral = int(boss_integral * (1 + (user_rank - boss_rank))) - points_bonus = int(80 * (user_rank - boss_rank)) + points_bonus = int(160 * (user_rank - boss_rank)) more_msg = f"道友低boss境界{user_rank - boss_rank}层,获得{points_bonus}%积分加成!" user_boss_fight_info = get_user_boss_fight_info(user_id) user_boss_fight_info['boss_integral'] += boss_integral - top_user_info = sql_message.get_top1_user() + top_user_info = await XiuxianDataManager().get_top1_user() top_user_exp = top_user_info['exp'] save_user_boss_fight_info(user_id, user_boss_fight_info) @@ -499,78 +425,70 @@ async def battle_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg now_exp = int(((top_user_exp * 0.1) / user_info['exp']) / (exp_buff * (1 / (convert_rank(user_info['level'])[0] + 1)))) if now_exp > 1000000: now_exp = int(1000000 / random.randint(5, 10)) - sql_message.update_exp(user_id, now_exp) + await XiuxianDataManager().update_exp(user_id, now_exp, 0) exp_msg = f",获得修为{int(now_exp)}点!" else: - exp_msg = f" " + exp_msg = " " msg = f"道友不敌{bossinfo['name']},重伤逃遁,临逃前收获灵石{get_stone}枚,{more_msg}获得世界积分:{boss_integral}点{exp_msg} " if user_info['root'] == "器师" and boss_integral < 0: - msg += f"\n如果出现负积分,说明你境界太高了,玩器师就不要那么高境界了!!!" + msg += "\n如果出现负积分,说明你境界太高了,玩器师就不要那么高境界了!!!" battle_flag[group_id] = False try: await send_msg_handler(bot, event, result) except ActionFailed: - msg += f"Boss战消息发送错误,可能被风控!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg += "Boss战消息发送错误,可能被风控!" + await handle_send(bot, event, send_group_id, msg) await battle.finish() elif victor == "群友赢了": # 新增boss战斗积分点数 boss_all_hp = bossinfo['总血量'] # 总血量 - boss_integral = 240 + boss_integral = 1000 if user_info['root'] == "器师": boss_integral = int(boss_integral * (1 + (user_rank - boss_rank))) - points_bonus = int(80 * (user_rank - boss_rank)) + points_bonus = int(320 * (user_rank - boss_rank)) more_msg = f"道友低boss境界{user_rank - boss_rank}层,获得{points_bonus}%积分加成!" else: - if boss_rank - user_rank >= 9: # 超过太多不给 + if boss_rank - user_rank >= 3: # 超过太多不给 boss_integral = 0 - more_msg = f"道友的境界超过boss太多了,不齿!" + more_msg = "道友的境界超过boss太多了,不齿!" - top_user_info = sql_message.get_top1_user() + top_user_info = await XiuxianDataManager().get_top1_user() top_user_exp = top_user_info['exp'] if exp_buff > 0 and user_info['root'] != "器师": - now_exp = int(((top_user_exp * 0.1) / user_info['exp']) / (exp_buff * (1 / (convert_rank(user_info['level'])[0] + 1)))) + now_exp = int(((float(top_user_exp) * 0.1) / float(user_info['exp'])) / (exp_buff * (1 / (convert_rank(user_info['level'])[0] + 1)))) if now_exp > 1000000: now_exp = int(1000000 / random.randint(5, 10)) - sql_message.update_exp(user_id, now_exp) + await XiuxianDataManager().update_exp(user_id, now_exp, 0) exp_msg = f",获得修为{int(now_exp)}点!" else: - exp_msg = f" " + exp_msg = " " drops_id, drops_info = boss_drops(user_rank, boss_rank, bossinfo, userinfo) - if drops_id == None: + if drops_id is None: drops_msg = " " elif boss_rank < convert_rank('遁一境中期')[0]: drops_msg = f"boss的尸体上好像有什么东西, 凑近一看居然是{drops_info['name']}! " - sql_message.send_back(user_info['user_id'], drops_info['id'],drops_info['name'], drops_info['type'], 1) + await XiuxianDataManager().send_back(user_info['user_id'], drops_info['id'],drops_info['name'], drops_info['type'], 1) else : drops_msg = " " group_boss[group_id].remove(group_boss[group_id][boss_num - 1]) battle_flag[group_id] = False - sql_message.update_ls(user_id, get_stone, 1) + await XiuxianDataManager().update_ls(user_id, get_stone, 0) user_boss_fight_info = get_user_boss_fight_info(user_id) user_boss_fight_info['boss_integral'] += boss_integral save_user_boss_fight_info(user_id, user_boss_fight_info) msg = f"恭喜道友击败{bossinfo['name']},收获灵石{get_stone}枚,{more_msg}获得世界积分:{boss_integral}点!{exp_msg} {drops_msg}" if user_info['root'] == "器师" and boss_integral < 0: - msg += f"\n如果出现负积分,说明你这器师境界太高了(如果总世界积分为负数,会帮你重置成0),玩器师就不要那么高境界了!!!" + msg += "\n如果出现负积分,说明你这器师境界太高了(如果总世界积分为负数,会帮你重置成0)\n玩器师就不要那么高境界了!!!" try: await send_msg_handler(bot, event, result) except ActionFailed: - msg += f"Boss战消息发送错,可能被风控!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg += "Boss战消息发送错,可能被风控!" + await handle_send(bot, event, send_group_id, msg) await battle.finish() @@ -581,35 +499,23 @@ async def boss_info_(bot: Bot, event: GroupMessageEvent, args: Message = Command group_id = str(event.group_id) isInGroup = isInGroups(event) if not isInGroup: # 不在配置表内 - msg = f"本群尚未开启世界Boss,请联系管理员开启!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "本群尚未开启世界Boss,请联系管理员开启!" + await handle_send(bot, event, send_group_id, msg) await boss_info.finish() bosss = None try: bosss = group_boss[group_id] - except: - msg = f"本群尚未生成世界Boss,请等待世界boss刷新!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + except ValueError: + msg = "本群尚未生成世界Boss,请等待世界boss刷新!" + await handle_send(bot, event, send_group_id, msg) await boss_info.finish() msg = args.extract_plain_text().strip() boss_num = re.findall(r"\d+", msg) # boss编号 if not bosss: - msg = f"本群尚未生成世界Boss,请等待世界boss刷新!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "本群尚未生成世界Boss,请等待世界boss刷新!" + await handle_send(bot, event, send_group_id, msg) await boss_info.finish() Flag = False # True查对应Boss @@ -617,12 +523,8 @@ async def boss_info_(bot: Bot, event: GroupMessageEvent, args: Message = Command boss_num = int(boss_num[0]) index = len(group_boss[group_id]) if not (0 < boss_num <= index): - msg = f"请输入正确的世界Boss编号!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请输入正确的世界Boss编号!" + await handle_send(bot, event, send_group_id, msg) await boss_info.finish() Flag = True @@ -630,7 +532,7 @@ async def boss_info_(bot: Bot, event: GroupMessageEvent, args: Message = Command bossmsgs = "" if Flag: # 查单个Boss信息 boss = group_boss[group_id][boss_num - 1] - bossmsgs = f''' + bossmsgs = ''' 世界Boss:{boss['name']} 境界:{boss['jj']} 总血量:{number_to(boss['总血量'])} @@ -643,11 +545,7 @@ async def boss_info_(bot: Bot, event: GroupMessageEvent, args: Message = Command boss_name = boss["name"] + "_c" else: boss_name = boss["name"] - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg, boss_name=boss_name) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg, boss_name = boss_name) await boss_info.finish() else: i = 1 @@ -655,11 +553,7 @@ async def boss_info_(bot: Bot, event: GroupMessageEvent, args: Message = Command bossmsgs += f"编号{i}、{boss['jj']}Boss:{boss['name']} \n" i += 1 msg = bossmsgs - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await boss_info.finish() @@ -670,35 +564,23 @@ async def create_(bot: Bot, event: GroupMessageEvent): group_id = str(event.group_id) isInGroup = isInGroups(event) if not isInGroup: # 不在配置表内 - msg = f"本群尚未开启世界Boss,请联系管理员开启!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "本群尚未开启世界Boss,请联系管理员开启!" + await handle_send(bot, event, send_group_id, msg) await create.finish() - bossinfo = createboss() + bossinfo = await createboss() try: group_boss[group_id] - except: + except ValueError: group_boss[group_id] = [] if len(group_boss[group_id]) >= config['Boss个数上限']: msg = f"本群世界Boss已达到上限{config['Boss个数上限']}个,无法继续生成" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await create.finish() group_boss[group_id].append(bossinfo) msg = f"已生成{bossinfo['jj']}Boss:{bossinfo['name']},诸位道友请击败Boss获得奖励吧!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await create.finish() @create_appoint.handle() @@ -708,34 +590,21 @@ async def _(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): group_id = str(event.group_id) isInGroup = isInGroups(event) if not isInGroup:#不在配置表内 - msg = f"本群尚未开启世界Boss,请联系管理员开启!" - if XiuConfig().img: - msg = await pic_msg_format(msg, event) - pic = await get_msg_pic(msg) - await create_appoint.finish(MessageSegment.image(pic)) - else: - await create_appoint.finish(msg, at_sender=False) + msg = "本群尚未开启世界Boss,请联系管理员开启!" + await handle_send(bot, event, send_group_id, msg) + await create_appoint.finish() try: group_boss[group_id] - except: + except ValueError: group_boss[group_id] = [] if len(group_boss[group_id]) >= config['Boss个数上限']: msg = f"本群世界Boss已达到上限{config['Boss个数上限']}个,无法继续生成" - if XiuConfig().img: - msg = await pic_msg_format(msg, event) - pic = await get_msg_pic(msg) - await create_appoint.finish(MessageSegment.image(pic)) - else: - await create_appoint.finish(msg, at_sender=False) + await handle_send(bot, event, send_group_id, msg) arg_list = args.extract_plain_text().split() if len(arg_list) < 1: - msg = f"请输入正确的指令,例如:生成指定世界boss 祭道境 少姜" - if XiuConfig().img: - msg = await pic_msg_format(msg, event) - pic = await get_msg_pic(msg) - await create_appoint.finish(MessageSegment.image(pic)) - else: - await create_appoint.finish(msg, at_sender=False) + msg = "请输入正确的指令,例如:生成指定世界boss 祭道境 少姜" + await handle_send(bot, event, send_group_id, msg) + await create_appoint.finish() boss_jj = arg_list[0] # 用户指定的境界 boss_name = arg_list[1] if len(arg_list) > 1 else None # 用户指定的Boss名称,如果有的话 @@ -743,21 +612,12 @@ async def _(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): # 使用提供的境界和名称生成boss信息 bossinfo = createboss_jj(boss_jj, boss_name) if bossinfo is None: - msg = f"请输入正确的境界,例如:生成指定世界boss 祭道境" - if XiuConfig().img: - msg = await pic_msg_format(msg, event) - pic = await get_msg_pic(msg) - await create_appoint.finish(MessageSegment.image(pic)) - else: - await create_appoint.finish(msg, at_sender=False) + msg = "请输入正确的境界,例如:生成指定世界boss 祭道境" + await handle_send(bot, event, send_group_id, msg) group_boss[group_id].append(bossinfo) msg = f"已生成{bossinfo['jj']}Boss:{bossinfo['name']},诸位道友请击败Boss获得奖励吧!" - if XiuConfig().img: - msg = await pic_msg_format(msg, event) - pic = await get_msg_pic(msg) - await create_appoint.finish(MessageSegment.image(pic)) - else: - await create_appoint.finish(msg, at_sender=False) + await handle_send(bot, event, send_group_id, msg) + await create_appoint.finish() @set_group_boss.handle(parameterless=[Cooldown(at_sender=False)]) @@ -770,12 +630,8 @@ async def set_group_boss_(bot: Bot, event: GroupMessageEvent, args: Message = Co if mode == '开启': if isInGroup: - msg = f"本群已开启世界Boss,请勿重复开启!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "本群已开启世界Boss,请勿重复开启!" + await handle_send(bot, event, send_group_id, msg) await set_group_boss.finish() else: info = { @@ -786,35 +642,23 @@ async def set_group_boss_(bot: Bot, event: GroupMessageEvent, args: Message = Co } config['open'].update(info) savef_boss(config) - msg = f"已开启本群世界Boss!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "已开启本群世界Boss!" + await handle_send(bot, event, send_group_id, msg) await set_group_boss.finish() elif mode == '关闭': if isInGroup: try: del config['open'][str(group_id)] - except: + except ValueError: pass savef_boss(config) - msg = f"已关闭本群世界Boss!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "已关闭本群世界Boss!" + await handle_send(bot, event, send_group_id, msg) await set_group_boss.finish() else: - msg = f"本群未开启世界Boss!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "本群未开启世界Boss!" + await handle_send(bot, event, send_group_id, msg) await set_group_boss.finish() elif mode == '': @@ -822,19 +666,11 @@ async def set_group_boss_(bot: Bot, event: GroupMessageEvent, args: Message = Co msg = __boss_help__ + f"非指令:1、拥有定时任务:每{groups[str(send_group_id)]['hours']}小时{groups[str(send_group_id)]['minutes']}分钟生成一只随机大境界的世界Boss" else: msg = __boss_help__ - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await set_group_boss.finish() else: - msg = f"请输入正确的指令:世界boss开启或关闭!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请输入正确的指令:世界boss开启或关闭!" + await handle_send(bot, event, send_group_id, msg) await set_group_boss.finish() @@ -842,24 +678,16 @@ async def set_group_boss_(bot: Bot, event: GroupMessageEvent, args: Message = Co async def boss_integral_info_(bot: Bot, event: GroupMessageEvent): """世界积分商店""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await boss_integral_info.finish() user_id = user_info['user_id'] isInGroup = isInGroups(event) if not isInGroup: # 不在配置表内 - msg = f"本群尚未开启世界Boss,请联系管理员开启!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "本群尚未开启世界Boss,请联系管理员开启!" + await handle_send(bot, event, send_group_id, msg) await boss_integral_info.finish() user_boss_fight_info = get_user_boss_fight_info(user_id) @@ -872,7 +700,7 @@ async def boss_integral_info_(bot: Bot, event: GroupMessageEvent): msg += f"所需世界积分:{v['cost']}点" l_msg.append(msg) else: - l_msg.append(f"世界积分商店内空空如也!") + l_msg.append("世界积分商店内空空如也!") await send_msg_handler(bot, event, '世界积分商店', bot.self_id, l_msg) await boss_integral_info.finish() @@ -881,13 +709,9 @@ async def boss_integral_info_(bot: Bot, event: GroupMessageEvent): async def boss_integral_use_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """世界积分商店兑换""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await boss_integral_use.finish() user_id = user_info['user_id'] @@ -896,24 +720,16 @@ async def boss_integral_use_(bot: Bot, event: GroupMessageEvent, args: Message = isInGroup = isInGroups(event) if not isInGroup: - msg = f"本群尚未开启世界Boss,请联系管理员开启!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "本群尚未开启世界Boss,请联系管理员开启!" + await handle_send(bot, event, send_group_id, msg) await boss_integral_use.finish() if shop_info: shop_id = int(shop_info[0][0]) quantity = int(shop_info[0][1]) if shop_info[0][1] else 1 else: - msg = f"请输入正确的商品编号!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请输入正确的商品编号!" + await handle_send(bot, event, send_group_id, msg) await boss_integral_use.finish() boss_integral_shop = config['世界积分商品'] @@ -928,43 +744,27 @@ async def boss_integral_use_(bot: Bot, event: GroupMessageEvent, args: Message = item_id = v['id'] break else: - msg = f"世界积分商店内空空如也!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "世界积分商店内空空如也!" + await handle_send(bot, event, send_group_id, msg) await boss_integral_use.finish() if is_in: user_boss_fight_info = get_user_boss_fight_info(user_id) total_cost = cost * quantity if user_boss_fight_info['boss_integral'] < total_cost: - msg = f"道友的世界积分不满足兑换条件呢" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友的世界积分不满足兑换条件呢" + await handle_send(bot, event, send_group_id, msg) await boss_integral_use.finish() else: user_boss_fight_info['boss_integral'] -= total_cost save_user_boss_fight_info(user_id, user_boss_fight_info) item_info = Items().get_data_by_item_id(item_id) - sql_message.send_back(user_id, item_id, item_info['name'], item_info['type'], quantity) # 兑换指定数量 + await XiuxianDataManager().send_back(user_id, item_id, item_info['name'], item_info['type'], quantity) # 兑换指定数量 msg = f"道友成功兑换获得:{item_info['name']}{quantity}个" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await boss_integral_use.finish() else: - msg = f"该编号不在商品列表内哦,请检查后再兑换" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "该编号不在商品列表内哦,请检查后再兑换" + await handle_send(bot, event, send_group_id, msg) await boss_integral_use.finish() @@ -978,7 +778,7 @@ def isInGroups(event: GroupMessageEvent): def get_user_boss_fight_info(user_id): try: user_boss_fight_info = read_user_boss_fight_info(user_id) - except: + except ValueError: save_user_boss_fight_info(user_id, user_boss_fight_info) return user_boss_fight_info @@ -1024,7 +824,7 @@ def get_dict_type_rate(data_dict): for i, v in data_dict.items(): try: temp_dict[i] = v["type_rate"] - except: + except ValueError: continue key = OtherSet().calculated(temp_dict) return key diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_boss/bossconfig.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_boss/bossconfig.py index 4f43d402..eb6141df 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_boss/bossconfig.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_boss/bossconfig.py @@ -57,93 +57,93 @@ "Boss倍率": { # Boss属性:大境界平均修为是基础数值,气血:15倍,真元:10倍,攻击力:0.2倍 # 作为参考:人物的属性,修为是基础数值,气血:0.5倍,真元:1倍,攻击力:0.1倍 - "气血": 329, - "真元": 20, - "攻击": 8 + "气血": 500, + "真元": 10, + "攻击": 4 }, "Boss生成时间参数": { # Boss生成的时间,2个不可全为0 "hours": 0, - "minutes": 45 + "minutes": 20 }, "世界积分商品": { "1": { "id": 1999, - "cost": 10000, + "cost": 100, "desc": "渡厄丹,使下一次突破丢失的修为减少为0!" }, "2": { "id": 4003, - "cost": 5000, + "cost": 500, "desc": "陨铁炉,以陨铁炼制的丹炉,耐高温,具有基础的炼丹功能" }, "3": { "id": 4002, - "cost": 25000, + "cost": 2500, "desc": "雕花紫铜炉,表面刻有精美雕花的紫铜丹炉,一看便出自大师之手,可以使产出的丹药增加1枚" }, "4": { "id": 4001, - "cost": 100000, + "cost": 10000, "desc": "寒铁铸心炉,由万年寒铁打造的顶尖丹炉,可以使产出的丹药增加2枚" }, "5": { "id": 2500, - "cost": 5000, + "cost": 50, "desc": "一级聚灵旗,提升洞天福地中的灵气汇集速度,加速修炼速度和灵田中药材生长速度" }, "6": { "id": 2501, - "cost": 10000, + "cost": 100, "desc": "二级聚灵旗,提升洞天福地中的灵气汇集速度,加速修炼速度和灵田中药材生长速度" }, "7": { "id": 2502, - "cost": 20000, + "cost": 200, "desc": "三级聚灵旗,提升洞天福地中的灵气汇集速度,加速修炼速度和灵田中药材生长速度" }, "8": { "id": 2503, - "cost": 40000, + "cost": 400, "desc": "四级聚灵旗,提升洞天福地中的灵气汇集速度,加速修炼速度和灵田中药材生长速度" }, "9": { "id": 2504, - "cost": 80000, + "cost": 800, "desc": "仙级聚灵旗,大幅提升洞天福地中的灵气汇集速度,加速修炼速度和灵田中药材生长速度" }, "10": { "id": 2505, - "cost": 160000, + "cost": 1600, "desc": "无上聚灵旗,极大提升洞天福地中的灵气汇集速度,加速修炼速度和灵田中药材生长速度" }, "11": { "id": 7085, - "cost": 2000000, + "cost": 2000, "desc": "冲天槊,无上仙器,不属于这个位面的武器,似乎还有种种能力未被发掘...提升100%攻击力!提升50%会心率!提升20%减伤率!提升50%会心伤害!" }, "12": { "id": 8931, - "cost": 2000000, + "cost": 2000, "desc": "苍寰变,无上神通,不属于这个位面的神通,连续攻击两次,造成6.5倍!7倍伤害!消耗气血0%、真元70%,发动概率100%,发动后休息一回合 " }, "13": { "id": 9937, - "cost": 2000000, + "cost": 2000, "desc": "一气化三清,无上仙法,比上面几个还厉害,可惜太长写不下 " }, "14": { "id": 10402, - "cost": 700000, + "cost": 7000, "desc": "真神威录,天阶下品辅修功法,增加70%会心率!" }, "15": { "id": 10403, - "cost": 1000000, + "cost": 10000, "desc": "太乙剑诀,天阶下品辅修功法,增加100%会心伤害!" }, "16": { "id": 10411, - "cost": 1200000, + "cost": 12000, "desc": "真龙九变,天阶上品辅修功法,增加攻击力60%!" } } @@ -157,7 +157,7 @@ def get_boss_config(): if key not in list(config.keys()): config[key] = CONFIG[key] savef_boss(config) - except: + except FileNotFoundError: config = CONFIG savef_boss(config) return config diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_boss/makeboss.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_boss/makeboss.py index 0c8d0d27..efacd05e 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_boss/makeboss.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_boss/makeboss.py @@ -1,34 +1,34 @@ import random from pathlib import Path -from ..xiuxian_utils.xiuxian2_handle import XiuxianDateManage +from ..xiuxian_utils.xiuxian2_handle import XiuxianDataManager from .bossconfig import get_boss_config import json config = get_boss_config() JINGJIEEXP = { # 数值为中期和圆满的平均值 - "搬血境": [1000, 2000, 3000], - "洞天境": [6000, 8000.10000], - "化灵境": [30000, 60000, 90000], - "铭纹境": [144000, 160000, 176000], - "列阵境": [352000, 284000, 416000], - "尊者境": [832000, 896000, 960000], - "神火境": [1920000, 2048000, 2176000], - "真一境": [4352000, 4608000, 4864000], - "圣祭境": [9728000, 12348000, 14968000], - "天神境": [30968000, 35968000, 40968000], - "虚道境": [60968000, 70968000, 80968000], - "斩我境": [120968000, 140968000, 160968000], - "遁一境": [321936000, 450710400, 579484800], - "至尊境": [1158969600, 1622557440, 2086145280], - "真仙境": [4172290560, 5841206784, 7510123008], - "仙王境": [15020246016, 21028344422, 27036442828], - "准帝境": [54072885657, 75702039920, 97331194180], - "仙帝境": [194662388360, 272527343704, 350392299048], - "祭道境": [1550392299048, 1850392299048, 2150392299048] + "搬血境": [100, 200, 300], + "洞天境": [600, 800, 1000], + "化灵境": [3000, 6000, 9000], + "铭纹境": [14400, 16000, 17600], + "列阵境": [35200, 28400, 41600], + "尊者境": [83200, 89600, 96000], + "神火境": [192000, 204800, 217600], + "真一境": [435200, 460800, 486400], + "圣祭境": [972800, 1234800, 1496800], + "天神境": [3096800, 3596800, 4096800], + "虚道境": [6096800, 7096800, 8096800], + "斩我境": [12096800, 14096800, 16096800], + "遁一境": [32193600, 45071040, 57948480], + "至尊境": [115896960, 162255744, 208614528], + "真仙境": [417229056, 584120678, 751012300], + "仙王境": [1502024601, 2102834442, 2703644282], + "准帝境": [5407288565, 7570203992, 9733119418], + "仙帝境": [19466238836, 27252734370, 35039229904], + "祭道境": [155039229904, 185039229904, 215039229904] } jinjie_list = [k for k, v in JINGJIEEXP.items()] -sql_message = XiuxianDateManage() # sql类 + # sql类 def get_boss_jinjie_dict(): CONFIGJSONPATH = Path() / "data" / "xiuxian" / "境界.json" @@ -55,8 +55,8 @@ def get_boss_exp(boss_jj): return None -def createboss(): - top_user_info = sql_message.get_realm_top1_user() # 改成了境界第一 +async def createboss(): + top_user_info = await XiuxianDataManager().get_realm_top1_user() # 改成了境界第一 top_user_level = top_user_info['level'] if len(top_user_level) == 5: level = top_user_level[:3] diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_boss/old_boss_info.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_boss/old_boss_info.py index 3837aec3..c6664697 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_boss/old_boss_info.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_boss/old_boss_info.py @@ -13,7 +13,7 @@ def __init__(self): try: with open(self.data_path, 'r', encoding='utf-8') as f: self.data = json.load(f) - except: + except FileNotFoundError: self.info = {} data = json.dumps(self.info, ensure_ascii=False, indent=4) with open(self.data_path, mode="x", encoding="UTF-8") as f: diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_buff/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_buff/__init__.py index 0cd779e6..4c449c6e 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_buff/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_buff/__init__.py @@ -11,10 +11,9 @@ from datetime import datetime from nonebot import on_command, on_fullmatch, require from ..xiuxian_utils.xiuxian2_handle import ( - XiuxianDateManage, OtherSet, get_player_info, - save_player_info,UserBuffDate, get_main_info_msg, - get_user_buff, get_sec_msg, get_sub_info_msg, - XIUXIAN_IMPART_BUFF + XiuxianDataManager, OtherSet, get_player_info, + save_player_info,UserBuffData, get_main_info_msg, + get_user_buff, get_sec_msg, get_sub_info_msg ) from ..xiuxian_config import XiuConfig from ..xiuxian_utils.data_source import jsondata @@ -22,15 +21,14 @@ from ..xiuxian_utils.player_fight import Player_fight from ..xiuxian_utils.utils import ( number_to, check_user, send_msg_handler, - check_user_type, get_msg_pic, CommandObjectID + check_user_type, get_msg_pic, CommandObjectID, + handle_send ) from ..xiuxian_utils.lay_out import assign_bot, Cooldown from .two_exp_cd import two_exp_cd cache_help = {} -sql_message = XiuxianDateManage() # sql类 -xiuxian_impart = XIUXIAN_IMPART_BUFF() BLESSEDSPOTCOST = 3500000 # 洞天福地购买消耗 two_exp_limit = 3 # 默认双修次数上限,修仙之人一天3次也不奇怪( @@ -51,7 +49,7 @@ del_exp_decimal = on_fullmatch("抑制黑暗动乱", priority=9, permission=GROUP, block=True) my_exp_num = on_fullmatch("我的双修次数", priority=9, permission=GROUP, block=True) -__buff_help__ = f""" +__buff_help__ = """ 功法帮助信息: 指令: 1、我的功法:查看自身功法信息 @@ -69,7 +67,7 @@ @two_exp_cd_up.scheduled_job("cron", hour=0, minute=0) async def two_exp_cd_up_(): two_exp_cd.re_data() - logger.opt(colors=True).info(f"双修次数已更新!") + logger.opt(colors=True).info("双修次数已更新!") @buff_help.handle(parameterless=[Cooldown(at_sender=False)]) @@ -94,45 +92,29 @@ async def buff_help_(bot: Bot, event: GroupMessageEvent, session_id: int = Comma async def blessed_spot_creat_(bot: Bot, event: GroupMessageEvent): """洞天福地购买""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await blessed_spot_creat.finish() user_id = user_info['user_id'] if int(user_info['blessed_spot_flag']) != 0: - msg = f"道友已经拥有洞天福地了,请发送洞天福地查看吧~" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友已经拥有洞天福地了,请发送洞天福地查看吧~" + await handle_send(bot, event, send_group_id, msg) await blessed_spot_creat.finish() if user_info['stone'] < BLESSEDSPOTCOST: msg = f"道友的灵石不足{BLESSEDSPOTCOST}枚,无法购买洞天福地" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await blessed_spot_creat.finish() else: - sql_message.update_ls(user_id, BLESSEDSPOTCOST, 2) - sql_message.update_user_blessed_spot_flag(user_id) + await XiuxianDataManager().update_ls(user_id, BLESSEDSPOTCOST, 1) + await XiuxianDataManager().update_user_blessed_spot_flag(user_id) mix_elixir_info = get_player_info(user_id, "mix_elixir_info") mix_elixir_info['收取时间'] = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) save_player_info(user_id, mix_elixir_info, 'mix_elixir_info') - msg = f"恭喜道友拥有了自己的洞天福地,请收集聚灵旗来提升洞天福地的等级吧~\n" + msg = "恭喜道友拥有了自己的洞天福地,请收集聚灵旗来提升洞天福地的等级吧~\n" msg += f"默认名称为:{user_info['user_name']}道友的家" - sql_message.update_user_blessed_spot_name(user_id, f"{user_info['user_name']}道友的家") - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await XiuxianDataManager().update_user_blessed_spot_name(user_id, f"{user_info['user_name']}道友的家") + await handle_send(bot, event, send_group_id, msg) await blessed_spot_creat.finish() @@ -140,25 +122,17 @@ async def blessed_spot_creat_(bot: Bot, event: GroupMessageEvent): async def blessed_spot_info_(bot: Bot, event: GroupMessageEvent): """洞天福地信息""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await blessed_spot_info.finish() user_id = user_info['user_id'] if int(user_info['blessed_spot_flag']) == 0: - msg = f"道友还没有洞天福地呢,请发送洞天福地购买来购买吧~" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友还没有洞天福地呢,请发送洞天福地购买来购买吧~" + await handle_send(bot, event, send_group_id, msg) await blessed_spot_info.finish() - msg = f"\n道友的洞天福地:\n" - user_buff_data = UserBuffDate(user_id).BuffInfo + msg = "\n道友的洞天福地:\n" + user_buff_data = await UserBuffData(user_id).BuffInfo if user_info['blessed_spot_name'] == 0: blessed_spot_name = "尚未命名" else: @@ -167,11 +141,7 @@ async def blessed_spot_info_(bot: Bot, event: GroupMessageEvent): msg += f"名字:{blessed_spot_name}\n" msg += f"修炼速度:增加{int(user_buff_data['blessed_spot']) * 100}%\n" msg += f"灵田数量:{mix_elixir_info['灵田数量']}" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await blessed_spot_info.finish() @@ -179,22 +149,14 @@ async def blessed_spot_info_(bot: Bot, event: GroupMessageEvent): async def ling_tian_up_(bot: Bot, event: GroupMessageEvent): """洞天福地灵田升级""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await ling_tian_up.finish() user_id = user_info['user_id'] if int(user_info['blessed_spot_flag']) == 0: - msg = f"道友还没有洞天福地呢,请发送洞天福地购买吧~" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友还没有洞天福地呢,请发送洞天福地购买吧~" + await handle_send(bot, event, send_group_id, msg) await ling_tian_up.finish() LINGTIANCONFIG = { "1": { @@ -216,7 +178,7 @@ async def ling_tian_up_(bot: Bot, event: GroupMessageEvent): mix_elixir_info = get_player_info(user_id, "mix_elixir_info") now_num = mix_elixir_info['灵田数量'] if now_num == len(LINGTIANCONFIG) + 1: - msg = f"道友的灵田已全部开垦完毕,无法继续开垦了!" + msg = "道友的灵田已全部开垦完毕,无法继续开垦了!" else: cost = LINGTIANCONFIG[str(now_num)]['level_up_cost'] if int(user_info['stone']) < cost: @@ -225,12 +187,8 @@ async def ling_tian_up_(bot: Bot, event: GroupMessageEvent): msg = f"道友成功消耗灵石:{cost},灵田数量+1,目前数量:{now_num + 1}" mix_elixir_info['灵田数量'] = now_num + 1 save_player_info(user_id, mix_elixir_info, 'mix_elixir_info') - sql_message.update_ls(user_id, cost, 2) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await XiuxianDataManager().update_ls(user_id, cost, 1) + await handle_send(bot, event, send_group_id, msg) await ling_tian_up.finish() @@ -238,43 +196,27 @@ async def ling_tian_up_(bot: Bot, event: GroupMessageEvent): async def blessed_spot_rename_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """洞天福地改名""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await blessed_spot_rename.finish() user_id = user_info['user_id'] if int(user_info['blessed_spot_flag']) == 0: - msg = f"道友还没有洞天福地呢,请发送洞天福地购买吧~" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友还没有洞天福地呢,请发送洞天福地购买吧~" + await handle_send(bot, event, send_group_id, msg) await blessed_spot_rename.finish() arg = args.extract_plain_text().strip() arg = str(arg) if arg == "": msg = "请输入洞天福地的名字!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await blessed_spot_rename.finish() if len(arg) > 9: - msg = f"洞天福地的名字不可大于9位,请重新命名" + msg = "洞天福地的名字不可大于9位,请重新命名" else: msg = f"道友的洞天福地成功改名为:{arg}" - sql_message.update_user_blessed_spot_name(user_id, arg) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await XiuxianDataManager().update_user_blessed_spot_name(user_id, arg) + await handle_send(bot, event, send_group_id, msg) await blessed_spot_rename.finish() @@ -282,30 +224,35 @@ async def blessed_spot_rename_(bot: Bot, event: GroupMessageEvent, args: Message async def qc_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """切磋,不会掉血""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await qc.finish() user_id = user_info['user_id'] - user1 = sql_message.get_user_real_info(user_id) + user1 = await XiuxianDataManager().get_user_real_info(user_id) give_qq = None # 艾特的时候存到这里 + arg_text = args.extract_plain_text().strip() # 获取纯文本参数 + for arg in args: if arg.type == "at": give_qq = arg.data.get("qq", "") - user2 = sql_message.get_user_real_info(give_qq) + + # 道号 + if not give_qq and arg_text: + other_user_info = await XiuxianDataManager().get_user_info_with_name(arg_text) + if other_user_info: + give_qq = other_user_info['user_id'] + else: + msg = f"修仙界没有找到道号为【{arg_text}】的修士,请检查道号是否正确!" + await handle_send(bot, event, send_group_id, msg) + await qc.finish() + + user2 = await XiuxianDataManager().get_user_real_info(give_qq) if give_qq: if give_qq == str(user_id): msg = "道友不会左右互搏之术!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await qc.finish() if user1 and user2: @@ -315,42 +262,42 @@ async def qc_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): "攻击": None, "真元": None, '会心': None, '防御': 0, 'exp': 0} - user1_weapon_data = UserBuffDate(user_id).get_user_weapon_data() #玩家1武器会心 - user1_armor_crit_buff = UserBuffDate(user_id).get_user_armor_buff_data() #玩家1防具会心 - user1_main_data = UserBuffDate(user_id).get_user_main_buff_data() #玩家1功法会心 + user1_weapon_data = await UserBuffData(user_id).get_user_weapon_data() #玩家1武器会心 + user1_armor_crit_buff = await UserBuffData(user_id).get_user_armor_buff_data() #玩家1防具会心 + user1_main_data = await UserBuffData(user_id).get_user_main_buff_data() #玩家1功法会心 - if user1_main_data != None: #玩家1功法会心 - main_crit_buff = user1_main_data['crit_buff'] + if user1_main_data is not None: #玩家1功法会心 + main_crit_buff = user1_main_data['crit_buf'] else: main_crit_buff = 0 if user1_armor_crit_buff is not None: #玩家1防具会心 - armor_crit_buff = user1_armor_crit_buff['crit_buff'] + armor_crit_buff = user1_armor_crit_buff['crit_buf'] else: armor_crit_buff = 0 if user1_weapon_data is not None: #玩家1武器会心 - player1['会心'] = int(((user1_weapon_data['crit_buff']) + (armor_crit_buff) + (main_crit_buff))* 100) + player1['会心'] = int(((user1_weapon_data['crit_buf']) + (armor_crit_buff) + (main_crit_buff))* 100) else: player1['会心'] = (armor_crit_buff + main_crit_buff) * 100 - user2_weapon_data = UserBuffDate(user2['user_id']).get_user_weapon_data() #玩家2武器会心 - user2_armor_crit_buff = UserBuffDate(user2['user_id']).get_user_armor_buff_data() #玩家2防具会心 - user2_main_data = UserBuffDate(user2['user_id']).get_user_main_buff_data() #玩家2功法会心 + user2_weapon_data = await UserBuffData(user2['user_id']).get_user_weapon_data() #玩家2武器会心 + user2_armor_crit_buff = await UserBuffData(user2['user_id']).get_user_armor_buff_data() #玩家2防具会心 + user2_main_data = await UserBuffData(user2['user_id']).get_user_main_buff_data() #玩家2功法会心 - if user2_main_data != None: #玩家2功法会心 - main_crit_buff2 = user2_main_data['crit_buff'] + if user2_main_data is not None: #玩家2功法会心 + main_crit_buff2 = user2_main_data['crit_buf'] else: main_crit_buff2 = 0 if user2_armor_crit_buff is not None: #玩家2防具会心 - armor_crit_buff2 = user2_armor_crit_buff['crit_buff'] + armor_crit_buff2 = user2_armor_crit_buff['crit_buf'] else: armor_crit_buff2 = 0 if user2_weapon_data is not None: #玩家2武器会心 - player2['会心'] = int(((user2_weapon_data['crit_buff']) + (armor_crit_buff2) + (main_crit_buff2) * 100)) + player2['会心'] = int(((user2_weapon_data['crit_buf']) + (armor_crit_buff2) + (main_crit_buff2) * 100)) else: player2['会心'] = (armor_crit_buff2 + main_crit_buff2) * 100 @@ -368,22 +315,17 @@ async def qc_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): player2['真元'] = user2['mp'] player2['exp'] = user2['exp'] - result, victor = Player_fight(player1, player2, 1, bot.self_id) + result, victor = await Player_fight(player1, player2, 1, bot.self_id) await send_msg_handler(bot, event, result) - msg = f"获胜的是{victor}" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) + if victor == "平局": + msg = "双方平分秋色,不分胜负!" else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = f"获胜的是{victor}" + await handle_send(bot, event, send_group_id, msg) await qc.finish() else: msg = "修仙界没有对方的信息,快邀请对方加入修仙界吧!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await qc.finish() @@ -391,11 +333,12 @@ async def qc_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): async def two_exp_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """双修""" bot, send_group_id = await assign_bot(bot=bot, event=event) + isUser, user_info, msg = await check_user(event) global two_exp_limit - isUser, user_1, msg = check_user(event) + isUser, user_1, msg = await check_user(event) if not isUser: if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -406,25 +349,17 @@ async def two_exp_(bot: Bot, event: GroupMessageEvent, args: Message = CommandAr if arg.type == "at": two_qq = arg.data.get("qq", "") - user_2 = sql_message.get_user_info_with_id(two_qq) + user_2 = await XiuxianDataManager().get_user_infos_by_ids(two_qq) if user_1 and user_2: if two_qq is None: msg = "请at你的道侣,与其一起双修!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await two_exp.finish() if int(user_1['user_id']) == int(two_qq): msg = "道友无法与自己双修!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await two_exp.finish() if user_2: exp_1 = user_1['exp'] @@ -432,7 +367,7 @@ async def two_exp_(bot: Bot, event: GroupMessageEvent, args: Message = CommandAr if exp_2 > exp_1: msg = "修仙大能看了看你,不屑一顾,扬长而去!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -441,21 +376,21 @@ async def two_exp_(bot: Bot, event: GroupMessageEvent, args: Message = CommandAr limt_1 = two_exp_cd.find_user(user_1['user_id']) limt_2 = two_exp_cd.find_user(user_2['user_id']) - sql_message.update_last_check_info_time(user_1['user_id']) # 更新查看修仙信息时间 + await XiuxianDataManager().update_last_check_info_time(user_1['user_id']) # 更新查看修仙信息时间 # 加入传承 - impart_data_1 = xiuxian_impart.get_user_impart_info_with_id(user_1['user_id']) - impart_data_2 = xiuxian_impart.get_user_impart_info_with_id(user_2['user_id']) - impart_two_exp_1 = impart_data_1['impart_two_exp'] if impart_data_1 is not None else 0 - impart_two_exp_2 = impart_data_2['impart_two_exp'] if impart_data_2 is not None else 0 + impart_data_1 = await XiuxianDataManager().get_user_impart_info_with_id(user_1['user_id']) + impart_data_2 = await XiuxianDataManager().get_user_impart_info_with_id(user_2['user_id']) + impart_two_exp_1 = impart_data_1['impart_two_exp_quantity'] if impart_data_1 is not None else 0 + impart_two_exp_2 = impart_data_2['impart_two_exp_quantity'] if impart_data_2 is not None else 0 - main_two_data_1 = UserBuffDate(user_1['user_id']).get_user_main_buff_data()#功法双修次数提升 - main_two_data_2 = UserBuffDate(user_2['user_id']).get_user_main_buff_data() - main_two_1 = main_two_data_1['two_buff'] if main_two_data_1 is not None else 0 - main_two_2 = main_two_data_2['two_buff'] if main_two_data_2 is not None else 0 + main_two_data_1 = UserBuffData(user_1['user_id']).get_user_main_buff_data()#功法双修次数提升 + main_two_data_2 = UserBuffData(user_2['user_id']).get_user_main_buff_data() + main_two_1 = main_two_data_1['two_buf'] if main_two_data_1 is not None else 0 + main_two_2 = main_two_data_2['two_buf'] if main_two_data_2 is not None else 0 if limt_1 >= two_exp_limit + impart_two_exp_1 + main_two_1: msg = "道友今天双修次数已经到达上限!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -463,16 +398,16 @@ async def two_exp_(bot: Bot, event: GroupMessageEvent, args: Message = CommandAr if limt_2 >= two_exp_limit + impart_two_exp_2 + main_two_2: msg = "对方今天双修次数已经到达上限!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await two_exp.finish() max_exp_1 = ( - int(OtherSet().set_closing_type(user_1['level'])) * XiuConfig().closing_exp_upper_limit + int(await OtherSet().set_closing_type(user_1['level'])) * XiuConfig().closing_exp_upper_limit ) # 获取下个境界需要的修为 * 1.5为闭关上限 max_exp_2 = ( - int(OtherSet().set_closing_type(user_2['level'])) * XiuConfig().closing_exp_upper_limit + int(await OtherSet().set_closing_type(user_2['level'])) * XiuConfig().closing_exp_upper_limit ) user_get_exp_max_1 = int(max_exp_1) - user_1['exp'] user_get_exp_max_2 = int(max_exp_2) - user_2['exp'] @@ -486,10 +421,10 @@ async def two_exp_(bot: Bot, event: GroupMessageEvent, args: Message = CommandAr if random.randint(1, 100) in [13, 14, 52, 10, 66]: exp = int((exp_1 + exp_2) * 0.0055) - if user_1['sect_position'] is None: - max_exp_limit = 4 - else: - max_exp_limit = user_1['sect_position'] + # if user_1['sect_position'] is None: + # max_exp_limit = 4 + # else: + # max_exp_limit = user_1['sect_position'] max_exp = 1000000000 #jsondata.sect_config_data()[str(max_exp_limit)]["max_exp"] #双修上限罪魁祸首 if exp >= max_exp: exp_limit_1 = max_exp @@ -497,17 +432,17 @@ async def two_exp_(bot: Bot, event: GroupMessageEvent, args: Message = CommandAr exp_limit_1 = exp if exp_limit_1 >= user_get_exp_max_1: - sql_message.update_exp(user_1['user_id'], user_get_exp_max_1) + await XiuxianDataManager().update_exp(user_1['user_id'], user_get_exp_max_1, 0) msg += f"{user_1['user_name']}修为到达上限,增加修为{user_get_exp_max_1}。" else: - sql_message.update_exp(user_1['user_id'], exp_limit_1) + await XiuxianDataManager().update_exp(user_1['user_id'], exp_limit_1, 0) msg += f"{user_1['user_name']}增加修为{exp_limit_1}。" - sql_message.update_power2(user_1['user_id']) + await XiuxianDataManager().update_power2(user_1['user_id']) - if user_2['sect_position'] is None: - max_exp_limit = 4 - else: - max_exp_limit = user_2['sect_position'] + # if user_2['sect_position'] is None: + # max_exp_limit = 4 + # else: + # max_exp_limit = user_2['sect_position'] max_exp = 1000000000 #jsondata.sect_config_data()[str(max_exp_limit)]["max_exp"] #双修上限罪魁祸首 if exp >= max_exp: exp_limit_2 = max_exp @@ -515,19 +450,19 @@ async def two_exp_(bot: Bot, event: GroupMessageEvent, args: Message = CommandAr exp_limit_2 = exp if exp_limit_2 >= user_get_exp_max_2: - sql_message.update_exp(user_2['user_id'], user_get_exp_max_2) + await XiuxianDataManager().update_exp(user_2['user_id'], user_get_exp_max_2, 0) msg += f"{user_2['user_name']}修为到达上限,增加修为{user_get_exp_max_2}。" else: - sql_message.update_exp(user_2['user_id'], exp_limit_2) + await XiuxianDataManager().update_exp(user_2['user_id'], exp_limit_2, 0) msg += f"{user_2['user_name']}增加修为{exp_limit_2}。" - sql_message.update_power2(user_2['user_id']) - sql_message.update_levelrate(user_1['user_id'], user_1['level_up_rate'] + 2) - sql_message.update_levelrate(user_2['user_id'], user_2['level_up_rate'] + 2) + await XiuxianDataManager().update_power2(user_2['user_id']) + await XiuxianDataManager().update_levelrate(user_1['user_id'], user_1['level_up_rate'] + 2) + await XiuxianDataManager().update_levelrate(user_2['user_id'], user_2['level_up_rate'] + 2) two_exp_cd.add_user(user_1['user_id']) two_exp_cd.add_user(user_2['user_id']) - msg += f"离开时双方互相留法宝为对方护道,双方各增加突破概率2%。" + msg += "离开时双方互相留法宝为对方护道,双方各增加突破概率2%。" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -535,54 +470,50 @@ async def two_exp_(bot: Bot, event: GroupMessageEvent, args: Message = CommandAr else: exp = int((exp_1 + exp_2) * 0.0055) - if user_1['sect_position'] is None: - max_exp_limit = 4 - else: - max_exp_limit = user_1['sect_position'] + # if user_1['sect_position'] is None: + # max_exp_limit = 4 + # else: + # max_exp_limit = user_1['sect_position'] max_exp = 1000000000 #jsondata.sect_config_data()[str(max_exp_limit)]["max_exp"] #双修上限罪魁祸首 if exp >= max_exp: exp_limit_1 = max_exp else: exp_limit_1 = exp if exp_limit_1 >= user_get_exp_max_1: - sql_message.update_exp(user_1['user_id'], user_get_exp_max_1) + await XiuxianDataManager().update_exp(user_1['user_id'], user_get_exp_max_1, 0) msg += f"{user_1['user_name']}修为到达上限,增加修为{user_get_exp_max_1}。" else: - sql_message.update_exp(user_1['user_id'], exp_limit_1) + await XiuxianDataManager().update_exp(user_1['user_id'], exp_limit_1, 0) msg += f"{user_1['user_name']}增加修为{exp_limit_1}。" - sql_message.update_power2(user_1['user_id']) + await XiuxianDataManager().update_power2(user_1['user_id']) - if user_2['sect_position'] is None: - max_exp_limit = 4 - else: - max_exp_limit = user_2['sect_position'] + # if user_2['sect_position'] is None: + # max_exp_limit = 4 + # else: + # max_exp_limit = user_2['sect_position'] max_exp = 1000000000 #jsondata.sect_config_data()[str(max_exp_limit)]["max_exp"] #双修上限罪魁祸首 if exp >= max_exp: exp_limit_2 = max_exp else: exp_limit_2 = exp if exp_limit_2 >= user_get_exp_max_2: - sql_message.update_exp(user_2['user_id'], user_get_exp_max_2) + await XiuxianDataManager().update_exp(user_2['user_id'], user_get_exp_max_2, 0) msg += f"{user_2['user_name']}修为到达上限,增加修为{user_get_exp_max_2}。" else: - sql_message.update_exp(user_2['user_id'], exp_limit_2) + await XiuxianDataManager().update_exp(user_2['user_id'], exp_limit_2, 0) msg += f"{user_2['user_name']}增加修为{exp_limit_2}。" - sql_message.update_power2(user_2['user_id']) + await XiuxianDataManager().update_power2(user_2['user_id']) two_exp_cd.add_user(user_1['user_id']) two_exp_cd.add_user(user_2['user_id']) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await two_exp.finish() else: msg = "修仙者应一心向道,务要留恋凡人!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await two_exp.finish() @@ -590,21 +521,17 @@ async def two_exp_(bot: Bot, event: GroupMessageEvent, args: Message = CommandAr async def stone_exp_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """灵石修炼""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await stone_exp.finish() user_id = user_info['user_id'] - user_mes = sql_message.get_user_info_with_id(user_id) # 获取用户信息 + user_mes = await XiuxianDataManager().get_user_infos_by_ids(user_id) # 获取用户信息 level = user_mes['level'] use_exp = user_mes['exp'] use_stone = user_mes['stone'] max_exp = ( - int(OtherSet().set_closing_type(level)) * XiuConfig().closing_exp_upper_limit + int(await OtherSet().set_closing_type(level)) * XiuConfig().closing_exp_upper_limit ) # 获取下个境界需要的修为 * 1.5为闭关上限 user_get_exp_max = int(max_exp) - use_exp @@ -619,45 +546,29 @@ async def stone_exp_(bot: Bot, event: GroupMessageEvent, args: Message = Command pass else: msg = "请输入正确的灵石数量!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await stone_exp.finish() stone_num = int(stone_num[0]) if use_stone <= stone_num: msg = "你的灵石还不够呢,快去赚点灵石吧!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await stone_exp.finish() exp = int(stone_num / 10) if exp >= user_get_exp_max: # 用户获取的修为到达上限 - sql_message.update_exp(user_id, user_get_exp_max) - sql_message.update_power2(user_id) # 更新战力 + await XiuxianDataManager().update_exp(user_id, user_get_exp_max, 0) + await XiuxianDataManager().update_power2(user_id) # 更新战力 msg = f"修炼结束,本次修炼到达上限,共增加修为:{user_get_exp_max},消耗灵石:{user_get_exp_max * 10}" - sql_message.update_ls(user_id, int(user_get_exp_max * 10), 2) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await XiuxianDataManager().update_ls(user_id, int(user_get_exp_max * 10), 1) + await handle_send(bot, event, send_group_id, msg) await stone_exp.finish() else: - sql_message.update_exp(user_id, exp) - sql_message.update_power2(user_id) # 更新战力 + await XiuxianDataManager().update_exp(user_id, exp, 0) + await XiuxianDataManager().update_power2(user_id) # 更新战力 msg = f"修炼结束,本次修炼共增加修为:{exp},消耗灵石:{stone_num}" - sql_message.update_ls(user_id, int(stone_num), 2) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await XiuxianDataManager().update_ls(user_id, int(stone_num), 1) + await handle_send(bot, event, send_group_id, msg) await stone_exp.finish() @@ -666,39 +577,23 @@ async def in_closing_(bot: Bot, event: GroupMessageEvent): """闭关""" bot, send_group_id = await assign_bot(bot=bot, event=event) user_type = 1 # 状态0为无事件 - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await out_closing.finish() user_id = user_info['user_id'] - is_type, msg = check_user_type(user_id, 0) + is_type, msg = await check_user_type(user_id, 0) if user_info['root_type'] == '伪灵根': msg = "器师无法闭关!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await in_closing.finish() if is_type: # 符合 - sql_message.in_closing(user_id, user_type) + await XiuxianDataManager().in_closing(user_id, user_type) msg = "进入闭关状态,如需出关,发送【出关】!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await in_closing.finish() else: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await in_closing.finish() @@ -707,23 +602,19 @@ async def out_closing_(bot: Bot, event: GroupMessageEvent): """出关""" bot, send_group_id = await assign_bot(bot=bot, event=event) user_type = 0 # 状态0为无事件 - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await out_closing.finish() user_id = user_info['user_id'] - user_mes = sql_message.get_user_info_with_id(user_id) # 获取用户信息 + user_mes = await XiuxianDataManager().get_user_infos_by_ids(user_id) # 获取用户信息 level = user_mes['level'] use_exp = user_mes['exp'] hp_speed = 25 mp_speed = 50 max_exp = ( - int(OtherSet().set_closing_type(level)) * XiuConfig().closing_exp_upper_limit + int(await OtherSet().set_closing_type(level)) * XiuConfig().closing_exp_upper_limit ) # 获取下个境界需要的修为 * 1.5为闭关上限 user_get_exp_max = int(max_exp) - use_exp @@ -732,54 +623,44 @@ async def out_closing_(bot: Bot, event: GroupMessageEvent): user_get_exp_max = 0 now_time = datetime.now() - user_cd_message = sql_message.get_user_cd(user_id) - is_type, msg = check_user_type(user_id, 1) + user_cd_message = await XiuxianDataManager().get_user_time(user_id) + is_type, msg = await check_user_type(user_id, 1) if not is_type: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await out_closing.finish() else: # 用户状态为1 - in_closing_time = datetime.strptime( - user_cd_message['create_time'], "%Y-%m-%d %H:%M:%S.%f" - ) # 进入闭关的时间 + in_closing_time = user_cd_message['schedule_create_time'] # 进入闭关的时间 exp_time = ( OtherSet().date_diff(now_time, in_closing_time) // 60 ) # 闭关时长计算(分钟) = second // 60 - level_rate = sql_message.get_root_rate(user_mes['root_type']) # 灵根倍率 + level_rate = await XiuxianDataManager().get_root_rate(user_mes['root_type']) # 灵根倍率 realm_rate = jsondata.level_data()[level]["spend"] # 境界倍率 - user_buff_data = UserBuffDate(user_id) - user_blessed_spot_data = UserBuffDate(user_id).BuffInfo['blessed_spot'] - mainbuffdata = user_buff_data.get_user_main_buff_data() - mainbuffratebuff = mainbuffdata['ratebuff'] if mainbuffdata != None else 0 # 功法修炼倍率 - mainbuffcloexp = mainbuffdata['clo_exp'] if mainbuffdata != None else 0 # 功法闭关经验 - mainbuffclors = mainbuffdata['clo_rs'] if mainbuffdata != None else 0 # 功法闭关回复 + user_buff_data = UserBuffData(user_id) + user_blessed_spot_data = (await user_buff_data.BuffInfo)['blessed_spot'] + mainbuffdata = await user_buff_data.get_user_main_buff_data() + mainbuffratebuff = mainbuffdata['ratebuf'] if mainbuffdata is not None else 0 # 功法修炼倍率 + mainbuffcloexp = mainbuffdata['clo_exp'] if mainbuffdata is not None else 0 # 功法闭关经验 + mainbuffclors = mainbuffdata['clo_rs'] if mainbuffdata is not None else 0 # 功法闭关回复 exp = int( (exp_time * XiuConfig().closing_exp) * ((level_rate * realm_rate * (1 + mainbuffratebuff) * (1 + mainbuffcloexp) * (1 + user_blessed_spot_data))) # 洞天福地为加法 ) # 本次闭关获取的修为 # 计算传承增益 - impart_data = xiuxian_impart.get_user_impart_info_with_id(user_id) - impart_exp_up = impart_data['impart_exp_up'] if impart_data is not None else 0 - exp = int(exp * (1 + impart_exp_up)) + impart_data = await XiuxianDataManager().get_user_impart_info_with_id(user_id) + impart_exp_addition = impart_data['impart_exp_addition'] if impart_data is not None else 0 + exp = int(exp * (1 + impart_exp_addition)) if exp >= user_get_exp_max: # 用户获取的修为到达上限 - sql_message.in_closing(user_id, user_type) - sql_message.update_exp(user_id, user_get_exp_max) - sql_message.update_power2(user_id) # 更新战力 + await XiuxianDataManager().in_closing(user_id, user_type) + await XiuxianDataManager().update_exp(user_id, user_get_exp_max, 0) + await XiuxianDataManager().update_power2(user_id) # 更新战力 - result_msg, result_hp_mp = OtherSet().send_hp_mp(user_id, int(exp * hp_speed * (1 + mainbuffclors)), int(exp * mp_speed)) - sql_message.update_user_attribute(user_id, result_hp_mp[0], result_hp_mp[1], int(result_hp_mp[2] / 10)) + result_msg, result_hp_mp = await OtherSet().send_hp_mp(user_id, int(exp * hp_speed * (1 + mainbuffclors)), int(exp * mp_speed)) + await XiuxianDataManager().update_user_attribute(user_id, result_hp_mp[0], result_hp_mp[1], int(result_hp_mp[2] / 10)) msg = f"闭关结束,本次闭关到达上限,共增加修为:{user_get_exp_max}{result_msg[0]}{result_msg[1]}" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await out_closing.finish() else: # 用户获取的修为没有到达上限 @@ -789,46 +670,46 @@ async def out_closing_(bot: Bot, event: GroupMessageEvent): user_stone = 0 if exp <= user_stone: exp = exp * 2 - sql_message.in_closing(user_id, user_type) - sql_message.update_exp(user_id, exp) - sql_message.update_ls(user_id, int(exp / 2), 2) - sql_message.update_power2(user_id) # 更新战力 + await XiuxianDataManager().in_closing(user_id, user_type) + await XiuxianDataManager().update_exp(user_id, exp, 0) + await XiuxianDataManager().update_ls(user_id, int(exp / 2), 1) + await XiuxianDataManager().update_power2(user_id) # 更新战力 - result_msg, result_hp_mp = OtherSet().send_hp_mp(user_id, int(exp * hp_speed * (1 + mainbuffclors)), int(exp * mp_speed)) - sql_message.update_user_attribute(user_id, result_hp_mp[0], result_hp_mp[1], + result_msg, result_hp_mp = await OtherSet().send_hp_mp(user_id, int(exp * hp_speed * (1 + mainbuffclors)), int(exp * mp_speed)) + await XiuxianDataManager().update_user_attribute(user_id, result_hp_mp[0], result_hp_mp[1], int(result_hp_mp[2] / 10)) msg = f"闭关结束,共闭关{exp_time}分钟,本次闭关增加修为:{exp},消耗灵石{int(exp / 2)}枚{result_msg[0]}{result_msg[1]}" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await out_closing.finish() else: exp = exp + user_stone - sql_message.in_closing(user_id, user_type) - sql_message.update_exp(user_id, exp) - sql_message.update_ls(user_id, user_stone, 2) - sql_message.update_power2(user_id) # 更新战力 - result_msg, result_hp_mp = OtherSet().send_hp_mp(user_id, int(exp * hp_speed * (1 + mainbuffclors)), int(exp * mp_speed)) - sql_message.update_user_attribute(user_id, result_hp_mp[0], result_hp_mp[1], + await XiuxianDataManager().in_closing(user_id, user_type) + await XiuxianDataManager().update_exp(user_id, exp, 0) + await XiuxianDataManager().update_ls(user_id, user_stone, 1) + await XiuxianDataManager().update_power2(user_id) # 更新战力 + result_msg, result_hp_mp = await OtherSet().send_hp_mp(user_id, int(exp * hp_speed * (1 + mainbuffclors)), int(exp * mp_speed)) + await XiuxianDataManager().update_user_attribute(user_id, result_hp_mp[0], result_hp_mp[1], int(result_hp_mp[2] / 10)) msg = f"闭关结束,共闭关{exp_time}分钟,本次闭关增加修为:{exp},消耗灵石{user_stone}枚{result_msg[0]}{result_msg[1]}" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await out_closing.finish() else: - sql_message.in_closing(user_id, user_type) - sql_message.update_exp(user_id, exp) - sql_message.update_power2(user_id) # 更新战力 - result_msg, result_hp_mp = OtherSet().send_hp_mp(user_id, int(exp * hp_speed * (1 + mainbuffclors)), int(exp * mp_speed)) - sql_message.update_user_attribute(user_id, result_hp_mp[0], result_hp_mp[1], int(result_hp_mp[2] / 10)) + await XiuxianDataManager().in_closing(user_id, user_type) + await XiuxianDataManager().update_exp(user_id, exp, 0) + await XiuxianDataManager().update_power2(user_id) # 更新战力 + result_msg, result_hp_mp = await OtherSet().send_hp_mp(user_id, int(exp * hp_speed * (1 + mainbuffclors)), int(exp * mp_speed)) + await XiuxianDataManager().update_user_attribute(user_id, result_hp_mp[0], result_hp_mp[1], int(result_hp_mp[2] / 10)) msg = f"闭关结束,共闭关{exp_time}分钟,本次闭关增加修为:{exp}{result_msg[0]}{result_msg[1]}" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -839,111 +720,104 @@ async def out_closing_(bot: Bot, event: GroupMessageEvent): async def mind_state_(bot: Bot, event: GroupMessageEvent): """我的状态信息""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_msg, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await mind_state.finish() - user_id = user_msg['user_id'] - sql_message.update_last_check_info_time(user_id) # 更新查看修仙信息时间 - if user_msg['hp'] is None or user_msg['hp'] == 0: - sql_message.update_user_hp(user_id) - user_msg = sql_message.get_user_real_info(user_id) + user_id = user_info['user_id'] + await XiuxianDataManager().update_last_check_info_time(user_id) # 更新查看修仙信息时间 + if user_info['hp'] is None or user_info['hp'] == 0: + await XiuxianDataManager().update_user_hp(user_id) + user_msg = await XiuxianDataManager().get_user_real_info(user_id) - level_rate = sql_message.get_root_rate(user_msg['root_type']) # 灵根倍率 + level_rate = await XiuxianDataManager().get_root_rate(user_msg['root_type']) # 灵根倍率 realm_rate = jsondata.level_data()[user_msg['level']]["spend"] # 境界倍率 - user_buff_data = UserBuffDate(user_id) - user_blessed_spot_data = UserBuffDate(user_id).BuffInfo['blessed_spot'] - main_buff_data = user_buff_data.get_user_main_buff_data() - user_armor_crit_data = user_buff_data.get_user_armor_buff_data() #我的状态防具会心 - user_weapon_data = UserBuffDate(user_id).get_user_weapon_data() #我的状态武器减伤 - user_main_crit_data = UserBuffDate(user_id).get_user_main_buff_data() #我的状态功法会心 - user_main_data = UserBuffDate(user_id).get_user_main_buff_data() #我的状态功法减伤 + user_buff_data = UserBuffData(user_id) + user_blessed_spot_data = (await user_buff_data.BuffInfo)['blessed_spot'] + main_buff_data = await user_buff_data.get_user_main_buff_data() + user_armor_crit_data = await user_buff_data.get_user_armor_buff_data() #我的状态防具会心 + user_weapon_data = await UserBuffData(user_id).get_user_weapon_data() #我的状态武器减伤 + user_main_crit_data = await UserBuffData(user_id).get_user_main_buff_data() #我的状态功法会心 + user_main_data = await UserBuffData(user_id).get_user_main_buff_data() #我的状态功法减伤 if user_main_data is not None: - main_def = user_main_data['def_buff'] * 100 #我的状态功法减伤 + main_def = user_main_data['def_buf'] * 100 #我的状态功法减伤 else: main_def = 0 if user_armor_crit_data is not None: #我的状态防具会心 - armor_crit_buff = ((user_armor_crit_data['crit_buff']) * 100) + armor_crit_buff = ((user_armor_crit_data['crit_buf']) * 100) else: armor_crit_buff = 0 if user_weapon_data is not None: - crit_buff = ((user_weapon_data['crit_buff']) * 100) + crit_buff = ((user_weapon_data['crit_buf']) * 100) else: crit_buff = 0 - user_armor_data = user_buff_data.get_user_armor_buff_data() + user_armor_data = await user_buff_data.get_user_armor_buff_data() if user_armor_data is not None: - def_buff = int(user_armor_data['def_buff'] * 100) #我的状态防具减伤 + def_buff = int(user_armor_data['def_buf'] * 100) #我的状态防具减伤 else: def_buff = 0 - user_armor_data = user_buff_data.get_user_armor_buff_data() + user_armor_data = await user_buff_data.get_user_armor_buff_data() if user_weapon_data is not None: - weapon_def = user_weapon_data['def_buff'] * 100 #我的状态武器减伤 + weapon_def = int(user_weapon_data['def_buf'] * 100) #我的状态武器减伤 else: weapon_def = 0 if user_main_crit_data is not None: #我的状态功法会心 - main_crit_buff = ((user_main_crit_data['crit_buff']) * 100) + main_crit_buff = ((user_main_crit_data['crit_buf']) * 100) else: main_crit_buff = 0 list_all = len(OtherSet().level) - 1 now_index = OtherSet().level.index(user_msg['level']) if list_all == now_index: - exp_meg = f"位面至高" + exp_meg = "位面至高" else: is_updata_level = OtherSet().level[now_index + 1] - need_exp = sql_message.get_level_power(is_updata_level) + need_exp = await XiuxianDataManager().get_level_power(is_updata_level) get_exp = need_exp - user_msg['exp'] if get_exp > 0: exp_meg = f"还需{number_to(get_exp)}修为可突破!" else: - exp_meg = f"可突破!" + exp_meg = "可突破!" - main_buff_rate_buff = main_buff_data['ratebuff'] if main_buff_data is not None else 0 - main_hp_buff = main_buff_data['hpbuff'] if main_buff_data is not None else 0 - main_mp_buff = main_buff_data['mpbuff'] if main_buff_data is not None else 0 - impart_data = xiuxian_impart.get_user_impart_info_with_id(user_id) - impart_hp_per = impart_data['impart_hp_per'] if impart_data is not None else 0 - impart_mp_per = impart_data['impart_mp_per'] if impart_data is not None else 0 - impart_know_per = impart_data['impart_know_per'] if impart_data is not None else 0 - impart_burst_per = impart_data['impart_burst_per'] if impart_data is not None else 0 - boss_atk = impart_data['boss_atk'] if impart_data is not None else 0 - weapon_critatk_data = UserBuffDate(user_id).get_user_weapon_data() #我的状态武器会心伤害 + main_buff_rate_buff = main_buff_data['ratebuf'] if main_buff_data is not None else 0 + main_hp_buff = main_buff_data['hpbuf'] if main_buff_data is not None else 0 + # main_mp_buff = main_buff_data['mpbuf'] if main_buff_data is not None else 0 + impart_data = await XiuxianDataManager().get_user_impart_info_with_id(user_id) + impart_hp_addition = impart_data['impart_hp_addition'] if impart_data is not None else 0 + # impart_mp_addition = impart_data['impart_mp_addition'] if impart_data is not None else 0 + impart_crit_addition = impart_data['impart_crit_addition'] if impart_data is not None else 0 + impart_crit_dmg_addition = impart_data['impart_crit_dmg_addition'] if impart_data is not None else 0 + impart_boss_atk_addition = impart_data['impart_boss_atk_addition'] if impart_data is not None else 0 + weapon_critatk_data = await UserBuffData(user_id).get_user_weapon_data() #我的状态武器会心伤害 weapon_critatk = weapon_critatk_data['critatk'] if weapon_critatk_data is not None else 0 #我的状态武器会心伤害 - user_main_critatk = UserBuffDate(user_id).get_user_main_buff_data() #我的状态功法会心伤害 + user_main_critatk = await UserBuffData(user_id).get_user_main_buff_data() #我的状态功法会心伤害 main_critatk = user_main_critatk['critatk'] if user_main_critatk is not None else 0 #我的状态功法会心伤害 leveluprate = int(user_msg['level_up_rate']) # 用户失败次数加成 number = user_main_critatk["number"] if user_main_critatk is not None else 0 msg = f""" 道号:{user_msg['user_name']} -气血:{number_to(user_msg['hp'])}/{number_to(int((user_msg['exp'] / 2) * (1 + main_hp_buff + impart_hp_per)))}({((user_msg['hp'] / ((user_msg['exp'] / 2) * (1 + main_hp_buff + impart_hp_per)))) * 100:.2f}%) +境界:{user_msg['level']} +气血:{number_to(user_msg['hp'])}/{number_to(int((user_msg['exp'] / 2) * (1 + main_hp_buff + impart_hp_addition)))}({((user_msg['hp'] / ((user_msg['exp'] / 2) * (1 + main_hp_buff + impart_hp_addition)))) * 100:.2f}%) 真元:{number_to(user_msg['mp'])}/{number_to(user_msg['exp'])}({((user_msg['mp'] / user_msg['exp']) * 100):.2f}%) 攻击:{number_to(user_msg['atk'])} 突破状态: {exp_meg}(概率:{jsondata.level_rate_data()[user_msg['level']] + leveluprate + number}%) -攻击修炼:{user_msg['atkpractice']}级(提升攻击力{user_msg['atkpractice'] * 4}%) +攻击修炼:{user_msg['atk_practice_level']}级(提升攻击力{user_msg['atk_practice_level'] * 4}%) 修炼效率:{int(((level_rate * realm_rate) * (1 + main_buff_rate_buff) * (1+ user_blessed_spot_data)) * 100)}% -会心:{crit_buff + int(impart_know_per * 100) + armor_crit_buff + main_crit_buff}% +会心:{crit_buff + int(impart_crit_addition * 100) + armor_crit_buff + main_crit_buff}% 减伤率:{def_buff + weapon_def + main_def}% -boss战增益:{int(boss_atk * 100)}% -会心伤害增益:{int((1.5 + impart_burst_per + weapon_critatk + main_critatk) * 100)}% +boss战增益:{int(impart_boss_atk_addition * 100)}% +会心伤害增益:{int((1.5 + float(impart_crit_dmg_addition) + float(weapon_critatk) + float(main_critatk)) * 100)}% """ - sql_message.update_last_check_info_time(user_id) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await XiuxianDataManager().update_last_check_info_time(user_id) + await handle_send(bot, event, send_group_id, msg) await mind_state.finish() @@ -951,44 +825,36 @@ async def mind_state_(bot: Bot, event: GroupMessageEvent): async def buffinfo_(bot: Bot, event: GroupMessageEvent): """我的功法""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await buffinfo.finish() user_id = user_info['user_id'] - mainbuffdata = UserBuffDate(user_id).get_user_main_buff_data() - if mainbuffdata != None: - s, mainbuffmsg = get_main_info_msg(str(get_user_buff(user_id)['main_buff'])) + mainbuffdata = await UserBuffData(user_id).get_user_main_buff_data() + if mainbuffdata is not None: + s, mainbuffmsg = get_main_info_msg(str(get_user_buff(user_id)['main_skill'])) else: mainbuffmsg = '' - subbuffdata = UserBuffDate(user_id).get_user_sub_buff_data()#辅修功法13 - if subbuffdata != None: - sub, subbuffmsg = get_sub_info_msg(str(get_user_buff(user_id)['sub_buff'])) + subbuffdata = await UserBuffData(user_id).get_user_sub_buff_data()#辅修功法13 + if subbuffdata is not None: + sub, subbuffmsg = get_sub_info_msg(str(get_user_buff(user_id)['support_skill'])) else: subbuffmsg = '' - secbuffdata = UserBuffDate(user_id).get_user_sec_buff_data() + secbuffdata = await UserBuffData(user_id).get_user_sec_buff_data() secbuffmsg = get_sec_msg(secbuffdata) if get_sec_msg(secbuffdata) != '无' else '' msg = f""" -道友的主功法:{mainbuffdata["name"] if mainbuffdata != None else '无'} +道友的主功法:{mainbuffdata["name"] if mainbuffdata is not None else '无'} {mainbuffmsg} -道友的辅修功法:{subbuffdata["name"] if subbuffdata != None else '无'} +道友的辅修功法:{subbuffdata["name"] if subbuffdata is not None else '无'} {subbuffmsg} -道友的神通:{secbuffdata["name"] if secbuffdata != None else '无'} +道友的神通:{secbuffdata["name"] if secbuffdata is not None else '无'} {secbuffmsg} """ - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await buffinfo.finish() @@ -996,23 +862,15 @@ async def buffinfo_(bot: Bot, event: GroupMessageEvent): async def del_exp_decimal_(bot: Bot, event: GroupMessageEvent): """清除修为浮点数""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await del_exp_decimal.finish() user_id = user_info['user_id'] exp = user_info['exp'] - sql_message.del_exp_decimal(user_id, exp) - msg = f"黑暗动乱暂时抑制成功!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await XiuxianDataManager().del_exp_decimal(user_id, exp) + msg = "黑暗动乱暂时抑制成功!" + await handle_send(bot, event, send_group_id, msg) await del_exp_decimal.finish() @@ -1021,29 +879,21 @@ async def my_exp_num_(bot: Bot, event: GroupMessageEvent): """我的双修次数""" global two_exp_limit bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await my_exp_num.finish() user_id = user_info['user_id'] limt = two_exp_cd.find_user(user_id) - impart_data = xiuxian_impart.get_user_impart_info_with_id(user_id) - impart_two_exp = impart_data['impart_two_exp'] if impart_data is not None else 0 + impart_data = await XiuxianDataManager().get_user_impart_info_with_id(user_id) + impart_two_exp_quantity = impart_data['impart_two_exp_quantity'] if impart_data is not None else 0 - main_two_data = UserBuffDate(user_id).get_user_main_buff_data() + main_two_data = await UserBuffData(user_id).get_user_main_buff_data() main_two = main_two_data['two_buff'] if main_two_data is not None else 0 - num = (two_exp_limit + impart_two_exp + main_two) - limt + num = (two_exp_limit + impart_two_exp_quantity + main_two) - limt if num <= 0: num = 0 msg = f"道友剩余双修次数{num}次!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await my_exp_num.finish() diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_buff/two_exp_cd.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_buff/two_exp_cd.py index 04ea9323..f0c00f58 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_buff/two_exp_cd.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_buff/two_exp_cd.py @@ -13,7 +13,7 @@ def __init__(self): try: with open(self.data_path, 'r', encoding='utf-8') as f: self.data = json.load(f) - except: + except FileNotFoundError: self.info = {"two_exp_cd": {}} data = json.dumps(self.info, ensure_ascii=False, indent=4) with open(self.data_path, mode="x", encoding="UTF-8") as f: @@ -38,7 +38,7 @@ def find_user(self, user_id): try: if self.data["two_exp_cd"][user_id] >= 0: return self.data["two_exp_cd"][user_id] - except: + except ValueError: self.data["two_exp_cd"][user_id] = 0 self.__save() return self.data["two_exp_cd"][user_id] diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_config.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_config.py index 7753fef2..21086916 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_config.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_config.py @@ -45,28 +45,10 @@ def convert_rank(rank_name): class XiuConfig: def __init__(self): - self.sql_table = ["user_xiuxian", "user_cd", "sects", "back", "BuffInfo"] - self.sql_user_xiuxian = ["id", "user_id", "user_name", "stone", "root", - "root_type", "level", "power", - "create_time", "is_sign", "is_beg", "is_ban", - "exp", "work_num", "level_up_cd", - "level_up_rate", "sect_id", - "sect_position", "hp", "mp", "atk", - "atkpractice", "sect_task", "sect_contribution", - "sect_elixir_get", "blessed_spot_flag", "blessed_spot_name", "user_stamina"] - self.sql_user_cd = ["user_id", "type", "create_time", "scheduled_time", "last_check_info_time"] - self.sql_sects = ["sect_id", "sect_name", "sect_owner", "sect_scale", "sect_used_stone", "sect_fairyland", - "sect_materials", "mainbuff", "secbuff", "elixir_room_level"] - self.sql_buff = ["id", "user_id", "main_buff", "sec_buff", "faqi_buff", "fabao_weapon", "armor_buff", - "atk_buff", "sub_buff", "blessed_spot"] - self.sql_back = ["user_id", "goods_id", "goods_name", "goods_type", "goods_num", "create_time", "update_time", - "remake", "day_num", "all_num", "action_time", "state", "bind_num"] - self.sql_user_auctions = [""] - # 上面是数据库校验,不知道做什么的话别动 self.level = convert_rank('江湖好手')[1] # 境界列表,别动 self.img = True # 是否使用图片发送消息 self.user_info_image = True # 是否使用图片发送个人信息 - self.level_up_cd = 0 # 突破CD(分钟) + self.level_up_time = 0 # 突破CD(分钟) self.closing_exp = 60 # 闭关每分钟获取的修为 self.put_bot = [] # 接收消息qq,主qq,框架将只处理此qq的消息 self.main_bo = [] # 负责发送消息的qq @@ -75,37 +57,43 @@ def __init__(self): # QQ所负责的群聊 #{群 :bot} 其中 bot类型 []或str } # "123456":"123456", self.sect_min_level = "铭纹境圆满" # 创建宗门最低境界 - self.sect_create_cost = 5000000 # 创建宗门消耗 - self.sect_rename_cost = 50000000 # 宗门改名消耗 + self.sect_create_cost = 500000 # 创建宗门消耗 + self.sect_rename_cost = 500000 # 宗门改名消耗 self.sect_rename_cd = 1 # 宗门改名cd/天 self.auto_change_sect_owner_cd = 7 # 自动换长时间不玩宗主cd/天 self.closing_exp_upper_limit = 1.5 # 闭关获取修为上限(例如:1.5 下个境界的修为数*1.5) self.level_punishment_floor = 10 # 突破失败扣除修为,惩罚下限(百分比) self.level_punishment_limit = 35 # 突破失败扣除修为,惩罚上限(百分比) self.level_up_probability = 0.2 # 突破失败增加当前境界突破概率的比例 - self.sign_in_lingshi_lower_limit = 10000 # 每日签到灵石下限 - self.sign_in_lingshi_upper_limit = 50000 # 每日签到灵石上限 + self.sign_in_lingshi_lower_limit = 1000 # 每日签到灵石下限 + self.sign_in_lingshi_upper_limit = 5000 # 每日签到灵石上限 self.beg_max_level = "铭纹境圆满" # 仙途奇缘能领灵石最高境界 self.beg_max_days = 3 # 仙途奇缘能领灵石最多天数 - self.beg_lingshi_lower_limit = 200000 # 仙途奇缘灵石下限 - self.beg_lingshi_upper_limit = 500000 # 仙途奇缘灵石上限 + self.beg_lingshi_lower_limit = 20000 # 仙途奇缘灵石下限 + self.beg_lingshi_upper_limit = 50000 # 仙途奇缘灵石上限 self.tou = 100000 # 偷灵石惩罚 self.dufang_cd = 10 # 金银阁cd/秒 self.tou_lower_limit = 0.01 # 偷灵石下限(百分比) self.tou_upper_limit = 0.50 # 偷灵石上限(百分比) - self.remake = 100000 # 重入仙途的消费 - self.max_stamina = 240 # 体力上限 - self.stamina_recovery_points = 1 # 体力恢复点数/分钟 + self.remake = 10000 # 重入仙途的消费 + self.max_stamina = 2400 # 体力上限 + self.stamina_recovery_points = 5 # 体力恢复点数/分钟 self.lunhui_min_level = "祭道境圆满" # 千世轮回最低境界 self.twolun_min_level = "祭道境圆满" # 万世轮回最低境界 self.del_boss_id = [] # 支持非管理员和超管天罚boss self.gen_boss_id = [] # 支持非管理员和超管生成boss - self.merge_forward_send = True # 使用消息合并转发,True是合并转发,False是合并转发的内容转换成长图发送 + self.merge_forward_send = False # 使用消息合并转发,True是合并转发,False是合并转发的内容转换成长图发送 self.img_compression_limit = 90 # 图片压缩率,0为不压缩,最高100,jpeg请调低压缩率 self.img_type = "webp" # 图片类型,webp或者jpeg,如果机器人的图片消息不显示请使用jpeg self.img_send_type = "io" # 图片发送类型,官方bot建议base64 self.admin_debug = False # 管理员调试模式,开启后只响应超管指令 - self.version = "xiuxian_2.2" # 修仙插件版本,别动 + # 数据库地址,格式为 postgresql://用户名:密码@localhost:5432/数据库名称 注意密码中如果有@符号记得转换成%40 + self.postgresql_url="" + self.min_database_connection = 20 # 数据库连接池最小连接数 + self.max_database_connection = 100 # 数据库连接池最大连接数 + self.backup_quantity = 60 # 保留备份数量 + self.backup_interval = 30 # 备份间隔/分钟 + self.version = "xiuxian_2.3" # 修仙插件版本,别动 class JsonConfig: diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_dufang/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_dufang/__init__.py index eafd797f..8c696e05 100644 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_dufang/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_dufang/__init__.py @@ -11,17 +11,18 @@ MessageSegment ) from nonebot.params import RegexGroup -from ..xiuxian_utils.xiuxian2_handle import XiuxianDateManage +from ..xiuxian_utils.xiuxian2_handle import XiuxianDataManager from ..xiuxian_config import XiuConfig from ..xiuxian_utils.utils import ( check_user, get_msg_pic, - CommandObjectID + CommandObjectID, + handle_send ) cache_help = {} -sql_message = XiuxianDateManage() # sql类 + # sql类 -__dufang_help__ = f""" +__dufang_help__ = """ 封群的,不建议玩!!! 超管可以调试,如果你真想玩并且不介意封群风险,可以让超管修改代码 """.strip() @@ -54,25 +55,17 @@ async def dufang_help_(bot: Bot, event: GroupMessageEvent, session_id: int = Com async def dufang_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = RegexGroup()): bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) user_id = user_info['user_id'] if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await dufang.finish() - user_message = sql_message.get_user_info_with_id(user_id) + user_message = await XiuxianDataManager().get_user_infos_by_ids(user_id) if args[2] is None: - msg = f"请输入正确的指令,例如金银阁10大、金银阁10奇、金银阁10猜3" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请输入正确的指令,例如金银阁10大、金银阁10奇、金银阁10猜3" + await handle_send(bot, event, send_group_id, msg) await dufang.finish() price = args[1] # 300 @@ -81,84 +74,48 @@ async def dufang_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = Re if mode == '猜': mode_num = args[3] # 猜的数值 if str(mode_num) not in ['1', '2', '3', '4', '5', '6']: - msg = f"请输入正确的指令,例如金银阁10大、、金银阁10奇、金银阁10猜3" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请输入正确的指令,例如金银阁10大、、金银阁10奇、金银阁10猜3" + await handle_send(bot, event, send_group_id, msg) await dufang.finish() price_num = int(price) if int(user_message['stone']) < price_num: msg = "道友的金额不足,请重新输入!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) elif price_num == 0: msg = "走开走开,没钱也敢来这赌!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) value = random.randint(1, 6) result = f"[CQ:dice,value={value}]" if value >= 4 and str(mode) == "大": - sql_message.update_ls(user_id, price_num, 1) + await XiuxianDataManager().update_ls(user_id, price_num, 0) await bot.send_group_msg(group_id=int(send_group_id), message=result) msg = f"最终结果为{value},你猜对了,收获灵石{price_num}块" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) elif value <= 3 and str(mode) == "小": - sql_message.update_ls(user_id, price_num, 1) + await XiuxianDataManager().update_ls(user_id, price_num, 0) await bot.send_group_msg(group_id=int(send_group_id), message=result) msg = f"最终结果为{value},你猜对了,收获灵石{price_num}块" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) elif value %2==1 and str(mode) == "奇": - sql_message.update_ls(user_id, price_num, 1) + await XiuxianDataManager().update_ls(user_id, price_num, 0) await bot.send_group_msg(group_id=int(send_group_id), message=result) msg = f"最终结果为{value},你猜对了,收获灵石{price_num}块" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) elif value %2==0 and str(mode) == "偶": - sql_message.update_ls(user_id, price_num, 1) + await XiuxianDataManager().update_ls(user_id, price_num, 0) msg = f"最终结果为{value},你猜对了,收获灵石{price_num}块" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) elif str(value) == str(mode_num) and str(mode) == "猜": - sql_message.update_ls(user_id, price_num * 5, 1) + await XiuxianDataManager().update_ls(user_id, price_num * 5, 0) msg = f"最终结果为{value},你猜对了,收获灵石{price_num * 5}块" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) else: - sql_message.update_ls(user_id, price_num, 2) + await XiuxianDataManager().update_ls(user_id, price_num, 1) msg = f"最终结果为{value},你猜错了,损失灵石{price_num}块" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) \ No newline at end of file + await handle_send(bot, event, send_group_id, msg) \ No newline at end of file diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_fusion/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_fusion/__init__.py index b7283438..500aa133 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_fusion/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_fusion/__init__.py @@ -1,193 +1,149 @@ -from ..xiuxian_utils.lay_out import assign_bot, Cooldown -from nonebot.params import CommandArg -from nonebot import on_command -from ..xiuxian_config import XiuConfig -from ..xiuxian_utils.xiuxian2_handle import XiuxianDateManage -from nonebot.adapters.onebot.v11 import ( - Bot, - GROUP, - Message, - GroupMessageEvent, - MessageSegment -) -from ..xiuxian_utils.item_json import Items -from ..xiuxian_config import convert_rank -from ..xiuxian_back.back_util import get_item_msg -from ..xiuxian_utils.utils import ( - check_user, get_msg_pic, number_to -) -sql_message = XiuxianDateManage() -items = Items() - -fusion_help_text = f""" -合成帮助: -1.合成 物品名:合成指定的物品。 -2.可合成物品 [物品名参数可选] 可以查看当前可合成的所有物品以及相关信息。 -""".strip() - - -fusion = on_command('合成', priority=15, permission=GROUP, block=True) -fusion_help = on_command("合成帮助", permission=GROUP, priority=15, block=True) -available_fusion = on_command('查看可合成物品', priority=15, permission=GROUP, block=True) - - -@fusion_help.handle(parameterless=[Cooldown(at_sender=False)]) -async def fusion_help_(bot: Bot, event: GroupMessageEvent): - bot, send_group_id = await assign_bot(bot=bot, event=event) - msg = fusion_help_text - if XiuConfig().img: - pic = await get_msg_pic(msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await fusion_help.finish() - - -@fusion.handle(parameterless=[Cooldown(at_sender=False)]) -async def fusion_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): - bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) - if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await fusion.finish() - - user_id = user_info['user_id'] - back_msg = sql_message.get_back_msg(user_id) - if back_msg is None: - msg = "道友的背包空空如也!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await fusion.finish() - - args_str = args.extract_plain_text().strip() - equipment_id, equipment = items.get_data_by_item_name(args_str) - if equipment is None: - msg = f"未找到可合成的物品:{args_str}" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await fusion.finish() - - fusion_info = equipment.get('fusion', None) - if not fusion_info: - msg = f"{equipment['name']} 不是一件可以合成的物品!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await fusion.finish() - - limit = fusion_info.get('limit', None) - if limit is not None: - current_amount = 0 - for back in back_msg: - if back['goods_id'] == int(equipment_id): - current_amount = back['goods_num'] - break - if current_amount >= limit: - msg = f"道友的背包中已有足够数量的 {equipment['name']},无法再次合成!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await fusion.finish() - - required_rank = fusion_info.get('need_rank', '江湖好手') - if convert_rank(user_info['level'])[0] > convert_rank(required_rank)[0]: - msg = f"道友的境界不足,合成 {equipment['name']} 需要达到 {required_rank}!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await fusion.finish() - - if user_info['exp'] < int(fusion_info.get('need_exp', 0)): - msg = f"道友的修为不足,合成 {equipment['name']} 需要修为 {int(fusion_info.get('need_exp', 0))}!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await fusion.finish() - - if user_info['stone'] < int(fusion_info.get('need_stone', 0)): - msg = f"道友的灵石不足,合成 {equipment['name']} 需要 {number_to(int(fusion_info.get('need_stone', 0)))} 枚灵石呢!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await fusion.finish() - - needed_items = fusion_info.get('need_item', {}) - missing_items = [] - for item_id, amount_needed in needed_items.items(): - total_amount = 0 - for back in back_msg: - if back['goods_id'] == int(item_id): - total_amount += back['goods_num'] - if total_amount < amount_needed: - missing_items.append((item_id, amount_needed - total_amount)) - - if missing_items: - missing_names = [f"{amount_needed} 个 {items.get_data_by_item_id(int(item_id))['name']}" for item_id, amount_needed in missing_items] - msg = "道友还缺少:\n" + "\n".join(missing_names) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await fusion.finish() - - sql_message.update_ls(user_id, int(fusion_info.get('need_stone', 0)), 2) # 扣灵石 - for item_id, amount_needed in needed_items.items(): - sql_message.update_back_j(user_id, int(item_id), amount_needed) # 扣道具 - - sql_message.send_back(user_id, int(equipment_id), equipment['name'], equipment['type'], 1, 1) - - item_type = equipment.get('type', '物品') - msg = f"道友成功合成了{item_type}: {equipment['name']}!!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await fusion.finish() - - -@available_fusion.handle(parameterless=[Cooldown(at_sender=False)]) -async def available_fusion_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): - bot, send_group_id = await assign_bot(bot=bot, event=event) - args_str = args.extract_plain_text().strip() - - if args_str: - equipment_id, equipment = items.get_data_by_item_name(args_str) - if equipment and 'fusion' in equipment: - msg = get_item_msg(int(equipment_id)) - else: - msg = f"未找到可合成的物品:{args_str}" - else: - fusion_items = items.get_fusion_items() - if not fusion_items: - msg = "目前没有可合成的物品。" - else: - msg = "可合成的物品如下:\n" + "\n".join(fusion_items) - - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await available_fusion.finish() +from ..xiuxian_utils.lay_out import assign_bot, Cooldown +from nonebot.params import CommandArg +from nonebot import on_command +from ..xiuxian_config import XiuConfig +from ..xiuxian_utils.xiuxian2_handle import XiuxianDataManager +from nonebot.adapters.onebot.v11 import ( + Bot, + GROUP, + Message, + GroupMessageEvent, + MessageSegment +) +from ..xiuxian_utils.item_json import Items +from ..xiuxian_config import convert_rank +from ..xiuxian_back.back_util import get_item_msg +from ..xiuxian_utils.utils import ( + check_user, get_msg_pic, number_to, handle_send +) + +items = Items() + +fusion_help_text = """ +合成帮助: +1.合成 物品名:合成指定的物品。 +2.查看可合成物品 [物品名参数可选] 可以查看当前可合成的所有物品以及相关信息。 +""".strip() + + +fusion = on_command('合成', priority=15, permission=GROUP, block=True) +fusion_help = on_command("合成帮助", permission=GROUP, priority=15, block=True) +available_fusion = on_command('查看可合成物品', priority=15, permission=GROUP, block=True) + + +@fusion_help.handle(parameterless=[Cooldown(at_sender=False)]) +async def fusion_help_(bot: Bot, event: GroupMessageEvent): + bot, send_group_id = await assign_bot(bot=bot, event=event) + msg = fusion_help_text + if XiuConfig().img: + pic = await get_msg_pic(msg) + await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) + else: + await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await fusion_help.finish() + + +@fusion.handle(parameterless=[Cooldown(at_sender=False)]) +async def fusion_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): + bot, send_group_id = await assign_bot(bot=bot, event=event) + isUser, user_info, msg = await check_user(event) + if not isUser: + await handle_send(bot, event, send_group_id, msg) + await fusion.finish() + + user_id = user_info['user_id'] + back_msg = await XiuxianDataManager().get_back_msg(user_id) + if back_msg is None: + msg = "道友的背包空空如也!" + await handle_send(bot, event, send_group_id, msg) + await fusion.finish() + + args_str = args.extract_plain_text().strip() + equipment_id, equipment = items.get_data_by_item_name(args_str) + if equipment is None: + msg = f"未找到可合成的物品:{args_str}" + await handle_send(bot, event, send_group_id, msg) + await fusion.finish() + + fusion_info = equipment.get('fusion', None) + if not fusion_info: + msg = f"{equipment['name']} 不是一件可以合成的物品!" + await handle_send(bot, event, send_group_id, msg) + await fusion.finish() + + limit = fusion_info.get('limit', None) + if limit is not None: + current_amount = 0 + for back in back_msg: + if back['goods_id'] == int(equipment_id): + current_amount = back['goods_num'] + break + if current_amount >= limit: + msg = f"道友的背包中已有足够数量的 {equipment['name']},无法再次合成!" + await handle_send(bot, event, send_group_id, msg) + await fusion.finish() + + required_rank = fusion_info.get('need_rank', '江湖好手') + if convert_rank(user_info['level'])[0] > convert_rank(required_rank)[0]: + msg = f"道友的境界不足,合成 {equipment['name']} 需要达到 {required_rank}!" + await handle_send(bot, event, send_group_id, msg) + await fusion.finish() + + if user_info['exp'] < int(fusion_info.get('need_exp', 0)): + msg = f"道友的修为不足,合成 {equipment['name']} 需要修为 {int(fusion_info.get('need_exp', 0))}!" + await handle_send(bot, event, send_group_id, msg) + await fusion.finish() + + if user_info['stone'] < int(fusion_info.get('need_stone', 0)): + msg = f"道友的灵石不足,合成 {equipment['name']} 需要 {number_to(int(fusion_info.get('need_stone', 0)))} 枚灵石呢!" + await handle_send(bot, event, send_group_id, msg) + await fusion.finish() + + needed_items = fusion_info.get('need_item', {}) + missing_items = [] + for item_id, amount_needed in needed_items.items(): + total_amount = 0 + for back in back_msg: + if back['goods_id'] == int(item_id): + total_amount += back['goods_num'] + if total_amount < amount_needed: + missing_items.append((item_id, amount_needed - total_amount)) + + if missing_items: + missing_names = [f"{amount_needed} 个 {items.get_data_by_item_id(int(item_id))['name']}" for item_id, amount_needed in missing_items] + msg = "道友还缺少:\n" + "\n".join(missing_names) + await handle_send(bot, event, send_group_id, msg) + await fusion.finish() + + await XiuxianDataManager().update_ls(user_id, int(fusion_info.get('need_stone', 0)), 1) # 扣灵石 + for item_id, amount_needed in needed_items.items(): + await XiuxianDataManager().update_back_j(user_id, int(item_id), amount_needed) # 扣道具 + + await XiuxianDataManager().send_back(user_id, int(equipment_id), equipment['name'], equipment['type'], 1, 1) + + item_type = equipment.get('type', '物品') + msg = f"道友成功合成了{item_type}: {equipment['name']}!!" + await handle_send(bot, event, send_group_id, msg) + await fusion.finish() + + +@available_fusion.handle(parameterless=[Cooldown(at_sender=False)]) +async def available_fusion_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): + bot, send_group_id = await assign_bot(bot=bot, event=event) + args_str = args.extract_plain_text().strip() + + if args_str: + equipment_id, equipment = items.get_data_by_item_name(args_str) + if equipment and 'fusion' in equipment: + msg = get_item_msg(int(equipment_id)) + else: + msg = f"未找到可合成的物品:{args_str}" + else: + fusion_items = items.get_fusion_items() + if not fusion_items: + msg = "目前没有可合成的物品。" + else: + msg = "可合成的物品如下:\n" + "\n".join(fusion_items) + + await handle_send(bot, event, send_group_id, msg) + await available_fusion.finish() diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart/__init__.py index 862b754c..6989b71c 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart/__init__.py @@ -11,19 +11,16 @@ MessageSegment, ) from nonebot.params import CommandArg - -from .. import NICKNAME from ..xiuxian_config import XiuConfig from ..xiuxian_utils.lay_out import Cooldown, assign_bot from ..xiuxian_utils.utils import ( CommandObjectID, - append_draw_card_node, check_user, - get_msg_pic, handle_send, send_msg_handler, + build_forward_msg_list, ) -from ..xiuxian_utils.xiuxian2_handle import XIUXIAN_IMPART_BUFF +from ..xiuxian_utils.xiuxian2_handle import XiuxianDataManager from .impart_data import impart_data_json from .impart_uitls import ( get_image_representation, @@ -31,12 +28,9 @@ img_path, impart_check, re_impart_data, - update_user_impart_data, + build_draw_images ) -xiuxian_impart = XIUXIAN_IMPART_BUFF() - - cache_help = {} time_img = [ @@ -70,7 +64,7 @@ impart_img = on_command( "传承卡图", aliases={"传承卡片"}, priority=50, permission=GROUP, block=True ) -__impart_help__ = f""" +__impart_help__ = """ 传承帮助信息: 指令: 1、传承抽卡:花费10颗思恋结晶获取一次传承卡片(抽到的卡片被动加成) @@ -104,14 +98,7 @@ async def impart_help_( await impart_help.finish() else: msg = __impart_help__ - if XiuConfig().img: - pic = await get_msg_pic(msg) - cache_help[session_id] = pic - await bot.send_group_msg( - group_id=int(send_group_id), message=MessageSegment.image(pic) - ) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await impart_help.finish() @@ -120,21 +107,23 @@ async def impart_img_(bot: Bot, event: GroupMessageEvent, args: Message = Comman """传承卡图""" bot, send_group_id = await assign_bot(bot=bot, event=event) img_name = args.extract_plain_text().strip() - img = img_path / str(img_name + ".webp") + isUser, user_info, msg = await check_user(event) + if not isUser: + await handle_send(bot, event, send_group_id, msg) + await impart_img.finish() + img = img_path / f"{img_name}.webp" if not os.path.exists(img): msg = "没有找到此卡图!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg( - group_id=int(send_group_id), message=MessageSegment.image(pic) - ) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await impart_img.finish() else: - await bot.send_group_msg( - group_id=int(send_group_id), message=MessageSegment.image(img) - ) + try: + await bot.send_group_msg( + group_id=int(send_group_id), message=MessageSegment.image(file=f"file:///{str(img)}") + ) + except Exception as e: + msg = f"发送图片失败:{str(e)}" + await handle_send(bot, event, send_group_id, msg) await impart_img.finish() @@ -142,101 +131,138 @@ async def impart_img_(bot: Bot, event: GroupMessageEvent, args: Message = Comman async def impart_draw_(bot: Bot, event: GroupMessageEvent): """传承抽卡""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - handle_send(bot, event, send_group_id, msg) - return + await handle_send(bot, event, send_group_id, msg) + await impart_draw.finish() - user_id = user_info["user_id"] + user_id = user_info['user_id'] impart_data_draw = await impart_check(user_id) if impart_data_draw is None: - await handle_send( - bot, event, send_group_id, "发生未知错误,多次尝试无果请找晓楠!" - ) - return - if impart_data_draw["stone_num"] < 10: - await handle_send(bot, event, send_group_id, "思恋结晶数量不足10个,无法抽卡!") - return - - summary = f"道友{user_info['user_name']}的传承抽卡" - if get_rank(user_id): - img_list = impart_data_json.data_all_keys() - reap_img = None - try: - reap_img = random.choice(img_list) - except: - await handle_send(bot, event, send_group_id, "请检查卡图数据完整!") - return - list_tp = [] - if impart_data_json.data_person_add(user_id, reap_img): - msg = "" - msg += f"检测到传承背包已经存在卡片{reap_img}\n" - msg += "已转化为2880分钟闭关时间\n" - msg += "累计共获得3540分钟闭关时间!" - msg += "抽卡10次结果如下\n" - append_draw_card_node(bot, list_tp, summary, msg) - - img = get_image_representation(reap_img) - append_draw_card_node(bot, list_tp, summary, img) - - random.shuffle(time_img) - for x in time_img[:9]: - img = get_image_representation(x) - append_draw_card_node(bot, list_tp, summary, img) - + msg = "发生未知错误,多次尝试无果请找晓楠!" + await handle_send(bot, event, send_group_id, msg) + await impart_draw.finish() + if impart_data_draw['impart_stone_quantity'] < 10: + msg = "思恋结晶数量不足10个,无法抽卡!" + await handle_send(bot, event, send_group_id, msg) + await impart_draw.finish() + else: + if await get_rank(user_id): + img_list = impart_data_json.data_all_keys() + reap_img = None try: - await send_msg_handler(bot, event, list_tp) - except ActionFailed: + reap_img = random.choice(img_list) + except ValueError: + msg = "请检查卡图数据完整!" await handle_send(bot, event, send_group_id, msg) - return - await update_user_impart_data(user_id, 3540) - # 更新传承数据 - await re_impart_data(user_id) - return + await impart_draw.finish() + + summary = f"道友{user_info['user_name']}的传承抽卡" + + if impart_data_json.data_person_add(user_id, reap_img): + # 抽到重复卡 + msg = f"检测到传承背包已经存在卡片{reap_img}\n" + msg += "已转化为2880分钟闭关时间\n" + msg += "累计共获得3540分钟闭关时间!\n" + msg += "抽卡10次结果如下" + + images = await build_draw_images(time_img, reap_img) + + # 构建图片发送参数 + image_params = { + "use_merge_forward_send": XiuConfig().merge_forward_send, + "img_path": img_path, + "img_format": "png" + } + + # 构建转发消息 + list_tp = build_forward_msg_list(bot, summary, msg, images, image_params) + + # 抽到重复卡,抽数归零,加3540分钟闭关时间 + await XiuxianDataManager().add_impart_exp_day(3540, user_id) + await XiuxianDataManager().update_stone_num(10, user_id, 1) + await XiuxianDataManager().update_impart_wish(0, user_id) + # 更新传承数据 + await re_impart_data(user_id) + + try: + await send_msg_handler(bot, event, list_tp) + except ActionFailed: + msg = "未知原因,抽卡失败!" + await handle_send(bot, event, send_group_id, msg) + await impart_draw.finish() + + await impart_draw.finish() + else: + # 抽到新卡 + msg = "累计共获得660分钟闭关时间!\n" + msg += f"抽卡10次结果如下,获得新的传承卡片{reap_img}" + + images = await build_draw_images(time_img, reap_img) + + # 构建图片发送参数 + image_params = { + "use_merge_forward_send": XiuConfig().merge_forward_send, + "img_path": img_path, + "img_format": "png" + } + + # 构建转发消息 + list_tp = build_forward_msg_list(bot, summary, msg, images, image_params) + + # 抽到新卡,抽数归零 + await XiuxianDataManager().add_impart_exp_day(660, user_id) + await XiuxianDataManager().update_stone_num(10, user_id, 1) + await XiuxianDataManager().update_impart_wish(0, user_id) + # 更新传承数据 + await re_impart_data(user_id) + + try: + await send_msg_handler(bot, event, list_tp) + except ActionFailed: + msg = "未知原因,抽卡失败!" + await handle_send(bot, event, send_group_id, msg) + await impart_draw.finish() + + await impart_draw.finish() else: - msg = "" - msg += "累计共获得660分钟闭关时间!" - msg += f"抽卡10次结果如下,获得新的传承卡片{reap_img}\n" - append_draw_card_node(bot, list_tp, summary, msg) - - img = get_image_representation(reap_img) - append_draw_card_node(bot, list_tp, summary, msg) - + # 没有抽到新卡 + summary = f"道友{user_info['user_name']}的传承抽卡" + msg = "累计共获得660分钟闭关时间!\n" + msg += "抽卡10次结果如下!" + + # 准备图片列表 random.shuffle(time_img) - for x in time_img[:9]: - img = get_image_representation(x) - append_draw_card_node(bot, list_tp, summary, img) - + + # 构建图片发送参数 + image_params = { + "use_merge_forward_send": XiuConfig().merge_forward_send, + "img_path": img_path, + "img_format": "png" + } + + # 构建转发消息 + list_tp = build_forward_msg_list(bot, summary, msg, time_img, image_params) + + # 没抽到新卡,只加660分钟 + await XiuxianDataManager().add_impart_exp_day(660, user_id) + await XiuxianDataManager().update_stone_num(10, user_id, 1) + await XiuxianDataManager().add_impart_wish(10, user_id) + # 更新传承数据 + await re_impart_data(user_id) + try: await send_msg_handler(bot, event, list_tp) except ActionFailed: - await handle_send(bot, event, send_group_id, msg) - return - await update_user_impart_data(user_id, 660) - return - else: - list_tp = [] - msg = "" - msg += "累计共获得660分钟闭关时间!" - msg += "抽卡10次结果如下!\n" - append_draw_card_node(bot, list_tp, summary, msg) - random.shuffle(time_img) - for x in time_img: - img = get_image_representation(x) - append_draw_card_node(bot, list_tp, summary, img) - try: - await send_msg_handler(bot, event, list_tp) - except ActionFailed: - await handle_send(bot, event, send_group_id, msg) - return - await update_user_impart_data(user_id, 660) + await handle_send(bot, event, send_group_id, "未知原因,抽卡失败!") + await impart_draw.finish() @impart_back.handle(parameterless=[Cooldown(at_sender=False)]) async def impart_back_(bot: Bot, event: GroupMessageEvent): """传承背包""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: await handle_send(bot, event, send_group_id, msg) return @@ -249,36 +275,41 @@ async def impart_back_(bot: Bot, event: GroupMessageEvent): ) return - list_tp = [] - img = None name = user_info["user_name"] - txt_back = f"""--道友{name}的传承物资-- -思恋结晶:{impart_data_draw["stone_num"]}颗 -抽卡次数:{impart_data_draw["wish"]}/90次 -累计闭关时间:{impart_data_draw["exp_day"]}分钟 -""" - txt_tp = f"""--道友{name}的传承总属性-- -攻击提升:{int(impart_data_draw["impart_atk_per"] * 100)}% -气血提升:{int(impart_data_draw["impart_hp_per"] * 100)}% -真元提升:{int(impart_data_draw["impart_mp_per"] * 100)}% -会心提升:{int(impart_data_draw["impart_know_per"] * 100)}% -会心伤害提升:{int(impart_data_draw["impart_burst_per"] * 100)}% -闭关经验提升:{int(impart_data_draw["impart_exp_up"] * 100)}% -炼丹收获数量提升:{impart_data_draw["impart_mix_per"]}颗 -灵田收取数量提升:{impart_data_draw["impart_reap_per"]}颗 -每日双修次数提升:{impart_data_draw["impart_two_exp"]}次 -boss战攻击提升:{int(impart_data_draw["boss_atk"] * 100)}% -道友拥有的传承卡片如下: -""" summary = f"道友{name}的传承背包" - append_draw_card_node(bot, list_tp, summary, txt_back) - append_draw_card_node(bot, list_tp, summary, txt_tp) - + + # 组合要显示的文本信息 + msg_text = """--道友{name}的传承物资-- +思恋结晶:{impart_data_draw["impart_stone_quantity"]}颗 +抽卡次数:{impart_data_draw["impart_wish_quantity"]}/90次 +累计闭关时间:{impart_data_draw["impart_exp_day_quantity"]}分钟 + +--道友{name}的传承总属性-- +攻击提升:{int(impart_data_draw["impart_atk_addition"] * 100)}% +气血提升:{int(impart_data_draw["impart_hp_addition"] * 100)}% +真元提升:{int(impart_data_draw["impart_mp_addition"] * 100)}% +会心提升:{int(impart_data_draw["impart_crit_addition"] * 100)}% +会心伤害提升:{int(impart_data_draw["impart_crit_dmg_addition"] * 100)}% +闭关经验提升:{int(impart_data_draw["impart_exp_addition"] * 100)}% +炼丹收获数量提升:{impart_data_draw["impart_mix_addition"]}颗 +灵田收取数量提升:{impart_data_draw["impart_reap_addition"]}颗 +每日双修次数提升:{impart_data_draw["impart_two_exp_quantity"]}次 +boss战攻击提升:{int(impart_data_draw["impart_boss_atk_addition"] * 100)}% +道友拥有的传承卡片如下:""" + + # 获取用户的卡片列表 img_tp = impart_data_json.data_person_list(user_id) - - for x in range(len(img_tp)): - img = get_image_representation(img_tp[x]) - append_draw_card_node(bot, list_tp, summary, img) + + # 构建图片发送参数 + image_params = { + "use_merge_forward_send": XiuConfig().merge_forward_send, + "img_path": img_path, + "img_format": "png", + "get_image_func": get_image_representation + } + + # 构建转发消息 + list_tp = build_forward_msg_list(bot, summary, msg_text, img_tp, image_params) try: await send_msg_handler(bot, event, list_tp) @@ -290,7 +321,7 @@ async def impart_back_(bot: Bot, event: GroupMessageEvent): async def re_impart_load_(bot: Bot, event: GroupMessageEvent): """加载传承数据""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: await handle_send(bot, event, send_group_id, msg) return @@ -315,7 +346,7 @@ async def re_impart_load_(bot: Bot, event: GroupMessageEvent): async def impart_info_(bot: Bot, event: GroupMessageEvent): """传承信息""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: await handle_send(bot, event, send_group_id, msg) return @@ -327,9 +358,9 @@ async def impart_info_(bot: Bot, event: GroupMessageEvent): ) return - msg = f"""--道友{user_info["user_name"]}的传承物资-- -思恋结晶:{impart_data_draw["stone_num"]}颗 -抽卡次数:{impart_data_draw["wish"]}/90次 -累计闭关时间:{impart_data_draw["exp_day"]}分钟 + msg = """--道友{user_info["user_name"]}的传承物资-- +思恋结晶:{impart_data_draw["impart_stone_quantity"]}颗 +抽卡次数:{impart_data_draw["impart_wish_quantity"]}/90次 +累计闭关时间:{impart_data_draw["impart_exp_day_quantity"]}分钟 """ await handle_send(bot, event, send_group_id, msg) diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart/impart_all.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart/impart_all.py index 9504f223..54cb9221 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart/impart_all.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart/impart_all.py @@ -1,532 +1,532 @@ impart_all = { "白玫瑰": { "id": 1, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.1 }, "白日菊": { "id": 2, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.1 }, "百合": { "id": 3, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.1 }, "百慕达奶油": { "id": 4, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.1 }, "波斯菊": { "id": 5, - "type": "impart_two_exp", + "type": "impart_two_exp_quantity", "vale": 1 }, "彩叶草": { "id": 6, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.1 }, "翠菊": { "id": 7, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.1 }, "大理": { "id": 8, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.1 }, "大岩酮": { "id": 9, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.1 }, "丁香": { "id": 10, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.1 }, "粉红蔷薇": { "id": 11, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.1 }, "粉蔷薇": { "id": 12, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.1 }, "风铃草": { "id": 13, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.1 }, "风信子": { "id": 14, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.1 }, "凤梨": { "id": 15, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.1 }, "芙蓉": { "id": 16, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.1 }, "海宇": { "id": 17, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.1 }, "红玫瑰": { "id": 18, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.1 }, "红蔷薇": { "id": 19, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.1 }, "红掌": { "id": 20, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.1 }, "蝴蝶兰": { "id": 21, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.1 }, "黄菊": { "id": 24, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.1 }, "黄玫瑰": { "id": 25, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.1 }, "黄蔷薇": { "id": 26, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.1 }, "火百合": { "id": 27, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.1 }, "金达莱": { "id": 28, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.1 }, "金凤": { "id": 29, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.1 }, "金鱼草": { "id": 30, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.1 }, "菊": { "id": 31, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.1 }, "卡萨布兰卡": { "id": 32, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.1 }, "蓝蔷薇": { "id": 33, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.1 }, "连翘": { "id": 34, - "type": "impart_exp_up", + "type": "impart_exp_addition", "vale": 0.05 }, "莲": { "id": 35, - "type": "impart_exp_up", + "type": "impart_exp_addition", "vale": 0.05 }, "铃兰": { "id": 36, - "type": "impart_exp_up", + "type": "impart_exp_addition", "vale": 0.05 }, "龙胆": { "id": 37, - "type": "impart_exp_up", + "type": "impart_exp_addition", "vale": 0.05 }, "麦秆菊": { "id": 38, - "type": "impart_exp_up", + "type": "impart_exp_addition", "vale": 0.05 }, "迷迭香": { "id": 39, - "type": "impart_exp_up", + "type": "impart_exp_addition", "vale": 0.05 }, "密蒙": { "id": 40, - "type": "impart_two_exp", + "type": "impart_two_exp_quantity", "vale": 1 }, "牡丹": { "id": 41, - "type": "impart_exp_up", + "type": "impart_exp_addition", "vale": 0.05 }, "木棉": { "id": 42, - "type": "impart_exp_up", + "type": "impart_exp_addition", "vale": 0.05 }, "蒲公英": { "id": 43, - "type": "impart_exp_up", + "type": "impart_exp_addition", "vale": 0.05 }, "三色堇": { "id": 44, - "type": "impart_exp_up", + "type": "impart_exp_addition", "vale": 0.05 }, "山茶": { "id": 45, - "type": "boss_atk", + "type": "impart_boss_atk_addition", "vale": 0.05 }, "山樱": { "id": 46, - "type": "boss_atk", + "type": "impart_boss_atk_addition", "vale": 0.05 }, "芍药": { "id": 47, - "type": "boss_atk", + "type": "impart_boss_atk_addition", "vale": 0.05 }, "蓍草": { "id": 48, - "type": "impart_two_exp", + "type": "impart_two_exp_quantity", "vale": 1 }, "时钟": { "id": 49, - "type": "boss_atk", + "type": "impart_boss_atk_addition", "vale": 0.05 }, "矢车菊": { "id": 50, - "type": "boss_atk", + "type": "impart_boss_atk_addition", "vale": 0.05 }, "水仙": { "id": 51, - "type": "boss_atk", + "type": "impart_boss_atk_addition", "vale": 0.05 }, "松虫草": { "id": 52, - "type": "boss_atk", + "type": "impart_boss_atk_addition", "vale": 0.05 }, "天竺葵": { "id": 53, - "type": "boss_atk", + "type": "impart_boss_atk_addition", "vale": 0.05 }, "仙客": { "id": 54, - "type": "boss_atk", + "type": "impart_boss_atk_addition", "vale": 0.05 }, "香水百合": { "id": 55, - "type": "boss_atk", + "type": "impart_boss_atk_addition", "vale": 0.05 }, "向日葵": { "id": 56, - "type": "impart_know_per", + "type": "impart_crit_addition", "vale": 0.05 }, "小苍兰": { "id": 57, - "type": "impart_know_per", + "type": "impart_crit_addition", "vale": 0.05 }, "雪莲": { "id": 58, - "type": "impart_know_per", + "type": "impart_crit_addition", "vale": 0.05 }, "荀麻": { "id": 59, - "type": "impart_know_per", + "type": "impart_crit_addition", "vale": 0.05 }, "野蔷薇": { "id": 60, - "type": "impart_burst_per", + "type": "impart_crit_dmg_addition", "vale": 0.1 }, "樱": { "id": 61, - "type": "impart_two_exp", + "type": "impart_two_exp_quantity", "vale": 1 }, "油桐": { "id": 62, - "type": "impart_burst_per", + "type": "impart_crit_dmg_addition", "vale": 0.1 }, "玉簪": { "id": 63, - "type": "impart_two_exp", + "type": "impart_two_exp_quantity", "vale": 1 }, "郁金香": { "id": 64, - "type": "impart_burst_per", + "type": "impart_crit_dmg_addition", "vale": 0.1 }, "鸢尾": { "id": 65, - "type": "impart_burst_per", + "type": "impart_crit_dmg_addition", "vale": 0.1 }, "紫罗兰": { "id": 66, - "type": "impart_burst_per", + "type": "impart_crit_dmg_addition", "vale": 0.1 }, "紫玫瑰": { "id": 67, - "type": "impart_mix_per", + "type": "impart_mix_addition", "vale": 1 }, "画屏春-暗香": { "id": 68, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.07 }, "画屏春-采桑": { "id": 69, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.07 }, "画屏春-葱茏": { "id": 70, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.07 }, "画屏春-风息": { "id": 71, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.07 }, "画屏春-风信": { "id": 72, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.07 }, "画屏春-风语": { "id": 73, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.07 }, "画屏春-眷念": { "id": 74, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.07 }, "画屏春-兰舟": { "id": 75, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.07 }, "画屏春-赛金": { "id": 76, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.07 }, "画屏春-似霞": { "id": 77, - "type": "impart_atk_per", + "type": "impart_atk_addition", "vale": 0.07 }, "画屏春-瑰丽": { "id": 78, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.07 }, "画屏春-国香": { "id": 79, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.07 }, "画屏春-花蕊": { "id": 80, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.07 }, "画屏春-回眸": { "id": 81, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.07 }, "画屏春-解红": { "id": 82, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.07 }, "画屏春-踏樱": { "id": 83, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.07 }, "画屏春-啼鹃": { "id": 84, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.07 }, "画屏春-樱浮": { "id": 85, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.07 }, "画屏春-樱柔": { "id": 86, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.07 }, "画屏春-早樱": { "id": 87, - "type": "impart_hp_per", + "type": "impart_hp_addition", "vale": 0.07 }, "画屏春-春水": { "id": 88, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.07 }, "画屏春-繁星": { "id": 89, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.07 }, "画屏春-佳色": { "id": 90, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.07 }, "画屏春-灵动": { "id": 91, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.07 }, "画屏春-倾杯": { "id": 92, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.07 }, "画屏春-秋霁": { "id": 93, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.07 }, "画屏春-时令": { "id": 94, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.07 }, "画屏春-无暇": { "id": 95, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.07 }, "画屏春-瑶花": { "id": 96, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.07 }, "画屏春-荧惑": { "id": 97, - "type": "impart_mp_per", + "type": "impart_mp_addition", "vale": 0.07 }, "画屏春-苍翠": { "id": 98, - "type": "impart_reap_per", + "type": "impart_reap_addition", "vale": 1 }, "画屏春-沉沦": { "id": 99, - "type": "impart_reap_per", + "type": "impart_reap_addition", "vale": 1 }, "画屏春-春晴": { "id": 100, - "type": "impart_reap_per", + "type": "impart_reap_addition", "vale": 1 }, "画屏春-蝶桂": { "id": 101, - "type": "impart_reap_per", + "type": "impart_reap_addition", "vale": 1 }, "画屏春-缚灵": { "id": 102, - "type": "impart_reap_per", + "type": "impart_reap_addition", "vale": 1 }, "画屏春-佳人": { "id": 103, - "type": "impart_reap_per", + "type": "impart_reap_addition", "vale": 1 }, "画屏春-晶莹": { "id": 104, - "type": "impart_reap_per", + "type": "impart_reap_addition", "vale": 1 }, "画屏春-生息": { "id": 105, - "type": "impart_reap_per", + "type": "impart_reap_addition", "vale": 1 }, "画屏春-雨润": { "id": 106, - "type": "impart_reap_per", + "type": "impart_reap_addition", "vale": 1 }, "画屏春-早春": { "id": 107, - "type": "impart_reap_per", + "type": "impart_reap_addition", "vale": 1 }, "紫云英": { "id": 108, - "type": "impart_reap_per", + "type": "impart_reap_addition", "vale": 1 } } diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart/impart_data.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart/impart_data.py index 47f266a0..7b68ae11 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart/impart_data.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart/impart_data.py @@ -22,7 +22,7 @@ def __init__(self): try: with open(self.data_path_person, 'r', encoding='utf-8') as f: self.data_person = json.load(f) - except: + except ValueError: self.info = {} data = json.dumps(self.info, ensure_ascii=False, indent=4) with open(self.data_path_person, mode="x", encoding="UTF-8") as f: @@ -39,7 +39,7 @@ def __init__(self): pass else: logger.opt(colors=True).info("传承数据有未知类型错误!请检查!") - except: + except ValueError: pass self.__save() @@ -87,7 +87,7 @@ def data_person_list(self, user_id): try: list_data_person_list = self.data_person[user_id] return list_data_person_list - except: + except (ValueError, KeyError, FileNotFoundError): return list_data_person_list def data_all_keys(self): diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart/impart_uitls.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart/impart_uitls.py index 7e864371..73bed716 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart/impart_uitls.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart/impart_uitls.py @@ -1,16 +1,16 @@ import os +import asyncio from pathlib import Path - import numpy +import random from nonebot.adapters.onebot.v11 import ( MessageSegment, ) from ..xiuxian_config import XiuConfig -from ..xiuxian_utils.xiuxian2_handle import XIUXIAN_IMPART_BUFF +from ..xiuxian_utils.xiuxian2_handle import XiuxianDataManager from .impart_data import impart_data_json -xiuxian_impart = XIUXIAN_IMPART_BUFF() img_path = Path() / os.getcwd() / "data" / "xiuxian" / "卡图" @@ -29,10 +29,10 @@ def character_probability(count): return ret -def get_rank(user_id): - impart_data = xiuxian_impart.get_user_impart_info_with_id(user_id) +async def get_rank(user_id): + impart_data = await XiuxianDataManager().get_user_impart_info_with_id(user_id) value = random_int() - num = int(impart_data["wish"]) + num = int(impart_data["impart_wish_quantity"]) for x in range(num, num + 10): index_5 = character_probability(x) if value <= index_5: @@ -44,11 +44,20 @@ def get_rank(user_id): async def impart_check(user_id): impart_data_json.find_user_impart(user_id) - if xiuxian_impart.get_user_impart_info_with_id(user_id) is None: - xiuxian_impart._create_user(user_id) - return xiuxian_impart.get_user_impart_info_with_id(user_id) + if await XiuxianDataManager().get_user_impart_info_with_id(user_id) is None: + await XiuxianDataManager()._create_user(user_id) + return await XiuxianDataManager().get_user_impart_info_with_id(user_id) else: - return xiuxian_impart.get_user_impart_info_with_id(user_id) + return await XiuxianDataManager().get_user_impart_info_with_id(user_id) + + + + +async def build_draw_images(time_imgs, special_card): + imgs = time_imgs[:10] + random.shuffle(imgs) + imgs[random.randint(0, 9)] = special_card + return imgs async def re_impart_data(user_id): @@ -57,49 +66,52 @@ async def re_impart_data(user_id): return False else: all_data = impart_data_json.data_all_() - impart_two_exp = 0 - impart_exp_up = 0 - impart_atk_per = 0 - impart_hp_per = 0 - impart_mp_per = 0 - boss_atk = 0 - impart_know_per = 0 - impart_burst_per = 0 - impart_mix_per = 0 - impart_reap_per = 0 + impart_two_exp_quantity = 0 + impart_exp_addition = 0 + impart_atk_addition = 0 + impart_hp_addition = 0 + impart_mp_addition = 0 + impart_boss_atk_addition = 0 + impart_crit_addition = 0 + impart_crit_dmg_addition = 0 + impart_mix_addition = 0 + impart_reap_addition = 0 for x in list_tp: - if all_data[x]["type"] == "impart_two_exp": - impart_two_exp = impart_two_exp + all_data[x]["vale"] - elif all_data[x]["type"] == "impart_exp_up": - impart_exp_up = impart_exp_up + all_data[x]["vale"] - elif all_data[x]["type"] == "impart_atk_per": - impart_atk_per = impart_atk_per + all_data[x]["vale"] - elif all_data[x]["type"] == "impart_hp_per": - impart_hp_per = impart_hp_per + all_data[x]["vale"] - elif all_data[x]["type"] == "impart_mp_per": - impart_mp_per = impart_mp_per + all_data[x]["vale"] - elif all_data[x]["type"] == "boss_atk": - boss_atk = boss_atk + all_data[x]["vale"] - elif all_data[x]["type"] == "impart_know_per": - impart_know_per = impart_know_per + all_data[x]["vale"] - elif all_data[x]["type"] == "impart_burst_per": - impart_burst_per = impart_burst_per + all_data[x]["vale"] - elif all_data[x]["type"] == "impart_mix_per": - impart_mix_per = impart_mix_per + all_data[x]["vale"] - elif all_data[x]["type"] == "impart_reap_per": - impart_reap_per = impart_reap_per + all_data[x]["vale"] + if all_data[x]["type"] == "impart_two_exp_quantity": + impart_two_exp_quantity = impart_two_exp_quantity + all_data[x]["vale"] + elif all_data[x]["type"] == "impart_exp_addition": + impart_exp_addition = impart_exp_addition + all_data[x]["vale"] + elif all_data[x]["type"] == "impart_atk_addition": + impart_atk_addition = impart_atk_addition + all_data[x]["vale"] + elif all_data[x]["type"] == "impart_hp_addition": + impart_hp_addition = impart_hp_addition + all_data[x]["vale"] + elif all_data[x]["type"] == "impart_mp_addition": + impart_mp_addition = impart_mp_addition + all_data[x]["vale"] + elif all_data[x]["type"] == "impart_boss_atk_addition": + impart_boss_atk_addition = impart_boss_atk_addition + all_data[x]["vale"] + elif all_data[x]["type"] == "impart_crit_addition": + impart_crit_addition = impart_crit_addition + all_data[x]["vale"] + elif all_data[x]["type"] == "impart_crit_dmg_addition": + impart_crit_dmg_addition = impart_crit_dmg_addition + all_data[x]["vale"] + elif all_data[x]["type"] == "impart_mix_addition": + impart_mix_addition = impart_mix_addition + all_data[x]["vale"] + elif all_data[x]["type"] == "impart_reap_addition": + impart_reap_addition = impart_reap_addition + all_data[x]["vale"] else: pass - xiuxian_impart.update_impart_two_exp(impart_two_exp, user_id) - xiuxian_impart.update_impart_exp_up(impart_exp_up, user_id) - xiuxian_impart.update_impart_atk_per(impart_atk_per, user_id) - xiuxian_impart.update_impart_hp_per(impart_hp_per, user_id) - xiuxian_impart.update_impart_mp_per(impart_mp_per, user_id) - xiuxian_impart.update_boss_atk(boss_atk, user_id) - xiuxian_impart.update_impart_know_per(impart_know_per, user_id) - xiuxian_impart.update_impart_burst_per(impart_burst_per, user_id) - xiuxian_impart.update_impart_mix_per(impart_mix_per, user_id) - xiuxian_impart.update_impart_reap_per(impart_reap_per, user_id) + + await asyncio.gather( + XiuxianDataManager().update_impart_two_exp(impart_two_exp_quantity, user_id), + XiuxianDataManager().update_impart_exp_up(impart_exp_addition, user_id), + XiuxianDataManager().update_impart_atk_per(impart_atk_addition, user_id), + XiuxianDataManager().update_impart_hp_per(impart_hp_addition, user_id), + XiuxianDataManager().update_impart_mp_per(impart_mp_addition, user_id), + XiuxianDataManager().update_boss_atk(impart_boss_atk_addition, user_id), + XiuxianDataManager().update_impart_know_per(impart_crit_addition, user_id), + XiuxianDataManager().update_impart_burst_per(impart_crit_dmg_addition, user_id), + XiuxianDataManager().update_impart_mix_per(impart_mix_addition, user_id), + XiuxianDataManager().update_impart_reap_per(impart_reap_addition, user_id) + ) return True @@ -110,9 +122,9 @@ async def update_user_impart_data(user_id, time: int): user_id: 用户QQ号 time: 传承时间 """ - xiuxian_impart.add_impart_exp_day(time, user_id) - xiuxian_impart.update_stone_num(10, user_id, 2) - xiuxian_impart.update_impart_wish(0, user_id) + await XiuxianDataManager().add_impart_exp_day(time, user_id) + await XiuxianDataManager().update_stone_num(10, user_id, 1) + await XiuxianDataManager().update_impart_wish(0, user_id) # 更新传承数据 await re_impart_data(user_id) diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart_pk/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart_pk/__init__.py index a0d1f5e6..bb48acc2 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart_pk/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart_pk/__init__.py @@ -5,22 +5,19 @@ GROUP, Message, GroupMessageEvent, - MessageSegment, ActionFailed ) from ..xiuxian_utils.lay_out import assign_bot, Cooldown from ..xiuxian_utils.data_source import jsondata from nonebot.log import logger -from ..xiuxian_utils.utils import check_user, get_msg_pic, send_msg_handler -from .impart_pk_uitls import impart_pk_check +from ..xiuxian_utils.utils import check_user, send_msg_handler, handle_send +from .impart_pk_uitls import impart_pk_check, impart_pk_now_msg_to_bot, impart_pk_now_msg from .xu_world import xu_world from .impart_pk import impart_pk from ..xiuxian_config import XiuConfig -from ..xiuxian_utils.xiuxian2_handle import XiuxianDateManage, OtherSet, UserBuffDate, XIUXIAN_IMPART_BUFF +from ..xiuxian_utils.xiuxian2_handle import XiuxianDataManager, OtherSet, UserBuffData from .. import NICKNAME -xiuxian_impart = XIUXIAN_IMPART_BUFF() -sql_message = XiuxianDateManage() # sql类 impart_re = require("nonebot_plugin_apscheduler").scheduler @@ -35,46 +32,30 @@ async def impart_re_(): impart_pk.re_data() xu_world.re_data() - logger.opt(colors=True).info(f"已重置虚神界次数") + logger.opt(colors=True).info("已重置虚神界次数") @impart_pk_project.handle(parameterless=[Cooldown(stamina_cost = 1, at_sender=False)]) async def impart_pk_project_(bot: Bot, event: GroupMessageEvent): """投影虚神界""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await impart_pk_project.finish() user_id = user_info['user_id'] impart_data_draw = await impart_pk_check(user_id) if impart_data_draw is None: - msg = f"发生未知错误,多次尝试无果请找晓楠!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "发生未知错误,多次尝试无果请找晓楠!" + await handle_send(bot, event, send_group_id, msg) await impart_pk_project.finish() # 加入虚神界 if impart_pk.find_user_data(user_id)["pk_num"] <= 0: - msg = f"道友今日次数已用尽,无法在加入虚神界!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友今日次数已用尽,无法在加入虚神界!" + await handle_send(bot, event, send_group_id, msg) await impart_pk_project.finish() msg = xu_world.add_xu_world(user_id) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await impart_pk_project.finish() @@ -82,32 +63,20 @@ async def impart_pk_project_(bot: Bot, event: GroupMessageEvent): async def impart_pk_list_(bot: Bot, event: GroupMessageEvent): """虚神界列表""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await impart_pk_list.finish() user_id = user_info['user_id'] impart_data_draw = await impart_pk_check(user_id) if impart_data_draw is None: - msg = f"发生未知错误,多次尝试无果请找晓楠!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "发生未知错误,多次尝试无果请找晓楠!" + await handle_send(bot, event, send_group_id, msg) await impart_pk_list.finish() xu_list = xu_world.all_xu_world_user() if len(xu_list) == 0: - msg = f"虚神界里还没有投影呢,快来输入【投影虚神界】加入分身吧!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "虚神界里还没有投影呢,快来输入【投影虚神界】加入分身吧!" + await handle_send(bot, event, send_group_id, msg) await impart_pk_list.finish() list_msg = [] win_num = "win_num" @@ -115,7 +84,7 @@ async def impart_pk_list_(bot: Bot, event: GroupMessageEvent): for x in range(len(xu_list)): user_data = impart_pk.find_user_data(xu_list[x]) if user_data: - name = sql_message.get_user_info_with_id(xu_list[x])['user_name'] + name = (await XiuxianDataManager().get_user_infos_by_ids(xu_list[x]))['user_name'] msg = "" msg += f"编号:{user_data['number']}\n" msg += f"道友:{name}\n" @@ -127,12 +96,8 @@ async def impart_pk_list_(bot: Bot, event: GroupMessageEvent): try: await send_msg_handler(bot, event, list_msg) except ActionFailed: - msg = f"未知原因,查看失败!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "未知原因,查看失败!" + await handle_send(bot, event, send_group_id, msg) await impart_pk_list.finish() await impart_pk_list.finish() @@ -141,36 +106,24 @@ async def impart_pk_list_(bot: Bot, event: GroupMessageEvent): async def impart_pk_now_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """虚神界对决""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await impart_pk_now.finish() user_id = user_info['user_id'] - sql_message.update_last_check_info_time(user_id) # 更新查看修仙信息时间 + await XiuxianDataManager().update_last_check_info_time(user_id) # 更新查看修仙信息时间 impart_data_draw = await impart_pk_check(user_id) if impart_data_draw is None: - msg = f"发生未知错误,多次尝试无果请找晓楠!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "发生未知错误,多次尝试无果请找晓楠!" + await handle_send(bot, event, send_group_id, msg) await impart_pk_now.finish() num = args.extract_plain_text().strip() user_data = impart_pk.find_user_data(user_info['user_id']) if user_data["pk_num"] <= 0: - msg = f"道友今日次数耗尽,每天再来吧!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友今日次数耗尽,每天再来吧!" + await handle_send(bot, event, send_group_id, msg) await impart_pk_now.finish() player_1_stones = 0 @@ -181,22 +134,22 @@ async def impart_pk_now_(bot: Bot, event: GroupMessageEvent, args: Message = Com if not num: while user_data["pk_num"] > 0: duel_count += 1 - msg, win = await impart_pk_uitls.impart_pk_now_msg_to_bot(user_info['user_name'], NICKNAME) + msg, win = await impart_pk_now_msg_to_bot(user_info['user_name'], NICKNAME) if win == 1: msg += f"战报:道友{user_info['user_name']}获胜,获得思恋结晶10颗\n" impart_pk.update_user_data(user_info['user_id'], True) - xiuxian_impart.update_stone_num(10, user_id, 1) + await XiuxianDataManager().update_stone_num(10, user_id, 0) player_1_stones += 10 elif win == 2: msg += f"战报:道友{user_info['user_name']}败了,消耗一次次数,获得思恋结晶5颗\n" impart_pk.update_user_data(user_info['user_id'], False) - xiuxian_impart.update_stone_num(5, user_id, 1) + await XiuxianDataManager().update_stone_num(5, user_id, 0) player_1_stones += 5 if impart_pk.find_user_data(user_id)["pk_num"] <= 0 and xu_world.check_xu_world_user_id(user_id) is True: msg += "检测到道友次数已用尽,已帮助道友退出虚神界!" xu_world.del_xu_world(user_id) else: - msg = f"挑战失败" + msg = "挑战失败" combined_msg += f"{msg}\n" break @@ -205,70 +158,54 @@ async def impart_pk_now_(bot: Bot, event: GroupMessageEvent, args: Message = Com combined_msg += f"总计:道友{user_info['user_name']}获得思恋结晶{player_1_stones}颗\n" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + combined_msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=combined_msg) + await handle_send(bot, event, send_group_id, combined_msg) await impart_pk_now.finish() if not num.isdigit(): - msg = f"编号解析异常,应全为数字!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "编号解析异常,应全为数字!" + await handle_send(bot, event, send_group_id, msg) await impart_pk_now.finish() num = int(num) - 1 xu_world_list = xu_world.all_xu_world_user() if num + 1 > len(xu_world_list) or num < 0: - msg = f"编号解析异常,虚神界没有此编号道友!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "编号解析异常,虚神界没有此编号道友!" + await handle_send(bot, event, send_group_id, msg) await impart_pk_now.finish() player_1 = user_info['user_id'] player_2 = xu_world_list[num] if str(player_1) == str(player_2): - msg = f"道友不能挑战自己的投影!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友不能挑战自己的投影!" + await handle_send(bot, event, send_group_id, msg) await impart_pk_now.finish() player_1_name = user_info['user_name'] - player_2_name = sql_message.get_user_info_with_id(player_2)['user_name'] + player_2_name = await XiuxianDataManager().get_user_infos_by_ids(player_2)['user_name'] while user_data["pk_num"] > 0: duel_count += 1 - msg_list, win = await impart_pk_uitls.impart_pk_now_msg(player_1, player_1_name, player_2, player_2_name) + msg_list, win = await impart_pk_now_msg(player_1, player_1_name, player_2, player_2_name) if win is None: - msg = f"挑战失败" + msg = "挑战失败" combined_msg += f"{msg}\n" break if win == 1: # 1号玩家胜利 发起者 impart_pk.update_user_data(player_1, True) impart_pk.update_user_data(player_2, False) - xiuxian_impart.update_stone_num(10, player_1, 1) - xiuxian_impart.update_stone_num(5, player_2, 1) + await XiuxianDataManager().update_stone_num(10, player_1, 0) + await XiuxianDataManager().update_stone_num(5, player_2, 0) player_1_stones += 10 player_2_stones += 5 msg_list.append( - {"type": "node", "data": {"name": f"虚神界战报", "uin": bot.self_id, + {"type": "node", "data": {"name": "虚神界战报", "uin": bot.self_id, "content": f"道友{player_1_name}获得了胜利,获得了思恋结晶10!\n" f"道友{player_2_name}获得败了,消耗一次次数,获得了思恋结晶5颗!"}}) if impart_pk.find_user_data(player_2)["pk_num"] <= 0: msg_list.append( - {"type": "node", "data": {"name": f"虚神界变更", "uin": bot.self_id, + {"type": "node", "data": {"name": "虚神界变更", "uin": bot.self_id, "content": f"道友{player_2_name}次数耗尽,离开了虚神界!"}}) xu_world.del_xu_world(player_2) combined_msg += "\n".join([node['data']['content'] for node in msg_list]) @@ -276,17 +213,17 @@ async def impart_pk_now_(bot: Bot, event: GroupMessageEvent, args: Message = Com elif win == 2: # 2号玩家胜利 被挑战者 impart_pk.update_user_data(player_2, True) impart_pk.update_user_data(player_1, False) - xiuxian_impart.update_stone_num(10, player_2, 1) - xiuxian_impart.update_stone_num(5, player_1, 1) + await XiuxianDataManager().update_stone_num(10, player_2, 0) + await XiuxianDataManager().update_stone_num(5, player_1, 0) player_2_stones += 10 player_1_stones += 5 msg_list.append( - {"type": "node", "data": {"name": f"虚神界战报", "uin": bot.self_id, + {"type": "node", "data": {"name": "虚神界战报", "uin": bot.self_id, "content": f"道友{player_2_name}获得了胜利,获得了思恋结晶10颗!\n" f"道友{player_1_name}获得败了,消耗一次次数,获得了思恋结晶5颗!"}}) if impart_pk.find_user_data(player_1)["pk_num"] <= 0: msg_list.append( - {"type": "node", "data": {"name": f"虚神界变更", "uin": bot.self_id, + {"type": "node", "data": {"name": "虚神界变更", "uin": bot.self_id, "content": f"道友{player_1_name}次数耗尽,离开了虚神界!"}}) xu_world.del_xu_world(player_1) combined_msg += "\n".join([node['data']['content'] for node in msg_list]) @@ -297,7 +234,7 @@ async def impart_pk_now_(bot: Bot, event: GroupMessageEvent, args: Message = Com try: await send_msg_handler(bot, event, msg_list) except ActionFailed: - msg = f"未知原因,对决显示失败!" + msg = "未知原因,对决显示失败!" combined_msg += f"{msg}\n" break @@ -305,11 +242,7 @@ async def impart_pk_now_(bot: Bot, event: GroupMessageEvent, args: Message = Com combined_msg += f"总计:道友{player_1_name}获得思恋结晶{player_1_stones}颗, 道友{player_2_name}获得思恋结晶{player_2_stones}颗\n" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + combined_msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=combined_msg) + await handle_send(bot, event, send_group_id, combined_msg) await impart_pk_now.finish() @@ -318,23 +251,15 @@ async def impart_pk_now_(bot: Bot, event: GroupMessageEvent, args: Message = Com async def impart_pk_exp_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """虚神界修炼""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await impart_pk_exp.finish() user_id = user_info['user_id'] impart_data_draw = await impart_pk_check(user_id) if impart_data_draw is None: - msg = f"发生未知错误,多次尝试无果请找晓楠!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "发生未知错误,多次尝试无果请找晓楠!" + await handle_send(bot, event, send_group_id, msg) await impart_pk_exp.finish() level = user_info['level'] hp_speed = 25 @@ -342,58 +267,38 @@ async def impart_pk_exp_(bot: Bot, event: GroupMessageEvent, args: Message = Com impaer_exp_time = args.extract_plain_text().strip() if not impaer_exp_time.isdigit(): - msg = f"输入解析异常,应全为数字!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "输入解析异常,应全为数字!" + await handle_send(bot, event, send_group_id, msg) await impart_pk_exp.finish() - if int(impaer_exp_time) > int(impart_data_draw['exp_day']): - msg = f"累计时间不足,修炼失败!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + if int(impaer_exp_time) > int(impart_data_draw['impart_exp_day_quantity']): + msg = "累计时间不足,修炼失败!" + await handle_send(bot, event, send_group_id, msg) await impart_pk_exp.finish() if user_info['root_type'] == '伪灵根': - msg = f"器师无法进行修炼!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "器师无法进行修炼!" + await handle_send(bot, event, send_group_id, msg) await impart_pk_exp.finish() # 闭关时长计算(分钟) - level_rate = sql_message.get_root_rate(user_info['root_type']) # 灵根倍率 + level_rate = await XiuxianDataManager().get_root_rate(user_info['root_type']) # 灵根倍率 realm_rate = jsondata.level_data()[level]["spend"] # 境界倍率 - user_buff_data = UserBuffDate(user_id) - mainbuffdata = user_buff_data.get_user_main_buff_data() - mainbuffratebuff = mainbuffdata['ratebuff'] if mainbuffdata is not None else 0 # 功法修炼倍率 - mainbuffcloexp = mainbuffdata['clo_exp'] if mainbuffdata != None else 0 # 功法闭关经验 - mainbuffclors = mainbuffdata['clo_rs'] if mainbuffdata != None else 0 # 功法闭关回复 + user_buff_data = UserBuffData(user_id) + mainbuffdata = await user_buff_data.get_user_main_buff_data() + mainbuffratebuff = mainbuffdata['ratebuf'] if mainbuffdata is not None else 0 # 功法修炼倍率 + mainbuffcloexp = mainbuffdata['clo_exp'] if mainbuffdata is not None else 0 # 功法闭关经验 + mainbuffclors = mainbuffdata['clo_rs'] if mainbuffdata is not None else 0 # 功法闭关回复 exp = int((int(impaer_exp_time) * XiuConfig().closing_exp) * ((level_rate * realm_rate * (1 + mainbuffratebuff) * (1 + mainbuffcloexp)))) # 本次闭关获取的修为 - max_exp = int((int(OtherSet().set_closing_type(user_info['level'])) * XiuConfig().closing_exp_upper_limit)) # 获取下个境界需要的修为 * 1.5为闭关上限 + max_exp = int((int(await OtherSet().set_closing_type(user_info['level'])) * XiuConfig().closing_exp_upper_limit)) # 获取下个境界需要的修为 * 1.5为闭关上限 if 0 < int(user_info['exp'] + exp) < max_exp: - xiuxian_impart.use_impart_exp_day(impaer_exp_time, user_id) - sql_message.update_exp(user_id, exp) - sql_message.update_power2(user_id) # 更新战力 - result_msg, result_hp_mp = OtherSet().send_hp_mp(user_id, int(exp * hp_speed * (1 + mainbuffclors)), int(exp * mp_speed)) - sql_message.update_user_attribute(user_id, result_hp_mp[0], result_hp_mp[1], int(result_hp_mp[2] / 10)) + await XiuxianDataManager().use_impart_exp_day(impaer_exp_time, user_id) + await XiuxianDataManager().update_exp(user_id, exp, 0) + await XiuxianDataManager().update_power2(user_id) # 更新战力 + result_msg, result_hp_mp = await OtherSet().send_hp_mp(user_id, int(exp * hp_speed * (1 + mainbuffclors)), int(exp * mp_speed)) + await XiuxianDataManager().update_user_attribute(user_id, result_hp_mp[0], result_hp_mp[1], int(result_hp_mp[2] / 10)) msg = f"虚神界修炼结束,共修炼{impaer_exp_time}分钟,本次闭关增加修为:{exp}{result_msg[0]}{result_msg[1]}" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await impart_pk_exp.finish() else: msg = f"修炼时长过长导致超出上限,此次修炼失败,最多可修炼{max(0, max_exp - int(user_info['exp'] + exp))}分钟" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await impart_pk_exp.finish() diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart_pk/impart_pk.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart_pk/impart_pk.py index ece3f3ae..55eb5b1b 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart_pk/impart_pk.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart_pk/impart_pk.py @@ -13,7 +13,7 @@ def __init__(self): try: with open(self.data_path, 'r', encoding='utf-8') as f: self.data = json.load(f) - except: + except FileNotFoundError: self.info = {} data = json.dumps(self.info, ensure_ascii=False, indent=4) with open(self.data_path, mode="x", encoding="UTF-8") as f: diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart_pk/impart_pk_uitls.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart_pk/impart_pk_uitls.py index 34687011..8f5df5ec 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart_pk/impart_pk_uitls.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart_pk/impart_pk_uitls.py @@ -1,9 +1,6 @@ from typing import List import random -from ..xiuxian_utils.xiuxian2_handle import XIUXIAN_IMPART_BUFF - -xiuxian_impart = XIUXIAN_IMPART_BUFF() - +from ..xiuxian_utils.xiuxian2_handle import XiuxianDataManager def random_bullet() -> List[int]: """ @@ -16,11 +13,11 @@ def random_bullet() -> List[int]: async def impart_pk_check(user_id): - if xiuxian_impart.get_user_impart_info_with_id(user_id) is None: - xiuxian_impart._create_user(user_id) - return xiuxian_impart.get_user_impart_info_with_id(user_id) + if await XiuxianDataManager().get_user_impart_info_with_id(user_id) is None: + await XiuxianDataManager().create_impart_user(user_id) + return await XiuxianDataManager().get_user_impart_info_with_id(user_id) else: - return xiuxian_impart.get_user_impart_info_with_id(user_id) + return await XiuxianDataManager().get_user_impart_info_with_id(user_id) msg_pass = { diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart_pk/xu_world.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart_pk/xu_world.py index 3f88af6a..fe2bd53c 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart_pk/xu_world.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_impart_pk/xu_world.py @@ -13,7 +13,7 @@ def __init__(self): try: with open(self.data_path, 'r', encoding='utf-8') as f: self.data = json.load(f) - except: + except FileNotFoundError: self.info = {} data = json.dumps(self.info, ensure_ascii=False, indent=4) with open(self.data_path, mode="x", encoding="UTF-8") as f: @@ -47,7 +47,7 @@ def check_xu_world_user_id(self, user_id): try: if self.data[user_id]: return True - except: + except ValueError: return False def add_xu_world(self, user_id): diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_info/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_info/__init__.py index 0ead3d8a..af28b6cd 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_info/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_info/__init__.py @@ -6,84 +6,80 @@ MessageSegment ) from ..xiuxian_utils.lay_out import assign_bot, Cooldown -from ..xiuxian_utils.xiuxian2_handle import XiuxianDateManage, OtherSet, UserBuffDate +from ..xiuxian_utils.xiuxian2_handle import XiuxianDataManager, OtherSet, UserBuffData from ..xiuxian_utils.data_source import jsondata from .draw_user_info import draw_user_info_img -from ..xiuxian_utils.utils import check_user, get_msg_pic, number_to +from ..xiuxian_utils.utils import check_user, number_to, handle_send from ..xiuxian_config import XiuConfig xiuxian_message = on_command("我的修仙信息", aliases={"我的存档"}, priority=23, permission=GROUP, block=True) -sql_message = XiuxianDateManage() # sql类 + # sql类 @xiuxian_message.handle(parameterless=[Cooldown(at_sender=False)]) async def xiuxian_message_(bot: Bot, event: GroupMessageEvent): """我的修仙信息""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await xiuxian_message.finish() user_id = user_info['user_id'] - user_info = sql_message.get_user_real_info(user_id) + user_info = await XiuxianDataManager().get_user_real_info(user_id) user_name = user_info['user_name'] user_num = user_info['id'] - rank = sql_message.get_exp_rank(user_id) - user_rank = int(rank[0]) - stone = sql_message.get_stone_rank(user_id) - user_stone = int(stone[0]) + rank = await XiuxianDataManager().get_exp_rank(user_id) + user_rank = int(rank) if rank is not None else 0 + stone = await XiuxianDataManager().get_stone_rank(user_id) + user_stone = int(stone) if stone is not None else 0 if user_name: pass else: - user_name = f"无名氏(发送改名+道号更新)" + user_name = "无名" - level_rate = sql_message.get_root_rate(user_info['root_type']) # 灵根倍率 + level_rate = await XiuxianDataManager().get_root_rate(user_info['root_type']) # 灵根倍率 realm_rate = jsondata.level_data()[user_info['level']]["spend"] # 境界倍率 sect_id = user_info['sect_id'] if sect_id: - sect_info = sql_message.get_sect_info(sect_id) + sect_info = await XiuxianDataManager().get_sect_info(sect_id) sectmsg = sect_info['sect_name'] sectzw = jsondata.sect_config_data()[f"{user_info['sect_position']}"]["title"] else: - sectmsg = f"无宗门" - sectzw = f"无" + sectmsg = "无宗门" + sectzw = "无" # 判断突破的修为 list_all = len(OtherSet().level) - 1 now_index = OtherSet().level.index(user_info['level']) if list_all == now_index: - exp_meg = f"位面至高" + exp_meg = "位面至高" else: is_updata_level = OtherSet().level[now_index + 1] - need_exp = sql_message.get_level_power(is_updata_level) + need_exp = await XiuxianDataManager().get_level_power(is_updata_level) get_exp = need_exp - user_info['exp'] if get_exp > 0: exp_meg = f"还需{number_to(get_exp)}修为可突破!" else: - exp_meg = f"可突破!" + exp_meg = "可突破!" - user_buff_data = UserBuffDate(user_id) - user_main_buff_date = user_buff_data.get_user_main_buff_data() - user_sub_buff_date = user_buff_data.get_user_sub_buff_data() - user_sec_buff_date = user_buff_data.get_user_sec_buff_data() - user_weapon_data = user_buff_data.get_user_weapon_data() - user_armor_data = user_buff_data.get_user_armor_buff_data() - main_buff_name = f"无" - sub_buff_name = f"无" - sec_buff_name = f"无" - weapon_name = f"无" - armor_name = f"无" + user_buff_data = UserBuffData(user_id) + user_main_buff_date = await user_buff_data.get_user_main_buff_data() + user_sub_buff_date = await user_buff_data.get_user_sub_buff_data() + user_sec_buff_date = await user_buff_data.get_user_sec_buff_data() + user_weapon_data = await user_buff_data.get_user_weapon_data() + user_armor_data = await user_buff_data.get_user_armor_buff_data() + main_buff_name = "无" + sub_buff_name = "无" + sec_buff_name = "无" + weapon_name = "无" + armor_name = "无" if user_main_buff_date is not None: main_buff_name = f"{user_main_buff_date['name']}({user_main_buff_date['level']})" - if user_sub_buff_date != None: + if user_sub_buff_date is not None: sub_buff_name = f"{user_sub_buff_date['name']}({user_sub_buff_date['level']})" if user_sec_buff_date is not None: sec_buff_name = f"{user_sec_buff_date['name']}({user_sec_buff_date['level']})" @@ -91,8 +87,8 @@ async def xiuxian_message_(bot: Bot, event: GroupMessageEvent): weapon_name = f"{user_weapon_data['name']}({user_weapon_data['level']})" if user_armor_data is not None: armor_name = f"{user_armor_data['name']}({user_armor_data['level']})" - main_rate_buff = UserBuffDate(user_id).get_user_main_buff_data() # 功法突破概率提升 - sql_message.update_last_check_info_time(user_id) # 更新查看修仙信息时间 + main_rate_buff = await UserBuffData(user_id).get_user_main_buff_data() # 功法突破概率提升 + await XiuxianDataManager().update_last_check_info_time(user_id) # 更新查看修仙信息时间 leveluprate = int(user_info['level_up_rate']) # 用户失败次数加成 number = main_rate_buff["number"] if main_rate_buff is not None else 0 DETAIL_MAP = { @@ -100,10 +96,10 @@ async def xiuxian_message_(bot: Bot, event: GroupMessageEvent): "境界": f"{user_info['level']}", "修为": f"{number_to(user_info['exp'])}", "灵石": f"{number_to(user_info['stone'])}", - "战力": f"{number_to(int(user_info['exp'] * level_rate * realm_rate))}", + "战力": f"{number_to(float(user_info['exp']) * float(level_rate) * float(realm_rate))}", "灵根": f"{user_info['root']}({user_info['root_type']}+{int(level_rate * 100)}%)", "突破状态": f"{exp_meg}概率:{jsondata.level_rate_data()[user_info['level']] + leveluprate + number}%", - "攻击力": f"{number_to(user_info['atk'])},攻修等级{user_info['atkpractice']}级", + "攻击力": f"{number_to(user_info['atk'])},攻修等级{user_info['atk_practice_level']}级", "所在宗门": sectmsg, "宗门职位": sectzw, "主修功法": main_buff_name, @@ -118,10 +114,14 @@ async def xiuxian_message_(bot: Bot, event: GroupMessageEvent): if XiuConfig().user_info_image: img_res = await draw_user_info_img(user_id, DETAIL_MAP) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(img_res)) + # 根据不同返回类型处理图片 + await bot.send_group_msg( + group_id=int(send_group_id), + message=MessageSegment.image(img_res) + ) await xiuxian_message.finish() else: - msg = f"""{user_name}道友的信息 + msg = """{user_name}道友的信息 灵根为:{user_info['root']}({user_info['root_type']}+{int(level_rate * 100)}%) 当前境界:{user_info['level']}(境界+{int(realm_rate * 100)}%) 当前灵石:{user_info['stone']} diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_info/download.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_info/download.py index a8392ac0..66cfa491 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_info/download.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_info/download.py @@ -38,10 +38,10 @@ async def get_avatar_by_user_id_and_save(user_id): try: if USER_AVATAR_PATH.exists(): - logger.opt(colors=True).info(f"用户头像已存在,跳过下载!") + logger.opt(colors=True).info("用户头像已存在,跳过下载!") im = Image.open(USER_AVATAR_PATH).resize((280, 280)).convert("RGBA") else: - logger.opt(colors=True).info(f"开始下载用户头像!") + logger.opt(colors=True).info("开始下载用户头像!") image_bytes = await download_avatar(user_id) im = Image.open(io.BytesIO(image_bytes)).resize((280, 280)).convert("RGBA") if not os.path.exists(PLAYERSDATA / user_id): diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_info/draw_user_info.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_info/draw_user_info.py index 69356b55..88c3f0c1 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_info/draw_user_info.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_info/draw_user_info.py @@ -8,8 +8,9 @@ from PIL import Image, ImageDraw, ImageFont from aiohttp import ClientSession from pathlib import Path +from base64 import b64encode from .download import get_avatar_by_user_id_and_save -from .send_image_tool import convert_img +from ..xiuxian_config import XiuConfig TEXT_PATH = Path() / "data" / "xiuxian" / "info_img" @@ -51,7 +52,7 @@ async def draw_user_info_img(user_id, DETAIL_MAP): img.resize((based_w, based_h), Image.Resampling.LANCZOS) # 贴一层黑色遮罩 img.paste(i := Image.new("RGBA", (based_w, based_h), (0, 0, 0, 168)), mask=i) - except: + except ValueError: logger.opt(colors=True).info("下载随机背景图失败,使用默认背景图") img = Image.open(TEXT_PATH / 'back.png').resize((based_w, based_h)).convert("RGBA") # 获取用户头像圆框 @@ -123,7 +124,6 @@ async def draw_user_info_img(user_id, DETAIL_MAP): tasks3.append(_draw_sect_info_line(img, key, value, DETAIL_sectinfo)) await asyncio.gather(*tasks3) img.convert("RGB") - res = await convert_img(img) paihang = Image.open( TEXT_PATH / 'line2.png').resize((900, 100)).convert("RGBA") @@ -142,8 +142,49 @@ async def draw_user_info_img(user_id, DETAIL_MAP): for key, value in DETAIL_paihang.items(): tasks4.append(_draw_ph_info_line(img, key, value, DETAIL_paihang)) await asyncio.gather(*tasks4) - res = await convert_img(img) - return res + + # 根据发送类型返回不同格式的图片 + if XiuConfig().img_send_type == "io": + # 使用压缩方法 + return await compress_img(img) + elif XiuConfig().img_send_type == "base64": + # 先压缩再转base64 + compressed_bytes = await compress_img(img) + return f"base64://{b64encode(compressed_bytes).decode()}" + else: + # 默认返回bytes格式 + return await compress_img(img) + + +async def compress_img(img): + """对传入图片进行压缩""" + img_byte_arr = BytesIO() + compression_quality = max( + 1, min(100, 100 - XiuConfig().img_compression_limit) + ) # 质量从100到1 + + if not (0 <= XiuConfig().img_compression_limit <= 100): + compression_quality = 50 + + # 转换为 RGB + if img.mode in ("RGBA", "P"): + img = img.convert("RGB") + + try: + if XiuConfig().img_type == "webp": + img.save(img_byte_arr, format="WEBP", quality=compression_quality) + elif XiuConfig().img_type == "jpeg": + img.save(img_byte_arr, format="JPEG", quality=compression_quality) + else: + img.save(img_byte_arr, format="WEBP", quality=compression_quality) + except Exception as e: + # 尝试降级为 JPEG + logger.opt(colors=True).info(f"图片保存出错:{str(e)},尝试降级为JPEG") + img.save(img_byte_arr, format="JPEG", quality=compression_quality) + + img_byte_arr.seek(0) + return img_byte_arr.getvalue() + async def _draw_line(img: Image.Image, key, value, DETAIL_MAP): line = Image.open(TEXT_PATH / 'line3.png').resize((450, 68)) diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_info/send_image_tool.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_info/send_image_tool.py deleted file mode 100755 index acffa37d..00000000 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_info/send_image_tool.py +++ /dev/null @@ -1,36 +0,0 @@ -from io import BytesIO -from pathlib import Path -from typing import Union -from base64 import b64encode -from PIL import Image - - -async def convert_img( - img: Union[Image.Image, str, Path, bytes], is_base64: bool = False -): - """ - :说明: - 将PIL.Image对象转换为bytes或者base64格式。 - :参数: - * img (Image): 图片。 - * is_base64 (bool): 是否转换为base64格式, 不填默认转为bytes。 - :返回: - * res: bytes对象或base64编码图片。 - """ - if isinstance(img, (str, Path)): - img = Image.open(str(img)) - - if isinstance(img, Image.Image): - img = img.convert('RGB') - result_buffer = BytesIO() - img.save(result_buffer, format='PNG', quality=80, subsampling=0) - res = result_buffer.getvalue() - if is_base64: - return 'base64://' + b64encode(res).decode() - return res - elif isinstance(img, bytes): - if is_base64: - return 'base64://' + b64encode(img).decode() - return img - else: - raise ValueError("不支持的输入格式") diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_lunhui/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_lunhui/__init__.py index c039bb21..7f9241ae 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_lunhui/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_lunhui/__init__.py @@ -1,219 +1,168 @@ -from nonebot import on_command, on_fullmatch -from ..xiuxian_utils.lay_out import assign_bot, Cooldown -from ..xiuxian_config import XiuConfig -from ..xiuxian_utils.xiuxian2_handle import XiuxianDateManage -from ..xiuxian_utils.data_source import jsondata -from nonebot.adapters.onebot.v11 import ( - Bot, - GROUP, - GroupMessageEvent, - MessageSegment -) -from ..xiuxian_utils.utils import ( - check_user, get_msg_pic, - CommandObjectID -) - -__warring_help__ = """ -详情: -散尽修为,轮回重修,将万世的道果凝聚为极致天赋 -修为、功法、神通将被清空!! -进入千世轮回:获得轮回灵根,可定制极品仙器(在做) -进入万世轮回:获得真轮回灵根,可定制无上仙器(在做) -自废修为:字面意思,仅搬血境可用 -""".strip() - -cache_help_fk = {} -sql_message = XiuxianDateManage() # sql类 - -warring_help = on_fullmatch("轮回重修帮助", priority=12, permission=GROUP, block=True) -lunhui = on_command('进入千世轮回', priority=15, permission=GROUP,block=True) -twolun = on_command('进入万世轮回', priority=15, permission=GROUP,block=True) -resetting = on_command('自废修为', priority=15, permission=GROUP,block=True) - - -@warring_help.handle(parameterless=[Cooldown(at_sender=False)]) -async def warring_help_(bot: Bot, event: GroupMessageEvent, session_id: int = CommandObjectID()): - """轮回重修帮助""" - bot, send_group_id = await assign_bot(bot=bot, event=event) - if session_id in cache_help_fk: - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(cache_help_fk[session_id])) - await warring_help.finish() - else: - msg = __warring_help__ - if XiuConfig().img: - pic = await get_msg_pic(msg) - cache_help_fk[session_id] = pic - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await warring_help.finish() - -@lunhui.handle(parameterless=[Cooldown(at_sender=False)]) -async def lunhui_(bot: Bot, event: GroupMessageEvent, session_id: int = CommandObjectID()): - bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) - if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await lunhui.finish() - - user_id = user_info['user_id'] - user_msg = sql_message.get_user_info_with_id(user_id) - user_name = user_msg['user_name'] - user_root = user_msg['root_type'] - list_level_all = list(jsondata.level_data().keys()) - level = user_info['level'] - - if user_root == '轮回道果' : - msg = "道友已是千世轮回之身!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await lunhui.finish() - - if user_root == '真·轮回道果' : - msg = "道友已是万世轮回之身!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await lunhui.finish() - - if list_level_all.index(level) >= list_level_all.index(XiuConfig().lunhui_min_level): - exp = user_msg['exp'] - now_exp = exp - 100 - sql_message.updata_level(user_id, '江湖好手') #重置用户境界 - sql_message.update_levelrate(user_id, 0) #重置突破成功率 - sql_message.update_j_exp(user_id, now_exp) #重置用户修为 - sql_message.update_user_hp(user_id) # 重置用户HP,mp,atk状态 - sql_message.reset_user_drug_resistance(user_id) #重置用户耐药性 - sql_message.updata_user_main_buff(user_id, 0) #重置用户主功法 - sql_message.updata_user_sub_buff(user_id, 0) #重置用户辅修功法 - sql_message.updata_user_sec_buff(user_id, 0) #重置用户神通 - sql_message.update_user_atkpractice(user_id, 0) #重置用户攻修等级 - sql_message.update_root(user_id, 6) #更换轮回灵根 - msg = f"千世轮回磨不灭,重回绝颠谁能敌,恭喜大能{user_name}轮回成功!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await lunhui.finish() - else: - msg = f"道友境界未达要求,进入千世轮回的最低境界为{XiuConfig().lunhui_min_level}" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await lunhui.finish() - -@twolun.handle(parameterless=[Cooldown(at_sender=False)]) -async def twolun_(bot: Bot, event: GroupMessageEvent, session_id: int = CommandObjectID()): - bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) - if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await twolun.finish() - - user_id = user_info['user_id'] - user_msg = sql_message.get_user_info_with_id(user_id) - user_name = user_msg['user_name'] - user_root = user_msg['root_type'] - list_level_all = list(jsondata.level_data().keys()) - level = user_info['level'] - - if user_root == '真·轮回道果': - msg = "道友已是万世轮回之身!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await twolun.finish() - - if user_root != '轮回道果': - msg = "道友还未轮回过,请先进入千世轮回!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await twolun.finish() - - if list_level_all.index(level) >= list_level_all.index(XiuConfig().twolun_min_level) and user_root == '轮回道果': - exp = user_msg['exp'] - now_exp = exp - 100 - sql_message.updata_level(user_id, '江湖好手') #重置用户境界 - sql_message.update_levelrate(user_id, 0) #重置突破成功率 - sql_message.update_j_exp(user_id, now_exp) #重置用户修为 - sql_message.update_user_hp(user_id) # 重置用户HP,mp,atk状态 - sql_message.reset_user_drug_resistance(user_id) #重置用户耐药性 - sql_message.update_root(user_id, 7) #更换轮回灵根 - msg = f"万世道果集一身,脱出凡道入仙道,恭喜大能{user_name}万世轮回成功!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await twolun.finish() - else: - msg = f"道友境界未达要求,万世轮回的最低境界为{XiuConfig().twolun_min_level}!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await twolun.finish() - -@resetting.handle(parameterless=[Cooldown(at_sender=False)]) -async def resetting_(bot: Bot, event: GroupMessageEvent, session_id: int = CommandObjectID()): - bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) - if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await resetting.finish() - - user_id = user_info['user_id'] - user_msg = sql_message.get_user_info_with_id(user_id) - user_name = user_msg['user_name'] - - - if user_msg['level'] in ['搬血境初期', '搬血境中期', '搬血境圆满']: - exp = user_msg['exp'] - now_exp = exp - sql_message.updata_level(user_id, '江湖好手') #重置用户境界 - sql_message.update_levelrate(user_id, 0) #重置突破成功率 - sql_message.update_j_exp(user_id, now_exp) #重置用户修为 - sql_message.update_user_hp(user_id) # 重置用户HP,mp,atk状态 - msg = f"{user_name}现在是一介凡人了!!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await resetting.finish() - else: - msg = f"道友境界未达要求,自废修为的最低境界为搬血境!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await resetting.finish() - +from nonebot import on_command, on_fullmatch +from ..xiuxian_utils.lay_out import assign_bot, Cooldown +from ..xiuxian_config import XiuConfig +from ..xiuxian_utils.xiuxian2_handle import XiuxianDataManager +from ..xiuxian_utils.data_source import jsondata +from nonebot.adapters.onebot.v11 import ( + Bot, + GROUP, + GroupMessageEvent, + MessageSegment +) +from ..xiuxian_utils.utils import ( + check_user, get_msg_pic, + CommandObjectID, + handle_send +) + +__warring_help__ = """ +详情: +散尽修为,轮回重修,将万世的道果凝聚为极致天赋 +修为、功法、神通将被清空!! +进入千世轮回:获得轮回灵根,可定制极品仙器(在做) +进入万世轮回:获得真轮回灵根,可定制无上仙器(在做) +自废修为:字面意思,仅搬血境可用 +""".strip() + +cache_help_fk = {} + # sql类 + +warring_help = on_fullmatch("轮回重修帮助", priority=12, permission=GROUP, block=True) +lunhui = on_command('进入千世轮回', priority=15, permission=GROUP,block=True) +twolun = on_command('进入万世轮回', priority=15, permission=GROUP,block=True) +resetting = on_command('自废修为', priority=15, permission=GROUP,block=True) + + +@warring_help.handle(parameterless=[Cooldown(at_sender=False)]) +async def warring_help_(bot: Bot, event: GroupMessageEvent, session_id: int = CommandObjectID()): + """轮回重修帮助""" + bot, send_group_id = await assign_bot(bot=bot, event=event) + if session_id in cache_help_fk: + await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(cache_help_fk[session_id])) + await warring_help.finish() + else: + msg = __warring_help__ + if XiuConfig().img: + pic = await get_msg_pic(msg) + cache_help_fk[session_id] = pic + await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) + else: + await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await warring_help.finish() + +@lunhui.handle(parameterless=[Cooldown(at_sender=False)]) +async def lunhui_(bot: Bot, event: GroupMessageEvent, session_id: int = CommandObjectID()): + bot, send_group_id = await assign_bot(bot=bot, event=event) + isUser, user_info, msg = await check_user(event) + if not isUser: + await handle_send(bot, event, send_group_id, msg) + await lunhui.finish() + + user_id = user_info['user_id'] + user_msg = await XiuxianDataManager().get_user_infos_by_ids(user_id) + user_name = user_msg['user_name'] + user_root = user_msg['root_type'] + list_level_all = list(jsondata.level_data().keys()) + level = user_info['level'] + + if user_root == '轮回道果' : + msg = "道友已是千世轮回之身!" + await handle_send(bot, event, send_group_id, msg) + await lunhui.finish() + + if user_root == '真·轮回道果' : + msg = "道友已是万世轮回之身!" + await handle_send(bot, event, send_group_id, msg) + await lunhui.finish() + + if list_level_all.index(level) >= list_level_all.index(XiuConfig().lunhui_min_level): + exp = user_msg['exp'] + now_exp = exp - 100 + await XiuxianDataManager().updata_level(user_id, '江湖好手') #重置用户境界 + await XiuxianDataManager().update_levelrate(user_id, 0) #重置突破成功率 + await XiuxianDataManager().update_exp(user_id, now_exp, 1) #重置用户修为 + await XiuxianDataManager().update_user_hp(user_id) # 重置用户HP,mp,atk状态 + await XiuxianDataManager().reset_user_drug_resistance(user_id) #重置用户耐药性 + await XiuxianDataManager().updata_user_main_buff(user_id, 0) #重置用户主功法 + await XiuxianDataManager().updata_user_sub_buff(user_id, 0) #重置用户辅修功法 + await XiuxianDataManager().updata_user_sec_buff(user_id, 0) #重置用户神通 + await XiuxianDataManager().update_user_atkpractice(user_id, 0) #重置用户攻修等级 + await XiuxianDataManager().update_root(user_id, 6) #更换轮回灵根 + msg = f"千世轮回磨不灭,重回绝颠谁能敌,恭喜大能{user_name}轮回成功!" + await handle_send(bot, event, send_group_id, msg) + await lunhui.finish() + else: + msg = f"道友境界未达要求,进入千世轮回的最低境界为{XiuConfig().lunhui_min_level}" + await handle_send(bot, event, send_group_id, msg) + await lunhui.finish() + +@twolun.handle(parameterless=[Cooldown(at_sender=False)]) +async def twolun_(bot: Bot, event: GroupMessageEvent, session_id: int = CommandObjectID()): + bot, send_group_id = await assign_bot(bot=bot, event=event) + isUser, user_info, msg = await check_user(event) + if not isUser: + await handle_send(bot, event, send_group_id, msg) + await twolun.finish() + + user_id = user_info['user_id'] + user_msg = await XiuxianDataManager().get_user_infos_by_ids(user_id) + user_name = user_msg['user_name'] + user_root = user_msg['root_type'] + list_level_all = list(jsondata.level_data().keys()) + level = user_info['level'] + + if user_root == '真·轮回道果': + msg = "道友已是万世轮回之身!" + await handle_send(bot, event, send_group_id, msg) + await twolun.finish() + + if user_root != '轮回道果': + msg = "道友还未轮回过,请先进入千世轮回!" + await handle_send(bot, event, send_group_id, msg) + await twolun.finish() + + if list_level_all.index(level) >= list_level_all.index(XiuConfig().twolun_min_level) and user_root == '轮回道果': + exp = user_msg['exp'] + now_exp = exp - 100 + await XiuxianDataManager().updata_level(user_id, '江湖好手') #重置用户境界 + await XiuxianDataManager().update_levelrate(user_id, 0) #重置突破成功率 + await XiuxianDataManager().update_exp(user_id, now_exp, 1) #重置用户修为 + await XiuxianDataManager().update_user_hp(user_id) # 重置用户HP,mp,atk状态 + await XiuxianDataManager().reset_user_drug_resistance(user_id) #重置用户耐药性 + await XiuxianDataManager().update_root(user_id, 7) #更换轮回灵根 + msg = f"万世道果集一身,脱出凡道入仙道,恭喜大能{user_name}万世轮回成功!" + await handle_send(bot, event, send_group_id, msg) + await twolun.finish() + else: + msg = f"道友境界未达要求,万世轮回的最低境界为{XiuConfig().twolun_min_level}!" + await handle_send(bot, event, send_group_id, msg) + await twolun.finish() + +@resetting.handle(parameterless=[Cooldown(at_sender=False)]) +async def resetting_(bot: Bot, event: GroupMessageEvent, session_id: int = CommandObjectID()): + bot, send_group_id = await assign_bot(bot=bot, event=event) + isUser, user_info, msg = await check_user(event) + if not isUser: + await handle_send(bot, event, send_group_id, msg) + await resetting.finish() + + user_id = user_info['user_id'] + user_msg = await XiuxianDataManager().get_user_infos_by_ids(user_id) + user_name = user_msg['user_name'] + + + if user_msg['level'] in ['搬血境初期', '搬血境中期', '搬血境圆满']: + exp = user_msg['exp'] + now_exp = exp + await XiuxianDataManager().updata_level(user_id, '江湖好手') #重置用户境界 + await XiuxianDataManager().update_levelrate(user_id, 0) #重置突破成功率 + await XiuxianDataManager().update_exp(user_id, now_exp, 1) #重置用户修为 + await XiuxianDataManager().update_user_hp(user_id) # 重置用户HP,mp,atk状态 + msg = f"{user_name}现在是一介凡人了!!" + await handle_send(bot, event, send_group_id, msg) + await resetting.finish() + else: + msg = "道友境界未达要求,自废修为的最低境界为搬血境!" + await handle_send(bot, event, send_group_id, msg) + await resetting.finish() + diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_mixelixir/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_mixelixir/__init__.py index f7a9cfdf..64df704d 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_mixelixir/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_mixelixir/__init__.py @@ -1,5 +1,4 @@ import random -import asyncio import re from nonebot import on_command, on_fullmatch from nonebot.params import EventPlainText @@ -7,25 +6,23 @@ Bot, GROUP, GroupMessageEvent, - MessageSegment, - ActionFailed + MessageSegment ) from ..xiuxian_utils.lay_out import assign_bot, Cooldown from ..xiuxian_utils.xiuxian2_handle import ( - XiuxianDateManage, get_player_info, save_player_info, - UserBuffDate, XIUXIAN_IMPART_BUFF + XiuxianDataManager, get_player_info, save_player_info, + UserBuffData ) from ..xiuxian_utils.utils import ( check_user, send_msg_handler, - get_msg_pic, CommandObjectID + get_msg_pic, CommandObjectID, + handle_send ) from ..xiuxian_utils.item_json import Items from .mixelixirutil import get_mix_elixir_msg, tiaohe, check_mix, make_dict from ..xiuxian_config import convert_rank, XiuConfig from datetime import datetime from .mix_elixir_config import MIXELIXIRCONFIG -sql_message = XiuxianDateManage() # sql类 -xiuxian_impart = XIUXIAN_IMPART_BUFF() items = Items() cache_help = {} @@ -38,7 +35,7 @@ mix_elixir_sqdj_up = on_fullmatch("升级收取等级", priority=6, permission=GROUP, block=True) mix_elixir_dykh_up = on_fullmatch("升级丹药控火", priority=6, permission=GROUP, block=True) -__elixir_help__ = f""" +__elixir_help__ = """ 炼丹帮助信息: 指令: 1、炼丹:会检测背包内的药材,自动生成配方【一次最多匹配25种药材】 @@ -51,13 +48,15 @@ 8、升级丹药控火:每一个等级会增加炼丹的产出数量 """ -__mix_elixir_help__ = f""" +__mix_elixir_help__ = """ 炼丹配方信息 1、炼丹需要主药、药引、辅药 2、主药和药引控制炼丹时的冷热调和,冷热失和则炼不出丹药 3、草药的类型控制产出丹药的类型 4、来自群友猫猫头工具网址 https://huggingface.co/spaces/chewing/liandan +如果无法访问可以试试下面这个 +https://huggingface.co/spaces/yjzyl9008/xiuxian_mixelixir """ @@ -65,52 +64,32 @@ async def mix_elixir_sqdj_up_(bot: Bot, event: GroupMessageEvent): """收取等级升级""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await mix_elixir_sqdj_up.finish() user_id = user_info['user_id'] if int(user_info['blessed_spot_flag']) == 0: - msg = f"道友还没有洞天福地呢,请发送洞天福地购买吧~" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友还没有洞天福地呢,请发送洞天福地购买吧~" + await handle_send(bot, event, send_group_id, msg) await mix_elixir_sqdj_up.finish() SQDJCONFIG = MIXELIXIRCONFIG['收取等级'] mix_elixir_info = get_player_info(user_id, "mix_elixir_info") now_level = mix_elixir_info['收取等级'] if now_level >= len(SQDJCONFIG): - msg = f"道友的收取等级已达到最高等级,无法升级了" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友的收取等级已达到最高等级,无法升级了" + await handle_send(bot, event, send_group_id, msg) await mix_elixir_sqdj_up.finish() next_level_cost = SQDJCONFIG[str(now_level + 1)]['level_up_cost'] if mix_elixir_info['炼丹经验'] < next_level_cost: msg = f"下一个收取等级所需要的炼丹经验为{next_level_cost}点,道友请炼制更多的丹药再来升级吧~" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await mix_elixir_sqdj_up.finish() mix_elixir_info['炼丹经验'] = mix_elixir_info['炼丹经验'] - next_level_cost mix_elixir_info['收取等级'] = now_level + 1 save_player_info(user_id, mix_elixir_info, 'mix_elixir_info') msg = f"道友的收取等级目前为:{mix_elixir_info['收取等级']}级,可以使灵田收获的药材增加{mix_elixir_info['收取等级']}个!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await mix_elixir_sqdj_up.finish() @@ -118,44 +97,28 @@ async def mix_elixir_sqdj_up_(bot: Bot, event: GroupMessageEvent): async def mix_elixir_dykh_up_(bot: Bot, event: GroupMessageEvent): """丹药控火升级""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await mix_elixir_dykh_up.finish() user_id = user_info['user_id'] DYKHCONFIG = MIXELIXIRCONFIG['丹药控火'] mix_elixir_info = get_player_info(user_id, "mix_elixir_info") now_level = mix_elixir_info['丹药控火'] if now_level >= len(DYKHCONFIG): - msg = f"道友的丹药控火等级已达到最高等级,无法升级了" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友的丹药控火等级已达到最高等级,无法升级了" + await handle_send(bot, event, send_group_id, msg) await mix_elixir_dykh_up.finish() next_level_cost = DYKHCONFIG[str(now_level + 1)]['level_up_cost'] if mix_elixir_info['炼丹经验'] < next_level_cost: msg = f"下一个丹药控火等级所需要的炼丹经验为{next_level_cost}点,道友请炼制更多的丹药再来升级吧~" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await mix_elixir_dykh_up.finish() mix_elixir_info['炼丹经验'] = mix_elixir_info['炼丹经验'] - next_level_cost mix_elixir_info['丹药控火'] = now_level + 1 save_player_info(user_id, mix_elixir_info, 'mix_elixir_info') msg = f"道友的丹药控火等级目前为:{mix_elixir_info['丹药控火']}级,可以使炼丹收获的丹药增加{mix_elixir_info['丹药控火']}个!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await mix_elixir_dykh_up.finish() @@ -163,23 +126,15 @@ async def mix_elixir_dykh_up_(bot: Bot, event: GroupMessageEvent): async def yaocai_get_(bot: Bot, event: GroupMessageEvent): """灵田收取""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await yaocai_get.finish() user_id = user_info['user_id'] if int(user_info['blessed_spot_flag']) == 0: - msg = f"道友还没有洞天福地呢,请发送洞天福地购买吧~" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友还没有洞天福地呢,请发送洞天福地购买吧~" + await handle_send(bot, event, send_group_id, msg) await yaocai_get.finish() mix_elixir_info = get_player_info(user_id, "mix_elixir_info") GETCONFIG = { @@ -195,19 +150,19 @@ async def yaocai_get_(bot: Bot, event: GroupMessageEvent): if timedeff >= round(GETCONFIG['time_cost'] * (1 - (GETCONFIG['加速基数'] * mix_elixir_info['药材速度'])), 2): yaocai_id_list = items.get_random_id_list_by_rank_and_item_type(convert_rank(user_info['level'])[0], ['药材']) # 加入传承 - impart_data = xiuxian_impart.get_user_impart_info_with_id(user_id) - impart_reap_per = impart_data['impart_reap_per'] if impart_data is not None else 0 + impart_data = await XiuxianDataManager().get_user_impart_info_with_id(user_id) + impart_reap_addition = impart_data['impart_reap_addition'] if impart_data is not None else 0 #功法灵田收取加成 - main_reap = UserBuffDate(user_id).get_user_main_buff_data() + main_reap = UserBuffData(user_id).get_user_main_buff_data() - if main_reap != None: #功法灵田收取加成 - reap_buff = main_reap['reap_buff'] + if main_reap is not None: #功法灵田收取加成 + reap_buff = main_reap['reap_buf'] else: reap_buff = 0 - num = mix_elixir_info['灵田数量'] + mix_elixir_info['收取等级'] + impart_reap_per + reap_buff + num = mix_elixir_info['灵田数量'] + mix_elixir_info['收取等级'] + impart_reap_addition + reap_buff msg = '' if not yaocai_id_list: - sql_message.send_back(user_info['user_id'], 3001, '恒心草', '药材', num) # 没有合适的,保底 + await XiuxianDataManager().send_back(user_info['user_id'], 3001, '恒心草', '药材', num) # 没有合适的,保底 msg += f"道友成功收获药材:恒心草 {num} 个!\n" else: i = 1 @@ -223,22 +178,14 @@ async def yaocai_get_(bot: Bot, event: GroupMessageEvent): for k, v in give_dict.items(): goods_info = items.get_data_by_item_id(k) msg += f"道友成功收获药材:{goods_info['name']} {v} 个!\n" - sql_message.send_back(user_info['user_id'], k, goods_info['name'], '药材', v) + await XiuxianDataManager().send_back(user_info['user_id'], k, goods_info['name'], '药材', v) mix_elixir_info['收取时间'] = nowtime save_player_info(user_id, mix_elixir_info, "mix_elixir_info") - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await yaocai_get.finish() else: msg = f"道友的灵田还不能收取,下次收取时间为:{round(GETCONFIG['time_cost'] * (1 - (GETCONFIG['加速基数'] * mix_elixir_info['药材速度'])), 2) - timedeff}小时之后" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await yaocai_get.finish() @@ -246,24 +193,20 @@ async def yaocai_get_(bot: Bot, event: GroupMessageEvent): async def my_mix_elixir_info_(bot: Bot, event: GroupMessageEvent): """我的炼丹信息""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await my_mix_elixir_info.finish() user_id = user_info['user_id'] mix_elixir_info = get_player_info(user_id, 'mix_elixir_info') - l_msg = [f"☆------道友的炼丹信息------☆"] + l_msg = ["☆------道友的炼丹信息------☆"] msg = f"药材收取等级:{mix_elixir_info['收取等级']}\n" msg += f"丹药控火等级:{mix_elixir_info['丹药控火']}\n" msg += f"丹药耐药性等级:{mix_elixir_info['丹药耐药性']}\n" msg += f"炼丹经验:{mix_elixir_info['炼丹经验']}\n" l_msg.append(msg) if mix_elixir_info['炼丹记录'] != {}: - l_msg.append(f"☆------道友的炼丹记录------☆") + l_msg.append("☆------道友的炼丹记录------☆") i = 1 for k, v in mix_elixir_info['炼丹记录'].items(): msg = f"编号:{i},{v['name']},炼成次数:{v['num']}次" @@ -309,16 +252,12 @@ async def mix_elixir_(bot: Bot, event: GroupMessageEvent): """炼丹,用来生成配方""" global user_ldl_dict, user_ldl_flag bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await mix_elixir.finish() user_id = user_info['user_id'] - user_back = sql_message.get_back_msg(user_id) + user_back = await XiuxianDataManager().get_back_msg(user_id) yaocai_dict = {} user_ldl_flag[user_id] = False # 初始化炼丹炉标志 for back in user_back: @@ -333,47 +272,27 @@ async def mix_elixir_(bot: Bot, event: GroupMessageEvent): if user_back is None: msg = "道友的背包空空如也,无法炼丹" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await mix_elixir.finish() if yaocai_dict == {}: msg = "道友的背包内没有药材,无法炼丹!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await mix_elixir.finish() if not user_ldl_flag[user_id]: msg = "道友背包内没有炼丹炉,无法炼丹!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await mix_elixir.finish() msg = "正在生成丹方,请稍候..." - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) yaocai_dict = await make_dict(yaocai_dict) finall_mix_elixir_msg = await get_mix_elixir_msg(yaocai_dict) if finall_mix_elixir_msg == {}: msg = "系统未检测到丹方,道友背包内的药材不满足!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await mix_elixir.finish() else: ldl_name = sorted(user_ldl_dict[user_id].items(), key=lambda x: x[0], reverse=False)[0][1] @@ -383,7 +302,7 @@ async def mix_elixir_(bot: Bot, event: GroupMessageEvent): msg = f"名字:{goods_info['name']}\n" msg += f"效果:{goods_info['desc']}\n" msg += f"配方:{v['配方']['配方简写']}丹炉{ldl_name}\n" - msg += f"\n☆------药材清单------☆\n" + msg += "\n☆------药材清单------☆\n" msg += f"主药:{v['配方']['主药']},{v['配方']['主药_level']},数量:{v['配方']['主药_num']}\n" msg += f"药引:{v['配方']['药引']},{v['配方']['药引_level']},数量:{v['配方']['药引_num']}\n" if v['配方']['辅药_num'] != 0: @@ -397,19 +316,16 @@ async def mix_elixir_(bot: Bot, event: GroupMessageEvent): # 配方 @mix_make.handle(parameterless=[Cooldown(stamina_cost = 3, at_sender=False)]) -async def mix_elixir_(bot: Bot, event: GroupMessageEvent, mode: str = EventPlainText()): +async def formula_elixir_(bot: Bot, event: GroupMessageEvent, mode: str = EventPlainText()): """配方,用来炼制丹药""" bot, send_group_id = await assign_bot(bot=bot, event=event) user_id = event.user_id + isUser, user_info, msg = await check_user(event) pattern = r"主药([\u4e00-\u9fa5]+)(\d+)药引([\u4e00-\u9fa5]+)(\d+)辅药([\u4e00-\u9fa5]+)(\d+)丹炉([\u4e00-\u9fa5]+)+" matched = re.search(pattern, mode) if matched is None: - msg = f"请输入正确的配方!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请输入正确的配方!" + await handle_send(bot, event, send_group_id, msg) await mix_make.finish() else: zhuyao_name = matched.groups()[0] @@ -417,40 +333,28 @@ async def mix_elixir_(bot: Bot, event: GroupMessageEvent, mode: str = EventPlain check, zhuyao_goods_id = await check_yaocai_name_in_back(user_id, zhuyao_name, zhuyao_num) if not check: msg = f"请检查药材:{zhuyao_name} 是否在背包中,或者数量是否足够!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await mix_make.finish() yaoyin_name = matched.groups()[2] yaoyin_num = int(matched.groups()[3]) # 数量一定会有 check, yaoyin_goods_id = await check_yaocai_name_in_back(user_id, yaoyin_name, yaoyin_num) if not check: msg = f"请检查药材:{yaoyin_name} 是否在背包中,或者数量是否足够!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await mix_make.finish() fuyao_name = matched.groups()[4] fuyao_num = int(matched.groups()[5]) check, fuyao_goods_id = await check_yaocai_name_in_back(user_id, fuyao_name, fuyao_num) if not check: msg = f"请检查药材:{fuyao_name} 是否在背包中,或者数量是否足够!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await mix_make.finish() if zhuyao_name == fuyao_name: check, fuyao_goods_id = await check_yaocai_name_in_back(user_id, fuyao_name, fuyao_num + zhuyao_num) if not check: msg = f"请检查药材:{zhuyao_name} 是否在背包中,或者数量是否足够!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -460,7 +364,7 @@ async def mix_elixir_(bot: Bot, event: GroupMessageEvent, mode: str = EventPlain if not check: msg = f"请检查药材:{yaoyin_name} 是否在背包中,或者数量是否足够!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -470,22 +374,14 @@ async def mix_elixir_(bot: Bot, event: GroupMessageEvent, mode: str = EventPlain check, ldl_info = await check_ldl_name_in_back(user_id, ldl_name) if not check: msg = f"请检查炼丹炉:{ldl_name} 是否在背包中!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await mix_make.finish() # 检测通过 zhuyao_info = Items().get_data_by_item_id(zhuyao_goods_id) yaoyin_info = Items().get_data_by_item_id(yaoyin_goods_id) if await tiaohe(zhuyao_info, zhuyao_num, yaoyin_info, yaoyin_num): # 调和失败 - msg = f"冷热调和失败!小心炸炉哦~" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "冷热调和失败!小心炸炉哦~" + await handle_send(bot, event, send_group_id, msg) await mix_make.finish() else: elixir_config = { @@ -498,32 +394,31 @@ async def mix_elixir_(bot: Bot, event: GroupMessageEvent, mode: str = EventPlain mix_elixir_info = get_player_info(user_id, 'mix_elixir_info') goods_info = Items().get_data_by_item_id(id) # 加入传承 - impart_data = xiuxian_impart.get_user_impart_info_with_id(user_id) - impart_mix_per = impart_data['impart_mix_per'] if impart_data is not None else 0 + impart_data = await XiuxianDataManager().get_user_impart_info_with_id(user_id) + impart_mix_addition = impart_data['impart_mix_addition'] if impart_data is not None else 0 #功法炼丹数加成 - main_dan_data = UserBuffDate(user_id).get_user_main_buff_data() + main_dan_data = UserBuffData(user_id).get_user_main_buff_data() - if main_dan_data != None: #功法炼丹数量加成 - main_dan = main_dan_data['dan_buff'] + if main_dan_data is not None: #功法炼丹数量加成 + main_dan = main_dan_data['dan_buf'] else: main_dan = 0 #功法炼丹经验加成 - main_dan_exp = UserBuffDate(user_id).get_user_main_buff_data() + main_dan_exp = UserBuffData(user_id).get_user_main_buff_data() - if main_dan_exp != None: #功法炼丹经验加成 + if main_dan_exp is not None: #功法炼丹经验加成 main_exp = main_dan_exp['dan_exp'] else: main_exp = 0 - num = 1 + ldl_info['buff'] + mix_elixir_info['丹药控火'] + impart_mix_per + main_dan#炼丹数量提升 + num = 1 + ldl_info['buf'] + mix_elixir_info['丹药控火'] + impart_mix_addition + main_dan#炼丹数量提升 msg = f"恭喜道友成功炼成丹药:{goods_info['name']}{num}枚" # 背包sql - sql_message.send_back(user_id, id, goods_info['name'], "丹药", num) #将炼制的丹药加入背包 - sql_message.update_back_j(user_id, zhuyao_goods_id, zhuyao_num) #将消耗的药材从背包中减去 - sql_message.update_back_j(user_id, fuyao_goods_id, fuyao_num) - sql_message.update_back_j(user_id, yaoyin_goods_id, yaoyin_num) + await XiuxianDataManager().send_back(user_id, id, goods_info['name'], "丹药", num) #将炼制的丹药加入背包 + await XiuxianDataManager().update_back_j(user_id, zhuyao_goods_id, zhuyao_num) #将消耗的药材从背包中减去 + await XiuxianDataManager().update_back_j(user_id, fuyao_goods_id, fuyao_num) + await XiuxianDataManager().update_back_j(user_id, yaoyin_goods_id, yaoyin_num) try: - var = mix_elixir_info['炼丹记录'][id] now_num = mix_elixir_info['炼丹记录'][id]['num'] #now_num 已经炼制的丹药数量 if now_num >= goods_info['mix_all']: msg += f"该丹药道友已炼制{now_num}次,无法获得炼丹经验了~" @@ -535,7 +430,7 @@ async def mix_elixir_(bot: Bot, event: GroupMessageEvent, mode: str = EventPlain mix_elixir_info['炼丹经验'] += (goods_info['mix_exp'] + main_exp) * num msg += f"获得炼丹经验{(goods_info['mix_exp'] + main_exp) * num}点" mix_elixir_info['炼丹记录'][id]['num'] += num - except: + except ValueError: mix_elixir_info['炼丹记录'][id] = {} mix_elixir_info['炼丹记录'][id]['name'] = goods_info['name'] mix_elixir_info['炼丹记录'][id]['num'] = num @@ -543,15 +438,15 @@ async def mix_elixir_(bot: Bot, event: GroupMessageEvent, mode: str = EventPlain msg += f"获得炼丹经验{(goods_info['mix_exp'] + main_exp) * num}点" save_player_info(user_id, mix_elixir_info, 'mix_elixir_info') if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await mix_make.finish() else: - msg = f"没有炼成丹药哦~就不扣你药材啦" + msg = "没有炼成丹药哦~就不扣你药材啦" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -561,7 +456,7 @@ async def mix_elixir_(bot: Bot, event: GroupMessageEvent, mode: str = EventPlain async def check_yaocai_name_in_back(user_id, yaocai_name, yaocai_num): flag = False goods_id = 0 - user_back = sql_message.get_back_msg(user_id) + user_back = await XiuxianDataManager().get_back_msg(user_id) for back in user_back: if back['goods_type'] == '药材': if Items().get_data_by_item_id(back['goods_id'])['name'] == yaocai_name: @@ -579,7 +474,7 @@ async def check_yaocai_name_in_back(user_id, yaocai_name, yaocai_num): async def check_ldl_name_in_back(user_id, ldl_name): flag = False goods_info = {} - user_back = sql_message.get_back_msg(user_id) + user_back = await XiuxianDataManager().get_back_msg(user_id) for back in user_back: if back['goods_type'] == '炼丹炉': if back['goods_name'] == ldl_name: diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_mixelixir/mixelixirutil.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_mixelixir/mixelixirutil.py index 6dfb5082..e5cab35d 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_mixelixir/mixelixirutil.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_mixelixir/mixelixirutil.py @@ -66,9 +66,7 @@ async def get_mix_elixir_msg(yaocai): continue o = 1 while o <= vv['num'] and o <= 5: - # _yaoyin = vv['药引']['h_a_c']['type'] * vv['药引']['h_a_c']['power'] * o if await tiaohe(v, i, vv, o): # 调和失败 - # if await absolute(_zhuyao + _yaoyin) > yonhudenji:#调和失败 o += 1 continue else: @@ -86,8 +84,7 @@ async def get_mix_elixir_msg(yaocai): zhuyao_type = str(v['主药']['type']) zhuyao_power = v['主药']['power'] * i elixir_config[zhuyao_type] = zhuyao_power - elixir_config[fuyao_type] = fuyao_power - # print(elixir_config) + elixir_config[fuyao_type] = fuyao_power is_mix, id_ = await check_mix(elixir_config) if is_mix: # 有可以合成的 if i + o + p <= Llandudno_info["max_num"]: @@ -155,6 +152,7 @@ async def absolute(x): async def tiaohe(zhuyao_info, zhuyao_num, yaoyin_info, yaoyin_num): + """调和药材""" _zhuyao = zhuyao_info['主药']['h_a_c']['type'] * zhuyao_info['主药']['h_a_c']['power'] * zhuyao_num _yaoyin = yaoyin_info['药引']['h_a_c']['type'] * yaoyin_info['药引']['h_a_c']['power'] * yaoyin_num diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_rift/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_rift/__init__.py index fccb7ee0..b540387e 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_rift/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_rift/__init__.py @@ -1,6 +1,6 @@ import random from datetime import datetime -from nonebot import get_bots, on_command, require, on_fullmatch +from nonebot import on_command, require, on_fullmatch from nonebot.params import CommandArg from nonebot.adapters.onebot.v11 import ( Bot, @@ -16,10 +16,10 @@ from ..xiuxian_utils.lay_out import assign_bot, assign_bot_group, Cooldown from nonebot.permission import SUPERUSER from nonebot.log import logger -from ..xiuxian_utils.xiuxian2_handle import XiuxianDateManage +from ..xiuxian_utils.xiuxian2_handle import XiuxianDataManager from ..xiuxian_utils.utils import ( check_user, check_user_type, - send_msg_handler, get_msg_pic, CommandObjectID + send_msg_handler, get_msg_pic, CommandObjectID, handle_send ) from .riftconfig import get_rift_config, savef_rift from .jsondata import save_rift_data, read_rift_data @@ -31,7 +31,7 @@ config = get_rift_config() -sql_message = XiuxianDateManage() # sql类 + # sql类 cache_help = {} group_rift = {} # dict groups = config['open'] # list @@ -44,16 +44,18 @@ create_rift = on_fullmatch("生成秘境", priority=5, permission=GROUP and (SUPERUSER | GROUP_ADMIN | GROUP_OWNER), block=True) complete_rift = on_command("秘境结算", aliases={"结算秘境"}, priority=7, permission=GROUP, block=True) break_rift = on_command("秘境探索终止", aliases={"终止探索秘境"}, priority=7, permission=GROUP, block=True) +close_rift = on_fullmatch("关闭秘境", priority=5, permission=GROUP and (SUPERUSER | GROUP_ADMIN | GROUP_OWNER), block=True) -__rift_help__ = f""" +__rift_help__ = """ 秘境帮助信息: 指令: 1、群秘境开启、关闭:开启本群的秘境生成,管理员权限 2、生成秘境:生成一个随机秘境,管理员权限 -3、探索秘境:探索秘境获取随机奖励 -4、秘境结算、结算秘境:结算秘境奖励 -5、秘境探索终止、终止探索秘境:终止秘境事件 -6、秘境帮助:获取秘境帮助信息 +3、关闭秘境:关闭当前群内已有的秘境,管理员权限 +4、探索秘境:探索秘境获取随机奖励 +5、秘境结算、结算秘境:结算秘境奖励 +6、秘境探索终止、终止探索秘境:终止秘境事件 +7、秘境帮助:获取秘境帮助信息 非指令: 1、每天早八生成一个随机等级的秘境 """.strip() @@ -63,13 +65,13 @@ async def read_rift_(): global group_rift group_rift.update(old_rift_info.read_rift_info()) - logger.opt(colors=True).info(f"历史rift数据读取成功") + logger.opt(colors=True).info("历史rift数据读取成功") @DRIVER.on_shutdown async def save_rift_(): global group_rift old_rift_info.save_rift(group_rift) - logger.opt(colors=True).info(f"rift数据已保存") + logger.opt(colors=True).info("rift数据已保存") # 定时任务生成群秘境 @set_rift.scheduled_job("cron", hour=8, minute=0) @@ -118,20 +120,12 @@ async def create_rift_(bot: Bot, event: GroupMessageEvent): group_id = str(event.group_id) if group_id not in groups: msg = '本群尚未开启秘境,请联系管理员开启群秘境' - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await create_rift.finish() try: msg = f"当前已存在{group_rift[group_id].name},秘境可探索次数:{group_rift[group_id].count}次,请诸位道友发送 探索秘境 来加入吧!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await create_rift.finish() except KeyError: rift = Rift() @@ -141,11 +135,7 @@ async def create_rift_(bot: Bot, event: GroupMessageEvent): rift.time = config['rift'][rift.name]['time'] group_rift[group_id] = rift msg = f"野生的{rift.name}出现了!秘境可探索次数:{rift.count}次,请诸位道友发送 探索秘境 来加入吧!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await create_rift.finish() @@ -153,51 +143,31 @@ async def create_rift_(bot: Bot, event: GroupMessageEvent): async def _(bot: Bot, event: GroupMessageEvent): """探索秘境""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await explore_rift.finish() user_id = user_info['user_id'] - is_type, msg = check_user_type(user_id, 0) # 需要无状态的用户 + is_type, msg = await check_user_type(user_id, 0) # 需要无状态的用户 if not is_type: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await explore_rift.finish() else: group_id = str(event.group_id) if group_id not in groups: msg = '本群尚未开启秘境,请联系管理员开启群秘境' - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await explore_rift.finish() try: group_rift[group_id] - except: + except ValueError: msg = '野外秘境尚未生成,请道友耐心等待!' - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await explore_rift.finish() if user_id in group_rift[group_id].l_user_id: msg = '道友已经参加过本次秘境啦,请把机会留给更多的道友!' - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await explore_rift.finish() user_rank = convert_rank(user_info["level"])[0] @@ -208,11 +178,7 @@ async def _(bot: Bot, event: GroupMessageEvent): rank_name_list = convert_rank(user_info["level"])[1] required_rank_name = rank_name_list[len(rank_name_list) - required_rank - 1] msg = f"秘境凶险万分,道友的境界不足,无法进入秘境:{group_rift[group_id].name},请道友提升到{required_rank_name}以上再来!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await explore_rift.finish() group_rift[group_id].l_user_id.append(user_id) @@ -225,22 +191,14 @@ async def _(bot: Bot, event: GroupMessageEvent): } save_rift_data(user_id, rift_data) - sql_message.do_work(user_id, 3, rift_data["time"]) + await XiuxianDataManager().do_work(user_id, 3, rift_data["time"]) if group_rift[group_id].count == 0: del group_rift[group_id] logger.opt(colors=True).info(f"群{group_id}秘境已到上限次数!") msg += "秘境随着道友的进入,已无法再维持更多的人,而关闭了!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await explore_rift.finish() - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await explore_rift.finish() @@ -248,13 +206,9 @@ async def _(bot: Bot, event: GroupMessageEvent): async def complete_rift_(bot: Bot, event: GroupMessageEvent): """秘境结算""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await complete_rift.finish() user_id = user_info['user_id'] @@ -262,57 +216,41 @@ async def complete_rift_(bot: Bot, event: GroupMessageEvent): group_id = str(event.group_id) if group_id not in groups: msg = '本群尚未开启秘境,请联系管理员开启群秘境' - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await complete_rift.finish() - is_type, msg = check_user_type(user_id, 3) # 需要在秘境的用户 + is_type, msg = await check_user_type(user_id, 3) # 需要在秘境的用户 if not is_type: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await complete_rift.finish() else: rift_info = None try: rift_info = read_rift_data(user_id) - except: + except ValueError: msg = '发生未知错误!' - sql_message.do_work(user_id, 0) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await XiuxianDataManager().do_work(user_id, 0) + await handle_send(bot, event, send_group_id, msg) await complete_rift.finish() - user_cd_message = sql_message.get_user_cd(user_id) + user_cd_message = await XiuxianDataManager().get_user_time(user_id) work_time = datetime.strptime( - user_cd_message['create_time'], "%Y-%m-%d %H:%M:%S.%f" + user_cd_message['schedule_create_time'], "%Y-%m-%d %H:%M:%S.%" ) exp_time = (datetime.now() - work_time).seconds // 60 # 时长计算 time2 = rift_info["time"] if exp_time < time2: msg = f"进行中的:{rift_info['name']}探索,预计{time2 - exp_time}分钟后可结束" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await complete_rift.finish() else: # 秘境结算逻辑 - sql_message.do_work(user_id, 0) + await XiuxianDataManager().do_work(user_id, 0) rift_rank = rift_info["rank"] # 秘境等级 rift_type = get_story_type() # 无事、宝物、战斗 if rift_type == "无事": msg = random.choice(NONEMSG) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -322,7 +260,7 @@ async def complete_rift_(bot: Bot, event: GroupMessageEvent): if rift_type == "掉血事件": msg = get_dxsj_info("掉血事件", user_info) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -331,7 +269,7 @@ async def complete_rift_(bot: Bot, event: GroupMessageEvent): result, msg = await get_boss_battle_info(user_info, rift_rank, bot.self_id) await send_msg_handler(bot, event, result) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -339,7 +277,7 @@ async def complete_rift_(bot: Bot, event: GroupMessageEvent): elif rift_type == "宝物": msg = get_treasure_info(user_info, rift_rank) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -350,55 +288,35 @@ async def complete_rift_(bot: Bot, event: GroupMessageEvent): async def break_rift_(bot: Bot, event: GroupMessageEvent): """终止探索秘境""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await break_rift.finish() user_id = user_info['user_id'] group_id = str(event.group_id) if group_id not in groups: msg = '本群尚未开启秘境,请联系管理员开启群秘境' - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await break_rift.finish() - is_type, msg = check_user_type(user_id, 3) # 需要在秘境的用户 + is_type, msg = await check_user_type(user_id, 3) # 需要在秘境的用户 if not is_type: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await break_rift.finish() else: user_id = user_info['user_id'] rift_info = None try: rift_info = read_rift_data(user_id) - except: + except ValueError: msg = '发生未知错误!' - sql_message.do_work(user_id, 0) - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await XiuxianDataManager().do_work(user_id, 0) + await handle_send(bot, event, send_group_id, msg) await break_rift.finish() - sql_message.do_work(user_id, 0) + await XiuxianDataManager().do_work(user_id, 0) msg = f"已终止{rift_info['name']}秘境的探索!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await break_rift.finish() @@ -412,54 +330,76 @@ async def set_group_rift_(bot: Bot, event: GroupMessageEvent, args: Message = Co if mode == '开启': if is_in_group: - msg = f"本群已开启群秘境,请勿重复开启!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "本群已开启群秘境,请勿重复开启!" + await handle_send(bot, event, send_group_id, msg) await set_group_rift.finish() else: config['open'].append(group_id) savef_rift(config) - msg = f"已开启本群秘境!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "已开启本群秘境!" + await handle_send(bot, event, send_group_id, msg) await set_group_rift.finish() elif mode == '关闭': if is_in_group: config['open'].remove(group_id) savef_rift(config) - msg = f"已关闭本群秘境!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "已关闭本群秘境!" + await handle_send(bot, event, send_group_id, msg) await set_group_rift.finish() else: - msg = f"本群未开启群秘境!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "本群未开启群秘境!" + await handle_send(bot, event, send_group_id, msg) await set_group_rift.finish() else: msg = __rift_help__ - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await set_group_rift.finish() def is_in_groups(event: GroupMessageEvent): return str(event.group_id) in groups + + +@close_rift.handle(parameterless=[Cooldown(at_sender=False)]) +async def close_rift_(bot: Bot, event: GroupMessageEvent): + """关闭当前群内秘境""" + bot, send_group_id = await assign_bot(bot=bot, event=event) + group_id = str(event.group_id) + + if group_id not in groups: + msg = '本群尚未开启秘境系统,请联系管理员开启群秘境' + await handle_send(bot, event, send_group_id, msg) + await close_rift.finish() + + # 检查是否有秘境存在 + try: + current_rift = group_rift[group_id] + except KeyError: + msg = '当前群内没有秘境,无需关闭' + await handle_send(bot, event, send_group_id, msg) + await close_rift.finish() + + # 检查是否有修仙者在秘境中 + users_in_rift = [] + for user_id in current_rift.l_user_id: + user_cd_message = await XiuxianDataManager().get_user_time(user_id) + if user_cd_message: + if user_cd_message['type'] == 3: # 类型3表示在秘境中 + users_in_rift.append(user_id) + + if users_in_rift: + msg = f'当前有{len(users_in_rift)}位道友正在探索秘境中,无法关闭秘境。请等待他们结算完毕后再关闭。' + await handle_send(bot, event, send_group_id, msg) + await close_rift.finish() + + # 关闭秘境 + rift_name = current_rift.name + del group_rift[group_id] + logger.opt(colors=True).info(f"群{group_id}的{rift_name}秘境被管理员手动关闭") + + msg = f"秘境【{rift_name}】已被管理员关闭!" + await handle_send(bot, event, send_group_id, msg) + await close_rift.finish() diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_rift/old_rift_info.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_rift/old_rift_info.py index 3ce0b41f..8697882f 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_rift/old_rift_info.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_rift/old_rift_info.py @@ -12,7 +12,7 @@ def __init__(self): try: with open(self.data_path, 'r', encoding='utf-8') as f: self.data = json.load(f) - except: + except FileNotFoundError: self.info = {} data = json.dumps(self.info, ensure_ascii=False, indent=4) with open(self.data_path, mode="x", encoding="UTF-8") as f: diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_rift/riftconfig.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_rift/riftconfig.py index 9e79511f..2419de58 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_rift/riftconfig.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_rift/riftconfig.py @@ -74,7 +74,7 @@ def get_rift_config(): if key not in list(config.keys()): config[key] = CONFIG[key] savef_rift(config) - except: + except FileNotFoundError: config = CONFIG savef_rift(config) return config diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_rift/riftmake.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_rift/riftmake.py index cafe3917..957dee8f 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_rift/riftmake.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_rift/riftmake.py @@ -2,13 +2,12 @@ from .riftconfig import get_rift_config from ..xiuxian_utils.xiuxian2_handle import OtherSet from .jsondata import read_f -from ..xiuxian_utils.xiuxian2_handle import XiuxianDateManage, UserBuffDate, XIUXIAN_IMPART_BUFF +from ..xiuxian_utils.xiuxian2_handle import XiuxianDataManager, UserBuffData from ..xiuxian_utils.player_fight import Boss_fight from ..xiuxian_utils.item_json import Items from ..xiuxian_config import convert_rank -sql_message = XiuxianDateManage() -xiuxian_impart = XIUXIAN_IMPART_BUFF() + items = Items() skill_data = read_f() @@ -68,7 +67,7 @@ }, "灵石": { "type_rate": 100, - "stone": 500000 + "stone": 50000 } }, "战斗": { @@ -85,7 +84,7 @@ "desc": "道友大战一番成功战胜{}!", "give": { "exp": [0.01, 0.02, 0.03, 0.04, 0.05, 0.07, 0.09], - "stone": 500000 + "stone": 50000 } }, "fail": { @@ -109,7 +108,7 @@ }, "stone": { "type_rate": 50, - "value": [5000000, 10000000, 15000000] + "value": [500000, 1000000, 1500000] }, } }, @@ -124,23 +123,23 @@ async def get_boss_battle_info(user_info, rift_rank, bot_id): """获取Boss战事件的内容""" boss_data = STORY['战斗']['Boss战斗']["Boss数据"] player = {"user_id": None, "道号": None, "气血": None, "攻击": None, "真元": None, '会心': None, '防御': 0} - userinfo = sql_message.get_user_real_info(user_info['user_id']) - user1_weapon_data = UserBuffDate(user_info['user_id']).get_user_weapon_data() - user_armor_data = UserBuffDate(user_info['user_id']).get_user_armor_buff_data()#秘境战斗防具会心 - user_main_crit_data = UserBuffDate(user_info['user_id']).get_user_main_buff_data() #秘境战斗功法会心 + userinfo = await XiuxianDataManager().get_user_real_info(user_info['user_id']) + user1_weapon_data = await UserBuffData(user_info['user_id']).get_user_weapon_data() + user_armor_data = await UserBuffData(user_info['user_id']).get_user_armor_buff_data()#秘境战斗防具会心 + user_main_crit_data = await UserBuffData(user_info['user_id']).get_user_main_buff_data() #秘境战斗功法会心 if user_main_crit_data is not None: #秘境战斗功法会心 - main_crit_buff = ((user_main_crit_data['crit_buff']) * 100) + main_crit_buff = ((user_main_crit_data['crit_buf']) * 100) else: main_crit_buff = 0 - if user_armor_data != None: #秘境战斗防具会心 - armor_crit_buff = user_armor_data['crit_buff'] + if user_armor_data is not None: #秘境战斗防具会心 + armor_crit_buff = user_armor_data['crit_buf'] else: armor_crit_buff = 0 if user1_weapon_data is not None: - player['会心'] = int(((user1_weapon_data['crit_buff']) + armor_crit_buff + main_crit_buff) * 100) + player['会心'] = int(((user1_weapon_data['crit_buf']) + armor_crit_buff + main_crit_buff) * 100) else: player['会心'] = (armor_crit_buff + main_crit_buff) * 100 @@ -171,8 +170,8 @@ async def get_boss_battle_info(user_info, rift_rank, bot_id): msg = success_info['desc'].format(boss_info['name']) give_exp = int(random.choice(success_info["give"]["exp"]) * user_info['exp']) give_stone = (rift_rank + user_rank) * success_info["give"]["stone"] - sql_message.update_exp(user_info['user_id'], give_exp) - sql_message.update_ls(user_info['user_id'], give_stone, 1) # 负数也挺正常 + await XiuxianDataManager().update_exp(user_info['user_id'], give_exp, 0) + await XiuxianDataManager().update_ls(user_info['user_id'], give_stone, 0) # 负数也挺正常 msg += f"获得了修为:{give_exp}点,灵石:{give_stone}枚!" else: # 输了 fail_info = STORY['战斗']['Boss战斗']["fail"] @@ -180,7 +179,7 @@ async def get_boss_battle_info(user_info, rift_rank, bot_id): return result, msg -def get_dxsj_info(rift_type, user_info): +async def get_dxsj_info(rift_type, user_info): """获取掉血事件的内容""" msg = None battle_data = STORY['战斗'] @@ -188,11 +187,11 @@ def get_dxsj_info(rift_type, user_info): value = random.choice(battle_data[rift_type]['cost'][cost_type]['value']) if cost_type == "exp": exp = int(user_info['exp'] * value) - sql_message.update_j_exp(user_info['user_id'], exp) + await XiuxianDataManager().update_exp(user_info['user_id'], exp, 1) nowhp = user_info['hp'] - (exp / 2) if (user_info['hp'] - (exp / 2)) > 0 else 1 nowmp = user_info['mp'] - exp if (user_info['mp'] - exp) > 0 else 1 - sql_message.update_user_hp_mp(user_info['user_id'], nowhp, nowmp) # 修为掉了,血量、真元也要掉 + await XiuxianDataManager().update_user_hp_mp(user_info['user_id'], nowhp, nowmp) # 修为掉了,血量、真元也要掉 msg = random.choice(battle_data[rift_type]['desc']).format(f"修为减少了:{exp}点!") elif cost_type == "hp": @@ -200,40 +199,40 @@ def get_dxsj_info(rift_type, user_info): now_hp = user_info['hp'] - cost_hp if now_hp < 0: now_hp = 1 - sql_message.update_user_hp_mp(user_info['user_id'], now_hp, user_info['mp']) + await XiuxianDataManager().update_user_hp_mp(user_info['user_id'], now_hp, user_info['mp']) msg = random.choice(battle_data[rift_type]['desc']).format(f"气血减少了:{cost_hp}点!") elif cost_type == "stone": cost_stone = value - sql_message.update_ls(user_info['user_id'], cost_stone, 2) # 负数也挺正常 + await XiuxianDataManager().update_ls(user_info['user_id'], cost_stone, 1) # 负数也挺正常 msg = random.choice(battle_data[rift_type]['desc']).format(f"灵石减少了:{cost_stone}枚!") return msg -def get_treasure_info(user_info, rift_rank): +async def get_treasure_info(user_info, rift_rank): rift_type = get_goods_type() # 功法、神通、法器、防具、法宝#todo msg = None if rift_type == "法器": weapon_info = get_weapon(user_info, rift_rank) temp_msg = f"{weapon_info[1]['level']}:{weapon_info[1]['name']}!" msg = random.choice(TREASUREMSG).format(temp_msg) - sql_message.send_back(user_info['user_id'], weapon_info[0], weapon_info[1]['name'], weapon_info[1]['type'], 1, 1) + await XiuxianDataManager().send_back(user_info['user_id'], weapon_info[0], weapon_info[1]['name'], weapon_info[1]['type'], 1, 1) # 背包sql elif rift_type == "防具": # todo armor_info = get_armor(user_info, rift_rank) temp_msg = f"{armor_info[1]['level']}防具:{armor_info[1]['name']}!" msg = random.choice(TREASUREMSG_1).format(temp_msg) - sql_message.send_back(user_info['user_id'], armor_info[0], armor_info[1]['name'], armor_info[1]['type'], 1, 1) + await XiuxianDataManager().send_back(user_info['user_id'], armor_info[0], armor_info[1]['name'], armor_info[1]['type'], 1, 1) # 背包sql elif rift_type == "功法": give_main_info = get_main_info(user_info['level'], rift_rank) if give_main_info[0]: # 获得了 main_buff_id = give_main_info[1] - main_buff = items.get_data_by_item_id(main_buff_id) - temp_msg = f"{main_buff['level']}功法:{main_buff['name']}" + main_skill = items.get_data_by_item_id(main_buff_id) + temp_msg = f"{main_skill['level']}功法:{main_skill['name']}" msg = random.choice(TREASUREMSG_2).format(temp_msg) - sql_message.send_back(user_info['user_id'], main_buff_id, main_buff['name'], main_buff['type'], 1, 1) + await XiuxianDataManager().send_back(user_info['user_id'], main_buff_id, main_skill['name'], main_skill['type'], 1, 1) else: msg = '道友在秘境中获得一本书籍,翻开一看居然是绿野仙踪...' @@ -241,10 +240,10 @@ def get_treasure_info(user_info, rift_rank): give_sec_info = get_sec_info(user_info['level'], rift_rank) if give_sec_info[0]: # 获得了 sec_buff_id = give_sec_info[1] - sec_buff = items.get_data_by_item_id(sec_buff_id) - temp_msg = f"{sec_buff['level']}神通:{sec_buff['name']}!" + ultimate_skill = items.get_data_by_item_id(sec_buff_id) + temp_msg = f"{ultimate_skill['level']}神通:{ultimate_skill['name']}!" msg = random.choice(TREASUREMSG_3).format(temp_msg) - sql_message.send_back(user_info['user_id'], sec_buff_id, sec_buff['name'], sec_buff['type'], 1, 1) + await XiuxianDataManager().send_back(user_info['user_id'], sec_buff_id, ultimate_skill['name'], ultimate_skill['type'], 1, 1) # 背包sql else: msg = '道友在秘境中获得一本书籍,翻开一看居然是金瓶梅...' @@ -253,10 +252,10 @@ def get_treasure_info(user_info, rift_rank): give_sub_info = get_sub_info(user_info['level'], rift_rank) if give_sub_info[0]: # 获得了 sub_buff_id = give_sub_info[1] - sub_buff = items.get_data_by_item_id(sub_buff_id) - temp_msg = f"{sub_buff['level']}辅修功法:{sub_buff['name']}!" + support_skill = items.get_data_by_item_id(sub_buff_id) + temp_msg = f"{support_skill['level']}辅修功法:{support_skill['name']}!" msg = random.choice(TREASUREMSG_5).format(temp_msg) - sql_message.send_back(user_info['user_id'], sub_buff_id, sub_buff['name'], sub_buff['type'], 1, 1) + await XiuxianDataManager().send_back(user_info['user_id'], sub_buff_id, support_skill['name'], support_skill['type'], 1, 1) # 背包sql else: msg = '道友在秘境中获得一本书籍,翻开一看居然是四库全书...' @@ -266,7 +265,7 @@ def get_treasure_info(user_info, rift_rank): stone_base = STORY['宝物']['灵石']['stone'] user_rank = random.randint(1, 10) # 随机等级 give_stone = (rift_rank + user_rank) * stone_base - sql_message.update_ls(user_info['user_id'], give_stone, 1) + await XiuxianDataManager().update_ls(user_info['user_id'], give_stone, 0) temp_msg = f"竟然获得了灵石:{give_stone}枚!" msg = random.choice(TREASUREMSG_4).format(temp_msg) @@ -280,7 +279,7 @@ def get_dict_type_rate(data_dict): for i, v in data_dict.items(): try: temp_dict[i] = v["type_rate"] - except: + except ValueError: continue key = OtherSet().calculated(temp_dict) return key diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_sect/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_sect/__init__.py index e883726d..e6bb199c 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_sect/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_sect/__init__.py @@ -1,8 +1,8 @@ import re import random from ..xiuxian_utils.xiuxian2_handle import ( - XiuxianDateManage, OtherSet, BuffJsonDate, - get_main_info_msg, UserBuffDate, get_sec_msg + XiuxianDataManager, OtherSet, BuffJsonData, + get_main_info_msg, UserBuffData, get_sec_msg ) from nonebot import on_command, on_fullmatch, require from nonebot.log import logger @@ -23,16 +23,15 @@ from ..xiuxian_utils.utils import ( check_user, number_to, get_msg_pic, send_msg_handler, CommandObjectID, - Txt2Img + Txt2Img, handle_send ) from ..xiuxian_utils.item_json import Items items = Items() -sql_message = XiuxianDateManage() # sql类 + # sql类 config = get_config() LEVLECOST = config["LEVLECOST"] cache_help = {} -userstask = {} buffrankkey = { "人阶下品": 1, @@ -104,58 +103,65 @@ # 定时任务每1小时按照宗门贡献度增加资材 @materialsupdate.scheduled_job("cron", hour=config["发放宗门资材"]["时间"]) async def materialsupdate_(): - all_sects = sql_message.get_all_sects_id_scale() + all_sects = await XiuxianDataManager().get_all_sects_id_scale() for s in all_sects: - sql_message.update_sect_materials(sect_id=s[0], sect_materials=s[1] * config["发放宗门资材"]["倍率"], key=1) + await XiuxianDataManager().update_sect_material(sect_id=s[0], sect_materials=s[1] * config["发放宗门资材"]["倍率"], key=0) - logger.opt(colors=True).info(f"已更新所有宗门的资材") + logger.opt(colors=True).info("已更新所有宗门的资材") # 每日0点重置用户宗门任务次数、宗门丹药领取次数 @resetusertask.scheduled_job("cron", hour=0, minute=0) async def resetusertask_(): - sql_message.sect_task_reset() - sql_message.sect_elixir_get_num_reset() - all_sects = sql_message.get_all_sects_id_scale() + await XiuxianDataManager().sect_task_reset() + await XiuxianDataManager().sect_elixir_get_num_reset() + all_sects = await XiuxianDataManager().get_all_sects_id_scale() for s in all_sects: - sect_info = sql_message.get_sect_info(s[0]) - if int(sect_info['elixir_room_level']) != 0: - elixir_room_cost = config['宗门丹房参数']['elixir_room_level'][str(sect_info['elixir_room_level'])]['level_up_cost'][ + sect_info = await XiuxianDataManager().get_sect_info(s[0]) + if int(sect_info["sect_elixir_room_level"]) != 0: + elixir_room_cost = config['宗门丹房参数']["sect_elixir_room_level"][str(sect_info["sect_elixir_room_level"])]['level_up_cost'][ '建设度'] - if sect_info['sect_materials'] < elixir_room_cost: + if sect_info["sect_material"] < elixir_room_cost: logger.opt(colors=True).info(f"宗门:{sect_info['sect_name']}的资材无法维持丹房") continue else: - sql_message.update_sect_materials(sect_id=sect_info['sect_id'], sect_materials=elixir_room_cost, key=2) - logger.opt(colors=True).info(f"已重置所有宗门任务次数、宗门丹药领取次数,已扣除丹房维护费") + await XiuxianDataManager().update_sect_material(sect_id=sect_info['id'], sect_materials=elixir_room_cost, key=1) + logger.opt(colors=True).info("已重置所有宗门任务次数、宗门丹药领取次数,已扣除丹房维护费") # 定时任务每1小时自动检测不常玩的宗主 @auto_sect_owner_change.scheduled_job("interval", hours=1) async def auto_sect_owner_change_(): - logger.opt(colors=True).info(f"开始检测不常玩的宗主") + logger.opt(colors=True).info("开始检测不常玩的宗主") - all_sect_owners_id = sql_message.get_sect_owners() - all_active = all(sql_message.get_last_check_info_time(owner_id) is None or - datetime.now() - sql_message.get_last_check_info_time(owner_id) < timedelta(days=XiuConfig().auto_change_sect_owner_cd) - for owner_id in all_sect_owners_id) + all_sect_owners_id = await XiuxianDataManager().get_sect_owners() + + # 列表推导式 + check_results = [] + for owner_id in all_sect_owners_id: + last_check_time = await XiuxianDataManager().get_last_check_info_time(owner_id) + is_active = (last_check_time is None or + datetime.now() - last_check_time < timedelta(days=XiuConfig().auto_change_sect_owner_cd)) + check_results.append(is_active) + + all_active = all(check_results) if all_active: - logger.opt(colors=True).info(f"各宗宗主在修行之途上勤勉不辍,宗门安危无忧,可喜可贺!") + logger.opt(colors=True).info("各宗宗主在修行之途上勤勉不辍,宗门安危无忧,可喜可贺!") for owner_id in all_sect_owners_id: - last_check_time = sql_message.get_last_check_info_time(owner_id) + last_check_time = await XiuxianDataManager().get_last_check_info_time(owner_id) if last_check_time is None or datetime.now() - last_check_time < timedelta(days=XiuConfig().auto_change_sect_owner_cd): continue - user_info = sql_message.get_user_info_with_id(owner_id) + user_info = await XiuxianDataManager().get_user_infos_by_ids(owner_id) sect_id = user_info['sect_id'] logger.opt(colors=True).info(f"{user_info['user_name']}离线时间超过{XiuConfig().auto_change_sect_owner_cd}天,开始自动换宗主") - new_owner_id = sql_message.get_highest_contrib_user_except_current(sect_id, owner_id) - new_owner_info = sql_message.get_user_info_with_id(new_owner_id[0]) + new_owner_id = await XiuxianDataManager().get_highest_contrib_active_user_except_current(sect_id, owner_id) + new_owner_info = await XiuxianDataManager().get_user_infos_by_ids(new_owner_id[0]) - sql_message.update_usr_sect(owner_id, sect_id, 1) - sql_message.update_usr_sect(new_owner_id[0], sect_id, 0) - sql_message.update_sect_owner(new_owner_id[0], sect_id) - sect_info = sql_message.get_sect_info_by_id(sect_id) + await XiuxianDataManager().update_ussr_sect_info(owner_id, sect_id, 1) + await XiuxianDataManager().update_ussr_sect_info(new_owner_id[0], sect_id, 0) + await XiuxianDataManager().update_sect_owner(new_owner_id[0], sect_id) + sect_info = await XiuxianDataManager().get_sect_info_by_id(sect_id) logger.opt(colors=True).info(f"由{new_owner_info['user_name']}继承{sect_info['sect_name']}宗主之位") @@ -184,13 +190,9 @@ async def sect_help_(bot: Bot, event: GroupMessageEvent, session_id: int = Comma async def sect_elixir_room_make_(bot: Bot, event: GroupMessageEvent): """宗门丹房建设""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_elixir_room_make.finish() sect_id = user_info['sect_id'] if sect_id: @@ -199,13 +201,13 @@ async def sect_elixir_room_make_(bot: Bot, event: GroupMessageEvent): owner_position = int(owner_idx[0]) if len(owner_idx) == 1 else 0 if sect_position == owner_position: elixir_room_config = config['宗门丹房参数'] - elixir_room_level_up_config = elixir_room_config['elixir_room_level'] - sect_info = sql_message.get_sect_info(sect_id) - elixir_room_level = sect_info['elixir_room_level'] # 宗门丹房等级 + elixir_room_level_up_config = elixir_room_config["sect_elixir_room_level"] + sect_info = await XiuxianDataManager().get_sect_info(sect_id) + elixir_room_level = sect_info["sect_elixir_room_level"] # 宗门丹房等级 if int(elixir_room_level) == len(elixir_room_level_up_config): - msg = f"宗门丹房等级已经达到最高等级,无法继续建设了!" + msg = "宗门丹房等级已经达到最高等级,无法继续建设了!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -214,10 +216,10 @@ async def sect_elixir_room_make_(bot: Bot, event: GroupMessageEvent): elixir_room_level_up_sect_scale_cost = elixir_room_level_up_config[str(to_up_level)]['level_up_cost']['建设度'] elixir_room_level_up_use_stone_cost = elixir_room_level_up_config[str(to_up_level)]['level_up_cost'][ 'stone'] - if elixir_room_level_up_use_stone_cost > int(sect_info['sect_used_stone']): + if elixir_room_level_up_use_stone_cost > int(sect_info['sect_stone']): msg = f"宗门可用灵石不满足升级条件,当前升级需要消耗宗门灵石:{elixir_room_level_up_use_stone_cost}枚!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -225,7 +227,7 @@ async def sect_elixir_room_make_(bot: Bot, event: GroupMessageEvent): elif elixir_room_level_up_sect_scale_cost > int(sect_info['sect_scale']): msg = f"宗门建设度不满足升级条件,当前升级需要消耗宗门建设度:{elixir_room_level_up_sect_scale_cost}点!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -233,31 +235,23 @@ async def sect_elixir_room_make_(bot: Bot, event: GroupMessageEvent): else: msg = f"宗门消耗:{elixir_room_level_up_sect_scale_cost}建设度,{elixir_room_level_up_use_stone_cost}宗门灵石\n" msg += f"成功升级宗门丹房,当前丹房为:{elixir_room_level_up_config[str(to_up_level)]['name']}!" - sql_message.update_sect_scale_and_used_stone(sect_id, - sect_info['sect_used_stone'] - elixir_room_level_up_use_stone_cost, + await XiuxianDataManager().update_sect_scale_and_used_stone(sect_id, + sect_info['sect_stone'] - elixir_room_level_up_use_stone_cost, sect_info['sect_scale'] - elixir_room_level_up_sect_scale_cost) - sql_message.update_sect_elixir_room_level(sect_id, to_up_level) + await XiuxianDataManager().update_sect_elixir_room_level(sect_id, to_up_level) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_elixir_room_make.finish() else: - msg = f"道友不是宗主,无法使用该命令!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友不是宗主,无法使用该命令!" + await handle_send(bot, event, send_group_id, msg) await sect_elixir_room_make.finish() else: - msg = f"道友尚未加入宗门!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友尚未加入宗门!" + await handle_send(bot, event, send_group_id, msg) await sect_elixir_room_make.finish() @@ -265,35 +259,27 @@ async def sect_elixir_room_make_(bot: Bot, event: GroupMessageEvent): async def sect_elixir_get_(bot: Bot, event: GroupMessageEvent): """宗门丹药领取""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_elixir_get.finish() sect_id = user_info['sect_id'] user_id = user_info['user_id'] - sql_message.update_last_check_info_time(user_id) # 更新查看修仙信息时间 + await XiuxianDataManager().update_last_check_info_time(user_id) # 更新查看修仙信息时间 if sect_id: sect_position = user_info['sect_position'] elixir_room_config = config['宗门丹房参数'] if sect_position == 4: - msg = f"""道友所在宗门的职位为:{jsondata.sect_config_data()[f"{sect_position}"]['title']},不满足领取要求!""" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = """道友所在宗门的职位为:{jsondata.sect_config_data()[f"{sect_position}"]['title']},不满足领取要求!""" + await handle_send(bot, event, send_group_id, msg) await sect_elixir_get.finish() else: - sect_info = sql_message.get_sect_info(sect_id) - if int(sect_info['elixir_room_level']) == 0: - msg = f"道友的宗门目前还未建设丹房!" + sect_info = await XiuxianDataManager().get_sect_info(sect_id) + if int(sect_info["sect_elixir_room_level"]) == 0: + msg = "道友的宗门目前还未建设丹房!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -301,52 +287,52 @@ async def sect_elixir_get_(bot: Bot, event: GroupMessageEvent): if int(user_info['sect_contribution']) < elixir_room_config['领取贡献度要求']: msg = f"道友的宗门贡献度不满足领取条件,当前宗门贡献度要求:{elixir_room_config['领取贡献度要求']}点!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_elixir_get.finish() - elixir_room_level_up_config = elixir_room_config['elixir_room_level'] - elixir_room_cost = elixir_room_level_up_config[str(sect_info['elixir_room_level'])]['level_up_cost']['建设度'] - if sect_info['sect_materials'] < elixir_room_cost: + elixir_room_level_up_config = elixir_room_config["sect_elixir_room_level"] + elixir_room_cost = elixir_room_level_up_config[str(sect_info["sect_elixir_room_level"])]['level_up_cost']['建设度'] + if sect_info["sect_material"] < elixir_room_cost: msg = f"当前宗门资材无法维护丹房,请等待{config['发放宗门资材']['时间']}点发放宗门资材后尝试领取!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_elixir_get.finish() - if int(user_info['sect_elixir_get']) == 1: - msg = f"道友已经领取过了,不要贪心哦~" + if int(user_info['is_elixir']) == 1: + msg = "道友已经领取过了,不要贪心哦~" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_elixir_get.finish() - if int(sect_info['elixir_room_level']) == 1: - msg = f"道友成功领取到丹药:渡厄丹!" - sql_message.send_back(user_info['user_id'], 1999, "渡厄丹", "丹药", 1, 1) # 1级丹房送1个渡厄丹 - sql_message.update_user_sect_elixir_get_num(user_info['user_id']) + if int(sect_info["sect_elixir_room_level"]) == 1: + msg = "道友成功领取到丹药:渡厄丹 3 枚!" + await XiuxianDataManager().send_back(user_info['user_id'], 1999, "渡厄丹", "丹药", 3, 1) # 1级丹房送1个渡厄丹 + await XiuxianDataManager().update_user_sect_elixir_get_num(user_info['user_id']) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_elixir_get.finish() else: - sect_now_room_config = elixir_room_level_up_config[str(sect_info['elixir_room_level'])] + sect_now_room_config = elixir_room_level_up_config[str(sect_info["sect_elixir_room_level"])] give_num = sect_now_room_config['give_level']['give_num'] - 1 rank_up = sect_now_room_config['give_level']['rank_up'] give_dict = {} give_elixir_id_list = items.get_random_id_list_by_rank_and_item_type( fanil_rank=convert_rank(user_info['level'])[0] - rank_up, item_type=['丹药']) if not give_elixir_id_list: # 没有合适的ID,全部给渡厄丹 - msg = f"道友成功领取到丹药:渡厄丹 2 枚!" - sql_message.send_back(user_info['user_id'], 1999, "渡厄丹", "丹药", 2, 1) # 送1个渡厄丹 - sql_message.update_user_sect_elixir_get_num(user_info['user_id']) + msg = "道友成功领取到丹药:渡厄丹 3 枚!" + await XiuxianDataManager().send_back(user_info['user_id'], 1999, "渡厄丹", "丹药", 3, 1) # 送1个渡厄丹 + await XiuxianDataManager().update_user_sect_elixir_get_num(user_info['user_id']) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -360,29 +346,25 @@ async def sect_elixir_get_(bot: Bot, event: GroupMessageEvent): try: give_dict[id] += 1 i += 1 - except: + except KeyError: give_dict[id] = 1 i += 1 - msg = f"道友成功领取到丹药:渡厄丹 1 枚!\n" - sql_message.send_back(user_info['user_id'], 1999, "渡厄丹", "丹药", 1, 1) # 送1个渡厄丹 + msg = "道友成功领取到丹药:渡厄丹 5 枚!\n" + await XiuxianDataManager().send_back(user_info['user_id'], 1999, "渡厄丹", "丹药", 5, 1) # 送1个渡厄丹 for k, v in give_dict.items(): goods_info = items.get_data_by_item_id(k) msg += f"道友成功领取到丹药:{goods_info['name']} {v} 枚!\n" - sql_message.send_back(user_info['user_id'], k, goods_info['name'], '丹药', v, bind_flag=1) - sql_message.update_user_sect_elixir_get_num(user_info['user_id']) + await XiuxianDataManager().send_back(user_info['user_id'], k, goods_info['name'], '丹药', v, bind_flag=1) + await XiuxianDataManager().update_user_sect_elixir_get_num(user_info['user_id']) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_elixir_get.finish() else: - msg = f"道友尚未加入宗门!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友尚未加入宗门!" + await handle_send(bot, event, send_group_id, msg) await sect_elixir_get.finish() @@ -390,31 +372,23 @@ async def sect_elixir_get_(bot: Bot, event: GroupMessageEvent): async def sect_buff_info_(bot: Bot, event: GroupMessageEvent): """宗门功法查看""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_buff_info.finish() sect_id = user_info['sect_id'] if sect_id: - sect_info = sql_message.get_sect_info(sect_id) - if sect_info['mainbuff'] == 0 and sect_info['secbuff'] == 0: - msg = f"本宗尚未获得任何功法、神通,请宗主发送宗门功法、神通搜寻来获得!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + sect_info = await XiuxianDataManager().get_sect_info(sect_id) + if sect_info['sect_main_skill'] == 0 and sect_info['sect_ultimate_skill'] == 0: + msg = "本宗尚未获得任何功法、神通,请宗主发送宗门功法、神通搜寻来获得!" + await handle_send(bot, event, send_group_id, msg) await sect_buff_info.finish() list_tp = [] msg = "" - if sect_info['mainbuff'] != 0: - mainbufflist = get_sect_mainbuff_id_list(sect_id) - main_msg = f"\n☆------宗门功法------☆\n" + if sect_info['sect_main_skill'] != 0: + mainbufflist = await get_sect_mainbuff_id_list(sect_id) + main_msg = "\n☆------宗门功法------☆\n" msg += main_msg list_tp.append( {"type": "node", "data": {"name": f"道友{user_info['user_name']}的宗门功法信息", "uin": bot.self_id, @@ -427,9 +401,9 @@ async def sect_buff_info_(bot: Bot, event: GroupMessageEvent): {"type": "node", "data": {"name": f"道友{user_info['user_name']}的宗门秘籍信息", "uin": bot.self_id, "content": mainmsg}}) - if sect_info['secbuff'] != 0: - secbufflist = get_sect_secbuff_id_list(sect_id) - sec_msg = f"☆------宗门神通------☆\n" + if sect_info['sect_ultimate_skill'] != 0: + secbufflist = await get_sect_secbuff_id_list(sect_id) + sec_msg = "☆------宗门神通------☆\n" msg += sec_msg list_tp.append( {"type": "node", "data": {"name": f"道友{user_info['user_name']}的宗门神通信息", "uin": bot.self_id, @@ -445,20 +419,12 @@ async def sect_buff_info_(bot: Bot, event: GroupMessageEvent): try: await send_msg_handler(bot, event, list_tp) except ActionFailed: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_buff_info.finish() await sect_buff_info.finish() else: - msg = f"道友尚未加入宗门!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友尚未加入宗门!" + await handle_send(bot, event, send_group_id, msg) await sect_buff_info.finish() @@ -466,13 +432,9 @@ async def sect_buff_info_(bot: Bot, event: GroupMessageEvent): async def sect_mainbuff_learn_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """学习宗门功法""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_mainbuff_learn.finish() msg = args.extract_plain_text().strip() sect_id = user_info['sect_id'] @@ -480,40 +442,36 @@ async def sect_mainbuff_learn_(bot: Bot, event: GroupMessageEvent, args: Message sect_position = user_info['sect_position'] if sect_position == 4: msg = f"""道友所在宗门的职位为:{jsondata.sect_config_data()[f"{sect_position}"]["title"]},不满足学习要求!""" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_mainbuff_learn.finish() else: - sect_info = sql_message.get_sect_info(sect_id) - if sect_info['mainbuff'] == 0: - msg = f"本宗尚未获得宗门功法,请宗主发送宗门功法搜寻来获得宗门功法!" + sect_info = await XiuxianDataManager().get_sect_info(sect_id) + if sect_info['sect_main_skill'] == 0: + msg = "本宗尚未获得宗门功法,请宗主发送宗门功法搜寻来获得宗门功法!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_mainbuff_learn.finish() - sectmainbuffidlist = get_sect_mainbuff_id_list(sect_id) + sectmainbuffidlist = await get_sect_mainbuff_id_list(sect_id) if msg not in get_mainname_list(sectmainbuffidlist): - msg = f"本宗还没有该功法,请发送本宗有的功法进行学习!" + msg = "本宗还没有该功法,请发送本宗有的功法进行学习!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_mainbuff_learn.finish() - userbuffinfo = UserBuffDate(user_info['user_id']).BuffInfo + userbuffinfo = await UserBuffData(user_info['user_id']).BuffInfo mainbuffid = get_mainnameid(msg, sectmainbuffidlist) - if str(userbuffinfo['main_buff']) == str(mainbuffid): - msg = f"道友请勿重复学习!" + if str(userbuffinfo['main_skill']) == str(mainbuffid): + msg = "道友请勿重复学习!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -525,13 +483,13 @@ async def sect_mainbuff_learn_(bot: Bot, event: GroupMessageEvent, args: Message mainbuffgear = buffrankkey[mainbufftype] # 获取逻辑 materialscost = mainbuffgear * mainbuffconfig['学习资材消耗'] - if sect_info['sect_materials'] >= materialscost: - sql_message.update_sect_materials(sect_id, materialscost, 2) - sql_message.updata_user_main_buff(user_info['user_id'], mainbuffid) + if sect_info["sect_material"] >= materialscost: + await XiuxianDataManager().update_sect_material(sect_id, materialscost, 1) + await XiuxianDataManager().updata_user_main_buff(user_info['user_id'], mainbuffid) mainbuff, mainbuffmsg = get_main_info_msg(str(mainbuffid)) msg = f"本次学习消耗{materialscost}宗门资材,成功学习到本宗{mainbufftype}功法:{mainbuff['name']}\n{mainbuffmsg}" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -539,18 +497,14 @@ async def sect_mainbuff_learn_(bot: Bot, event: GroupMessageEvent, args: Message else: msg = f"本次学习需要消耗{materialscost}宗门资材,不满足条件!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_mainbuff_learn.finish() else: - msg = f"道友尚未加入宗门!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友尚未加入宗门!" + await handle_send(bot, event, send_group_id, msg) await sect_mainbuff_learn.finish() @@ -558,13 +512,9 @@ async def sect_mainbuff_learn_(bot: Bot, event: GroupMessageEvent, args: Message async def sect_mainbuff_get_(bot: Bot, event: GroupMessageEvent): """搜寻宗门功法""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_mainbuff_get.finish() sect_id = user_info['sect_id'] if sect_id: @@ -573,23 +523,24 @@ async def sect_mainbuff_get_(bot: Bot, event: GroupMessageEvent): owner_position = int(owner_idx[0]) if len(owner_idx) == 1 else 0 if sect_position == owner_position: mainbuffconfig = config['宗门主功法参数'] - sect_info = sql_message.get_sect_info(sect_id) + sect_info = await XiuxianDataManager().get_sect_info(sect_id) mainbuffgear, mainbufftype = get_sectbufftxt(sect_info['sect_scale'], mainbuffconfig) stonecost = mainbuffgear * mainbuffconfig['获取消耗的灵石'] materialscost = mainbuffgear * mainbuffconfig['获取消耗的资材'] total_stone_cost = stonecost total_materials_cost = materialscost - if sect_info['sect_used_stone'] >= total_stone_cost and sect_info['sect_materials'] >= total_materials_cost: + if sect_info['sect_stone'] >= total_stone_cost and sect_info["sect_material"] >= total_materials_cost: success_count = 0 fail_count = 0 repeat_count = 0 - mainbuffidlist = get_sect_mainbuff_id_list(sect_id) + mainbuffidlist = await get_sect_mainbuff_id_list(sect_id) + print("mainbuffidlist", mainbuffidlist) results = [] for i in range(100): if random.randint(0, 100) <= mainbuffconfig['获取到功法的概率']: - mainbuffid = random.choice(BuffJsonDate().get_gfpeizhi()[mainbufftype]['gf_list']) + mainbuffid = int(random.choice(BuffJsonData().get_gfpeizhi()[mainbufftype]['gf_list'])) if mainbuffid in mainbuffidlist: mainbuff, mainbuffmsg = get_main_info_msg(mainbuffid) repeat_count += 1 @@ -602,21 +553,21 @@ async def sect_mainbuff_get_(bot: Bot, event: GroupMessageEvent): else: fail_count += 1 - sql_message.update_sect_materials(sect_id, total_materials_cost, 2) - sql_message.update_sect_scale_and_used_stone(sect_id, sect_info['sect_used_stone'] - total_stone_cost, sect_info['sect_scale']) + await XiuxianDataManager().update_sect_material(sect_id, total_materials_cost, 1) + await XiuxianDataManager().update_sect_scale_and_used_stone(sect_id, sect_info['sect_stone'] - total_stone_cost, sect_info['sect_scale']) sql = set_sect_list(mainbuffidlist) - sql_message.update_sect_mainbuff(sect_id, sql) + await XiuxianDataManager().update_sect_mainbuff(sect_id, sql) msg = f"共消耗{total_stone_cost}宗门灵石,{total_materials_cost}宗门资材。\n" msg += f"失败{fail_count}次,获取重复功法{repeat_count}次" if success_count > 0: msg += f",搜寻到新功法{success_count}次。\n" else: - msg += f",未搜寻到新功法!\n" - msg += f"\n".join(results) + msg += ",未搜寻到新功法!\n" + msg += "\n".join(results) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -624,26 +575,18 @@ async def sect_mainbuff_get_(bot: Bot, event: GroupMessageEvent): else: msg = f"需要消耗{total_stone_cost}宗门灵石,{total_materials_cost}宗门资材,不满足条件!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_mainbuff_get.finish() else: - msg = f"道友不是宗主,无法使用该命令!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友不是宗主,无法使用该命令!" + await handle_send(bot, event, send_group_id, msg) await sect_mainbuff_get.finish() else: - msg = f"道友尚未加入宗门!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友尚未加入宗门!" + await handle_send(bot, event, send_group_id, msg) await sect_mainbuff_get.finish() @@ -651,13 +594,9 @@ async def sect_mainbuff_get_(bot: Bot, event: GroupMessageEvent): async def sect_secbuff_get_(bot: Bot, event: GroupMessageEvent): """搜寻宗门神通""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_secbuff_get.finish() sect_id = user_info['sect_id'] if sect_id: @@ -666,23 +605,23 @@ async def sect_secbuff_get_(bot: Bot, event: GroupMessageEvent): owner_position = int(owner_idx[0]) if len(owner_idx) == 1 else 0 if sect_position == owner_position: secbuffconfig = config['宗门神通参数'] - sect_info = sql_message.get_sect_info(sect_id) + sect_info = await XiuxianDataManager().get_sect_info(sect_id) secbuffgear, secbufftype = get_sectbufftxt(sect_info['sect_scale'], secbuffconfig) stonecost = secbuffgear * secbuffconfig['获取消耗的灵石'] materialscost = secbuffgear * secbuffconfig['获取消耗的资材'] total_stone_cost = stonecost total_materials_cost = materialscost - if sect_info['sect_used_stone'] >= total_stone_cost and sect_info['sect_materials'] >= total_materials_cost: + if sect_info['sect_stone'] >= total_stone_cost and sect_info["sect_material"] >= total_materials_cost: success_count = 0 fail_count = 0 repeat_count = 0 - secbuffidlist = get_sect_secbuff_id_list(sect_id) + secbuffidlist = await get_sect_secbuff_id_list(sect_id) results = [] for i in range(100): if random.randint(0, 100) <= secbuffconfig['获取到神通的概率']: - secbuffid = random.choice(BuffJsonDate().get_gfpeizhi()[secbufftype]['st_list']) + secbuffid = int(random.choice(BuffJsonData().get_gfpeizhi()[secbufftype]['st_list'])) if secbuffid in secbuffidlist: secbuff = items.get_data_by_item_id(secbuffid) repeat_count += 1 @@ -695,21 +634,21 @@ async def sect_secbuff_get_(bot: Bot, event: GroupMessageEvent): else: fail_count += 1 - sql_message.update_sect_materials(sect_id, total_materials_cost, 2) - sql_message.update_sect_scale_and_used_stone(sect_id, sect_info['sect_used_stone'] - total_stone_cost, sect_info['sect_scale']) + await XiuxianDataManager().update_sect_material(sect_id, total_materials_cost, 1) + await XiuxianDataManager().update_sect_scale_and_used_stone(sect_id, sect_info['sect_stone'] - total_stone_cost, sect_info['sect_scale']) sql = set_sect_list(secbuffidlist) - sql_message.update_sect_secbuff(sect_id, sql) + await XiuxianDataManager().update_sect_secbuff(sect_id, sql) msg = f"共消耗{total_stone_cost}宗门灵石,{total_materials_cost}宗门资材。\n" msg += f"失败{fail_count}次,获取重复神通{repeat_count}次" if success_count > 0: msg += f",搜寻到新神通{success_count}次。\n" else: - msg += f",未搜寻到新神通!\n" - msg += f"\n".join(results) + msg += ",未搜寻到新神通!\n" + msg += "\n".join(results) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -717,26 +656,18 @@ async def sect_secbuff_get_(bot: Bot, event: GroupMessageEvent): else: msg = f"需要消耗{total_stone_cost}宗门灵石,{total_materials_cost}宗门资材,不满足条件!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_secbuff_get.finish() else: - msg = f"道友不是宗主,无法使用该命令!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友不是宗主,无法使用该命令!" + await handle_send(bot, event, send_group_id, msg) await sect_secbuff_get.finish() else: - msg = f"道友尚未加入宗门!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友尚未加入宗门!" + await handle_send(bot, event, send_group_id, msg) await sect_secbuff_get.finish() @@ -744,13 +675,9 @@ async def sect_secbuff_get_(bot: Bot, event: GroupMessageEvent): async def sect_secbuff_learn_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """学习宗门神通""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_secbuff_learn.finish() msg = args.extract_plain_text().strip() sect_id = user_info['sect_id'] @@ -758,41 +685,37 @@ async def sect_secbuff_learn_(bot: Bot, event: GroupMessageEvent, args: Message sect_position = user_info['sect_position'] if sect_position == 4: msg = f"""道友所在宗门的职位为:{jsondata.sect_config_data()[f"{sect_position}"]['title']},不满足学习要求!""" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_secbuff_learn.finish() else: - sect_info = sql_message.get_sect_info(sect_id) - if sect_info['secbuff'] == 0: - msg = f"本宗尚未获得宗门神通,请宗主发送宗门神通搜寻来获得宗门神通!" + sect_info = await XiuxianDataManager().get_sect_info(sect_id) + if sect_info['sect_ultimate_skill'] == 0: + msg = "本宗尚未获得宗门神通,请宗主发送宗门神通搜寻来获得宗门神通!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_secbuff_learn.finish() - sectsecbuffidlist = get_sect_secbuff_id_list(sect_id) + sectsecbuffidlist = await get_sect_secbuff_id_list(sect_id) if msg not in get_secname_list(sectsecbuffidlist): - msg = f"本宗还没有该神通,请发送本宗有的神通进行学习!" + msg = "本宗还没有该神通,请发送本宗有的神通进行学习!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_secbuff_learn.finish() - userbuffinfo = UserBuffDate(user_info['user_id']).BuffInfo + userbuffinfo = await UserBuffData(user_info['user_id']).BuffInfo secbuffid = get_secnameid(msg, sectsecbuffidlist) - if str(userbuffinfo['sec_buff']) == str(secbuffid): - msg = f"道友请勿重复学习!" + if str(userbuffinfo['ultimate_skill']) == str(secbuffid): + msg = "道友请勿重复学习!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -805,13 +728,13 @@ async def sect_secbuff_learn_(bot: Bot, event: GroupMessageEvent, args: Message secbuffgear = buffrankkey[secbufftype] # 获取逻辑 materialscost = secbuffgear * secbuffconfig['学习资材消耗'] - if sect_info['sect_materials'] >= materialscost: - sql_message.update_sect_materials(sect_id, materialscost, 2) - sql_message.updata_user_sec_buff(user_info['user_id'], secbuffid) + if sect_info["sect_material"] >= materialscost: + await XiuxianDataManager().update_sect_material(sect_id, materialscost, 1) + await XiuxianDataManager().updata_user_sec_buff(user_info['user_id'], secbuffid) secmsg = get_sec_msg(secbuff) msg = f"本次学习消耗{materialscost}宗门资材,成功学习到本宗{secbufftype}神通:{secbuff['name']}\n{secbuff['name']}:{secmsg}" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -819,18 +742,14 @@ async def sect_secbuff_learn_(bot: Bot, event: GroupMessageEvent, args: Message else: msg = f"本次学习需要消耗{materialscost}宗门资材,不满足条件!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_secbuff_learn.finish() else: - msg = f"道友尚未加入宗门!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友尚未加入宗门!" + await handle_send(bot, event, send_group_id, msg) await sect_secbuff_learn.finish() @@ -838,13 +757,9 @@ async def sect_secbuff_learn_(bot: Bot, event: GroupMessageEvent, args: Message async def upatkpractice_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """升级攻击修炼""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await upatkpractice.finish() user_id = user_info['user_id'] sect_id = user_info['sect_id'] @@ -857,39 +772,27 @@ async def upatkpractice_(bot: Bot, event: GroupMessageEvent, args: Message = Com except ValueError: level_up_count = 1 if sect_id: - sect_materials = int(sql_message.get_sect_info(sect_id)['sect_materials']) # 当前资材 - useratkpractice = int(user_info['atkpractice']) # 当前等级 + sect_materials = int((await XiuxianDataManager().get_sect_info(sect_id))["sect_material"]) # 当前资材 + useratkpractice = int(user_info['atk_practice_level']) # 当前等级 if useratkpractice == 50: - msg = f"道友的攻击修炼等级已达到最高等级!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友的攻击修炼等级已达到最高等级!" + await handle_send(bot, event, send_group_id, msg) await upatkpractice.finish() - sect_level = get_sect_level(sect_id)[0] if get_sect_level(sect_id)[ + sect_level = (await get_sect_level(sect_id))[0] if (await get_sect_level(sect_id))[ 0] <= 50 else 50 # 获取当前宗门修炼等级上限,500w建设度1级,上限25级 sect_position = user_info['sect_position'] # 确保用户不会尝试升级超过宗门等级的上限 level_up_count = min(level_up_count, sect_level - useratkpractice) if sect_position == 4: - msg = f"""道友所在宗门的职位为:{jsondata.sect_config_data()[f"{sect_position}"]["title"]},不满足使用资材的条件!""" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = """道友所在宗门的职位为:{jsondata.sect_config_data()[f"{sect_position}"]["title"]},不满足使用资材的条件!""" + await handle_send(bot, event, send_group_id, msg) await upatkpractice.finish() if useratkpractice >= sect_level: msg = f"道友的攻击修炼等级已达到当前宗门修炼等级的最高等级:{sect_level},请捐献灵石提升贡献度吧!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await upatkpractice.finish() total_stone_cost = sum(LEVLECOST[str(useratkpractice + i)] for i in range(level_up_count)) @@ -897,39 +800,23 @@ async def upatkpractice_(bot: Bot, event: GroupMessageEvent, args: Message = Com if int(user_info['stone']) < total_stone_cost: msg = f"道友的灵石不够,升级到攻击修炼等级 {useratkpractice + level_up_count} 还需 {total_stone_cost - int(user_info['stone'])} 灵石!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await upatkpractice.finish() if sect_materials < total_materials_cost: msg = f"道友的所处的宗门资材不足,还需 {total_materials_cost - sect_materials} 资材来升级到攻击修炼等级 {useratkpractice + level_up_count}!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await upatkpractice.finish() - sql_message.update_ls(user_id, total_stone_cost, 2) - sql_message.update_sect_materials(sect_id, total_materials_cost, 2) - sql_message.update_user_atkpractice(user_id, useratkpractice + level_up_count) + await XiuxianDataManager().update_ls(user_id, total_stone_cost, 1) + await XiuxianDataManager().update_sect_material(sect_id, total_materials_cost, 1) + await XiuxianDataManager().update_user_atkpractice(user_id, useratkpractice + level_up_count) msg = f"升级成功,道友当前攻击修炼等级:{useratkpractice + level_up_count},消耗灵石:{total_stone_cost}枚,消耗宗门资材{total_materials_cost}!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await upatkpractice.finish() else: - msg = f"修炼逆天而行消耗巨大,请加入宗门再进行修炼!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "修炼逆天而行消耗巨大,请加入宗门再进行修炼!" + await handle_send(bot, event, send_group_id, msg) await upatkpractice.finish() @@ -937,42 +824,26 @@ async def upatkpractice_(bot: Bot, event: GroupMessageEvent, args: Message = Com async def sect_task_refresh_(bot: Bot, event: GroupMessageEvent): """刷新宗门任务""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_task_refresh.finish() user_id = user_info['user_id'] sect_id = user_info['sect_id'] if sect_id: - if isUserTask(user_id): - create_user_sect_task(user_id) - msg = f"已刷新,道友当前接取的任务:{userstask[user_id]['任务名称']}\n{userstask[user_id]['任务内容']['desc']}" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + if await isUserTask(user_id): + await create_user_sect_task(user_id) + task = await XiuxianDataManager().get_sect_task(user_id) + msg = f"已刷新,道友当前接取的任务:{task['task_name']}\n{task['task_desc']}" + await handle_send(bot, event, send_group_id, msg) await sect_task_refresh.finish() else: - msg = f"道友目前还没有宗门任务,请发送指令宗门任务接取来获取吧" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友目前还没有宗门任务,请发送指令宗门任务接取来获取吧" + await handle_send(bot, event, send_group_id, msg) await sect_task_refresh.finish() - else: - msg = f"道友尚未加入宗门,请加入宗门后再发送该指令!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友尚未加入宗门,请加入宗门后再发送该指令!" + await handle_send(bot, event, send_group_id, msg) await sect_task_refresh.finish() @@ -980,7 +851,7 @@ async def sect_task_refresh_(bot: Bot, event: GroupMessageEvent): async def sect_list_(bot: Bot, event: GroupMessageEvent): """宗门列表:当前为返回转发内容""" bot, send_group_id = await assign_bot(bot=bot, event=event) - sect_lists_with_members = sql_message.get_all_sects_with_member_count() + sect_lists_with_members = await XiuxianDataManager().get_all_sects_with_member_count() msg_list = [] for sect in sect_lists_with_members: @@ -996,19 +867,15 @@ async def sect_users_(bot: Bot, event: GroupMessageEvent): """查看所在宗门成员信息""" bot, send_group_id = await assign_bot(bot=bot, event=event) msg_list = [] - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_users.finish() if user_info: sect_id = user_info['sect_id'] if sect_id: - sect_info = sql_message.get_sect_info(sect_id) - userlist = sql_message.get_all_users_by_sect_id(sect_id) + sect_info = await XiuxianDataManager().get_sect_info(sect_id) + userlist = await XiuxianDataManager().get_all_users_by_sect_id(sect_id) msg = f"☆【{sect_info['sect_name']}】的成员信息☆\n" msg_list.append(msg) i = 1 @@ -1018,9 +885,9 @@ async def sect_users_(bot: Bot, event: GroupMessageEvent): msg_list.append(msg) i += 1 else: - msg_list.append(f"一介散修,莫要再问。") + msg_list.append("一介散修,莫要再问。") else: - msg_list.append(f"未曾踏入修仙世界,输入【我要修仙】加入我们,看破这世间虚妄!") + msg_list.append("未曾踏入修仙世界,输入【我要修仙】加入我们,看破这世间虚妄!") await send_msg_handler(bot, event, '宗门成员', bot.self_id, msg_list) await sect_users.finish() @@ -1029,51 +896,33 @@ async def sect_users_(bot: Bot, event: GroupMessageEvent): async def sect_task_(bot: Bot, event: GroupMessageEvent): """获取宗门任务""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_task.finish() user_id = user_info['user_id'] sect_id = user_info['sect_id'] if sect_id: - user_now_num = int(user_info['sect_task']) + user_now_num = int(user_info['sect_task_quantity']) if user_now_num >= config["每日宗门任务次上限"]: msg = f"道友已完成{user_now_num}次,今日无法再获取宗门任务了!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_task.finish() - if isUserTask(user_id): # 已有任务 - msg = f"道友当前已接取了任务:{userstask[user_id]['任务名称']}\n{userstask[user_id]['任务内容']['desc']}" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + if await isUserTask(user_id): # 已有任务 + task = await XiuxianDataManager().get_sect_task(user_id) + msg = f"道友当前已接取了任务:{task['task_name']}\n{task['task_desc']}" + await handle_send(bot, event, send_group_id, msg) await sect_task.finish() - create_user_sect_task(user_id) - msg = f"{userstask[user_id]['任务内容']['desc']}" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await create_user_sect_task(user_id) + task = await XiuxianDataManager().get_sect_task(user_id) + msg = f"{task['task_desc']}" + await handle_send(bot, event, send_group_id, msg) await sect_task.finish() else: - msg = f"道友尚未加入宗门,请加入宗门后再获取任务!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友尚未加入宗门,请加入宗门后再获取任务!" + await handle_send(bot, event, send_group_id, msg) await sect_task.finish() @@ -1081,41 +930,35 @@ async def sect_task_(bot: Bot, event: GroupMessageEvent): async def sect_task_complete_(bot: Bot, event: GroupMessageEvent): """完成宗门任务""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_task_complete.finish() user_id = user_info['user_id'] sect_id = user_info['sect_id'] if sect_id: - if not isUserTask(user_id): - msg = f"道友当前没有接取宗门任务,道友浪费了一次出门机会哦!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + if not await isUserTask(user_id): + msg = "道友当前没有接取宗门任务,道友浪费了一次出门机会哦!" + await handle_send(bot, event, send_group_id, msg) await sect_task_complete.finish() - if userstask[user_id]['任务内容']['type'] == 1: # type=1:需要扣气血,type=2:需要扣灵石 - costhp = int((user_info['exp'] / 2) * userstask[user_id]['任务内容']['cost']) + task = await XiuxianDataManager().get_sect_task(user_id) + + if task['task_type'] == 1: # type=1:需要扣气血,type=2:需要扣灵石 + costhp = int((user_info['exp'] / 2) * task['task_cost']) if user_info['hp'] < user_info['exp'] / 10 or costhp >= user_info['hp']: msg = ( - f"道友兴高采烈的出门做任务,结果状态欠佳,没过两招就力不从心,坚持不住了," - f"道友只好原路返回,浪费了一次出门机会,看你这么可怜,就不扣你任务次数了!" + "道友兴高采烈的出门做任务,结果状态欠佳,没过两招就力不从心,坚持不住了," + "道友只好原路返回,浪费了一次出门机会,看你这么可怜,就不扣你任务次数了!" ) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_task_complete.finish() - get_exp = int(user_info['exp'] * userstask[user_id]['任务内容']['give']) + get_exp = int(user_info['exp'] * task['task_give']) if user_info['sect_position'] is None: max_exp_limit = 4 @@ -1124,41 +967,37 @@ async def sect_task_complete_(bot: Bot, event: GroupMessageEvent): max_exp = jsondata.sect_config_data()[str(max_exp_limit)]["max_exp"] if get_exp >= max_exp: get_exp = max_exp - max_exp_next = int((int(OtherSet().set_closing_type(user_info['level'])) * XiuConfig().closing_exp_upper_limit)) # 获取下个境界需要的修为 * 1.5为闭关上限 + max_exp_next = int((int(await OtherSet().set_closing_type(user_info['level'])) * XiuConfig().closing_exp_upper_limit)) # 获取下个境界需要的修为 * 1.5为闭关上限 if int(get_exp + user_info['exp']) > max_exp_next: get_exp = 1 - msg = f"检测到修为将要到达上限!" - sect_stone = int(userstask[user_id]['任务内容']['sect']) - sql_message.update_user_hp_mp(user_id, user_info['hp'] - costhp, user_info['mp']) - sql_message.update_exp(user_id, get_exp) - sql_message.donate_update(user_info['sect_id'], sect_stone) - sql_message.update_sect_materials(sect_id, sect_stone * 10, 1) - sql_message.update_user_sect_task(user_id, 1) - sql_message.update_user_sect_contribution(user_id, user_info['sect_contribution'] + int(sect_stone)) - msg += f"道友大战一番,气血减少:{costhp},获得修为:{get_exp},所在宗门建设度增加:{sect_stone},资材增加:{sect_stone * 10}, 宗门贡献度增加:{int(sect_stone)}" - userstask[user_id] = {} - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "检测到修为将要到达上限!" + sect_stone = int(task['task_sect']) + await XiuxianDataManager().update_user_hp_mp(user_id, user_info['hp'] - costhp, user_info['mp']) + await XiuxianDataManager().update_exp(user_id, get_exp, 0) + await XiuxianDataManager().donate_update(user_info['sect_id'], sect_stone) + await XiuxianDataManager().update_sect_material(sect_id, sect_stone * 10, 0) + await XiuxianDataManager().update_user_sect_task(user_id, 1) + await XiuxianDataManager().update_user_sect_contribution(user_id, user_info['sect_contribution'] + int(sect_stone)) + await XiuxianDataManager().delete_sect_task(user_id) + msg += f"道友大战一番,气血减少:{number_to(costhp)},获得修为:{number_to(get_exp)},所在宗门建设度增加:{number_to(sect_stone)},资材增加:{number_to(sect_stone * 10)}, 宗门贡献度增加:{number_to(int(sect_stone))}" + await handle_send(bot, event, send_group_id, msg) await sect_task_complete.finish() - elif userstask[user_id]['任务内容']['type'] == 2: # type=1:需要扣气血,type=2:需要扣灵石 - costls = userstask[user_id]['任务内容']['cost'] + elif task['task_type'] == 2: # type=1:需要扣气血,type=2:需要扣灵石 + costls = task['task_cost'] if costls > int(user_info['stone']): msg = ( f"道友兴高采烈的出门做任务,结果发现灵石带少了,当前任务所需灵石:{costls}," - f"道友只好原路返回,浪费了一次出门机会,看你这么可怜,就不扣你任务次数了!") + "道友只好原路返回,浪费了一次出门机会,看你这么可怜,就不扣你任务次数了!") if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_task_complete.finish() - get_exp = int(user_info['exp'] * userstask[user_id]['任务内容']['give']) + get_exp = int(user_info['exp'] * task['task_give']) if user_info['sect_position'] is None: max_exp_limit = 4 @@ -1167,32 +1006,24 @@ async def sect_task_complete_(bot: Bot, event: GroupMessageEvent): max_exp = jsondata.sect_config_data()[str(max_exp_limit)]["max_exp"] if get_exp >= max_exp: get_exp = max_exp - max_exp_next = int((int(OtherSet().set_closing_type(user_info['level'])) * XiuConfig().closing_exp_upper_limit)) # 获取下个境界需要的修为 * 1.5为闭关上限 + max_exp_next = int((int(await OtherSet().set_closing_type(user_info['level'])) * XiuConfig().closing_exp_upper_limit)) # 获取下个境界需要的修为 * 1.5为闭关上限 if int(get_exp + user_info['exp']) > max_exp_next: get_exp = 1 - msg = f"检测到修为将要到达上限!" - sect_stone = int(userstask[user_id]['任务内容']['sect']) - sql_message.update_ls(user_id, costls, 2) - sql_message.update_exp(user_id, get_exp) - sql_message.donate_update(user_info['sect_id'], sect_stone) - sql_message.update_sect_materials(sect_id, sect_stone * 10, 1) - sql_message.update_user_sect_task(user_id, 1) - sql_message.update_user_sect_contribution(user_id, user_info['sect_contribution'] + int(sect_stone)) - msg = f"道友为了完成任务购买宝物消耗灵石:{costls}枚,获得修为:{get_exp},所在宗门建设度增加:{sect_stone},资材增加:{sect_stone * 10}, 宗门贡献度增加:{int(sect_stone)}" - userstask[user_id] = {} - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "检测到修为将要到达上限!" + sect_stone = int(task['task_sect']) + await XiuxianDataManager().update_ls(user_id, costls, 1) + await XiuxianDataManager().update_exp(user_id, get_exp, 0) + await XiuxianDataManager().donate_update(user_info['sect_id'], sect_stone) + await XiuxianDataManager().update_sect_material(sect_id, sect_stone * 10, 0) + await XiuxianDataManager().update_user_sect_task(user_id, 1) + await XiuxianDataManager().update_user_sect_contribution(user_id, user_info['sect_contribution'] + int(sect_stone)) + await XiuxianDataManager().delete_sect_task(user_id) + msg = f"道友为了完成任务购买宝物消耗灵石:{number_to(costls)}枚,获得修为:{number_to(get_exp)},所在宗门建设度增加:{number_to(sect_stone)},资材增加:{number_to(sect_stone * 10)}, 宗门贡献度增加:{number_to(int(sect_stone))}" + await handle_send(bot, event, send_group_id, msg) await sect_task_complete.finish() else: - msg = f"道友尚未加入宗门,请加入宗门后再完成任务,但你申请出门的机会我已经用小本本记下来了!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友尚未加入宗门,请加入宗门后再完成任务,但你申请出门的机会我已经用小本本记下来了!" + await handle_send(bot, event, send_group_id, msg) await sect_task_complete.finish() @@ -1200,33 +1031,21 @@ async def sect_task_complete_(bot: Bot, event: GroupMessageEvent): async def sect_owner_change_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """宗主传位""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) enabled_groups = JsonConfig().get_enabled_groups() if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_owner_change.finish() user_id = user_info['user_id'] if not user_info['sect_id']: - msg = f"道友还未加入一方宗门。" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友还未加入一方宗门。" + await handle_send(bot, event, send_group_id, msg) await sect_owner_change.finish() position_this = [k for k, v in jsondata.sect_config_data().items() if v.get("title", "") == "宗主"] owner_position = int(position_this[0]) if len(position_this) == 1 else 0 if user_info['sect_position'] != owner_position: - msg = f"只有宗主才能进行传位。" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "只有宗主才能进行传位。" + await handle_send(bot, event, send_group_id, msg) await sect_owner_change.finish() give_qq = None # 艾特的时候存到这里 for arg in args: @@ -1234,20 +1053,16 @@ async def sect_owner_change_(bot: Bot, event: GroupMessageEvent, args: Message = give_qq = arg.data.get("qq", "") if give_qq: if give_qq == user_id: - msg = f"无法对自己的进行传位操作。" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "无法对自己的进行传位操作。" + await handle_send(bot, event, send_group_id, msg) await sect_owner_change.finish() else: - give_user = sql_message.get_user_info_with_id(give_qq) + give_user = await XiuxianDataManager().get_user_infos_by_ids(give_qq) if give_user['sect_id'] == user_info['sect_id']: - sql_message.update_usr_sect(give_user['user_id'], give_user['sect_id'], owner_position) - sql_message.update_usr_sect(user_info['user_id'], user_info['sect_id'], owner_position + 1) - sect_info = sql_message.get_sect_info_by_id(give_user['sect_id']) - sql_message.update_sect_owner(give_user['user_id'], sect_info['sect_id']) + await XiuxianDataManager().update_ussr_sect_info(give_user['user_id'], give_user['sect_id'], owner_position) + await XiuxianDataManager().update_ussr_sect_info(user_info['user_id'], user_info['sect_id'], owner_position + 1) + sect_info = await XiuxianDataManager().get_sect_info_by_id(give_user['sect_id']) + await XiuxianDataManager().update_sect_owner(give_user['user_id'], sect_info['sect_id']) msg = f"传老宗主{user_info['user_name']}法旨,即日起由{give_user['user_name']}继任{sect_info['sect_name']}宗主" for group_id in enabled_groups: bot = await assign_bot_group(group_id=group_id) @@ -1263,18 +1078,14 @@ async def sect_owner_change_(bot: Bot, event: GroupMessageEvent, args: Message = else: msg = f"{give_user['user_name']}不在你管理的宗门内,请检查。" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_owner_change.finish() else: - msg = f"请按照规范进行操作,ex:宗主传位@XXX,将XXX道友(需在自己管理下的宗门)升为宗主,自己则变为宗主下一等职位。" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请按照规范进行操作,ex:宗主传位@XXX,将XXX道友(需在自己管理下的宗门)升为宗主,自己则变为宗主下一等职位。" + await handle_send(bot, event, send_group_id, msg) await sect_owner_change.finish() @@ -1282,78 +1093,50 @@ async def sect_owner_change_(bot: Bot, event: GroupMessageEvent, args: Message = async def sect_rename_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """宗门改名""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_rename.finish() if not user_info['sect_id']: - msg = f"道友还未加入一方宗门。" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友还未加入一方宗门。" + await handle_send(bot, event, send_group_id, msg) await sect_rename.finish() position_this = [k for k, v in jsondata.sect_config_data().items() if v.get("title", "") == "宗主"] owner_position = int(position_this[0]) if len(position_this) == 1 else 0 if user_info['sect_position'] != owner_position: - msg = f"只有宗主才能进行改名!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "只有宗主才能进行改名!" + await handle_send(bot, event, send_group_id, msg) await sect_rename.finish() else: update_sect_name = args.extract_plain_text().strip() sect_id = user_info['sect_id'] - sect_info = sql_message.get_sect_info(sect_id) + sect_info = await XiuxianDataManager().get_sect_info(sect_id) enabled_groups = JsonConfig().get_enabled_groups() len_sect_name = len(update_sect_name.encode('gbk')) if len_sect_name > 20: - msg = f"道友输入的宗门名字过长,请重新输入!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友输入的宗门名字过长,请重新输入!" + await handle_send(bot, event, send_group_id, msg) await sect_rename.finish() elif update_sect_name is None: - msg = f"道友确定要改名无名之宗门?还请三思。" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友确定要改名无名之宗门?还请三思。" + await handle_send(bot, event, send_group_id, msg) await sect_rename.finish() - elif sect_info['sect_used_stone'] < XiuConfig().sect_rename_cost: - msg = f"道友宗门灵石储备不足,还需{number_to(XiuConfig().sect_rename_cost - sect_info['sect_used_stone'])}灵石!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + elif sect_info['sect_stone'] < XiuConfig().sect_rename_cost: + msg = f"道友宗门灵石储备不足,还需{number_to(XiuConfig().sect_rename_cost - sect_info['sect_stone'])}灵石!" + await handle_send(bot, event, send_group_id, msg) await sect_rename.finish() - elif sql_message.update_sect_name(sect_id, update_sect_name) is False: - msg = f"已存在同名宗门(自己宗门名字一样的就不要改了),请重新输入!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + elif await XiuxianDataManager().update_sect_name(sect_id, update_sect_name) is False: + msg = "已存在同名宗门(自己宗门名字一样的就不要改了),请重新输入!" + await handle_send(bot, event, send_group_id, msg) await sect_rename.finish() else: - sql_message.update_sect_name(sect_id, update_sect_name) - sql_message.update_sect_used_stone(sect_id, XiuConfig().sect_rename_cost, 2) - msg = f""" + await XiuxianDataManager().update_sect_name(sect_id, update_sect_name) + await XiuxianDataManager().update_sect_stone(sect_id, XiuConfig().sect_rename_cost, 1) + msg = """ 传宗门——{sect_info['sect_name']} 宗主{user_info['user_name']}法旨: 宗门改名为{update_sect_name}! @@ -1379,14 +1162,10 @@ async def sect_rename_(bot: Bot, event: GroupMessageEvent, args: Message = Comma async def create_sect_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """创建宗门,对灵石、修为等级有要求,且需要当前状态无宗门""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - msg = f"区区凡人,也想创立万世仙门,大胆!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "区区凡人,也想创立万世仙门,大胆!" + await handle_send(bot, event, send_group_id, msg) await create_sect.finish() user_id = user_info['user_id'] # 首先判断是否满足创建宗门的三大条件 @@ -1403,20 +1182,16 @@ async def create_sect_(bot: Bot, event: GroupMessageEvent, args: Message = Comma # 获取宗门名称 sect_name = args.extract_plain_text().strip() if sect_name: - sql_message.create_sect(user_id, sect_name) - new_sect = sql_message.get_sect_info_by_qq(user_id) + await XiuxianDataManager().create_sect(user_id, sect_name) + new_sect = await XiuxianDataManager().get_sect_info_by_qq(user_id) owner_idx = [k for k, v in jsondata.sect_config_data().items() if v.get("title", "") == "宗主"] owner_position = int(owner_idx[0]) if len(owner_idx) == 1 else 0 - sql_message.update_usr_sect(user_id, new_sect['sect_id'], owner_position) - sql_message.update_ls(user_id, XiuConfig().sect_create_cost, 2) - msg = f"恭喜{user_info['user_name']}道友创建宗门——{sect_name},宗门编号为{new_sect['sect_id']}。为道友贺!为仙道贺!" + await XiuxianDataManager().update_ussr_sect_info(user_id, new_sect['id'], owner_position) + await XiuxianDataManager().update_ls(user_id, XiuConfig().sect_create_cost, 1) + msg = f"恭喜{user_info['user_name']}道友创建宗门——{sect_name},宗门编号为{new_sect['id']}。为道友贺!为仙道贺!" else: - msg = f"道友确定要创建无名之宗门?还请三思。" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友确定要创建无名之宗门?还请三思。" + await handle_send(bot, event, send_group_id, msg) await create_sect.finish() @@ -1424,22 +1199,14 @@ async def create_sect_(bot: Bot, event: GroupMessageEvent, args: Message = Comma async def sect_kick_out_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """踢出宗门""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_kick_out.finish() user_id = user_info['user_id'] if not user_info['sect_id']: - msg = f"道友还未加入一方宗门。" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友还未加入一方宗门。" + await handle_send(bot, event, send_group_id, msg) await sect_kick_out.finish() give_qq = None # 艾特的时候存到这里 for arg in args: @@ -1448,52 +1215,44 @@ async def sect_kick_out_(bot: Bot, event: GroupMessageEvent, args: Message = Com if bool(give_qq) is False: msg = args.extract_plain_text().strip() give_qq = re.findall(r"\d+", msg)[0] # QQ_ID - if sql_message.get_user_info_with_id(give_qq) is None: - msg = f"修仙界没有此人,请输入正确QQ_ID或正规at!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + if await XiuxianDataManager().get_user_infos_by_ids(give_qq) is None: + msg = "修仙界没有此人,请输入正确QQ_ID或正规at!" + await handle_send(bot, event, send_group_id, msg) await sect_kick_out.finish() if give_qq: if give_qq == user_id: - msg = f"无法对自己的进行踢出操作,试试退出宗门?" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "无法对自己的进行踢出操作,试试退出宗门?" + await handle_send(bot, event, send_group_id, msg) await sect_kick_out.finish() else: - give_user = sql_message.get_user_info_with_id(give_qq) + give_user = await XiuxianDataManager().get_user_infos_by_ids(give_qq) if give_user['sect_id'] == user_info['sect_id']: position_zhanglao = [k for k, v in jsondata.sect_config_data().items() if v.get("title", "") == "长老"] idx_position = int(position_zhanglao[0]) if len(position_zhanglao) == 1 else 1 if user_info['sect_position'] <= idx_position: if give_user['sect_position'] <= user_info['sect_position']: - msg = f"""{give_user['user_name']}的宗门职务为{jsondata.sect_config_data()[f"{give_user['sect_position']}"]['title']},不在你之下,无权操作。""" + msg = """{give_user['user_name']}的宗门职务为{jsondata.sect_config_data()[f"{give_user['sect_position']}"]['title']},不在你之下,无权操作。""" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_kick_out.finish() else: - sect_info = sql_message.get_sect_info_by_id(give_user['sect_id']) - sql_message.update_usr_sect(give_user['user_id'], None, None) - sql_message.update_user_sect_contribution(give_user['user_id'], 0) + sect_info = await XiuxianDataManager().get_sect_info_by_id(give_user['sect_id']) + await XiuxianDataManager().update_ussr_sect_info(give_user['user_id'], None, None) + await XiuxianDataManager().update_user_sect_contribution(give_user['user_id'], 0) msg = f"""传{jsondata.sect_config_data()[f"{user_info['sect_position']}"]['title']}{user_info['user_name']}法旨,即日起{give_user['user_name']}被{sect_info['sect_name']}除名""" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_kick_out.finish() else: - msg = f"""你的宗门职务为{jsondata.sect_config_data()[f"{user_info['sect_position']}"]['title']},只有长老及以上可执行踢出操作。""" + msg = """你的宗门职务为{jsondata.sect_config_data()[f"{user_info['sect_position']}"]['title']},只有长老及以上可执行踢出操作。""" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -1501,18 +1260,14 @@ async def sect_kick_out_(bot: Bot, event: GroupMessageEvent, args: Message = Com else: msg = f"{give_user['user_name']}不在你管理的宗门内,请检查。" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_kick_out.finish() else: - msg = f"请按照规范进行操作,ex:踢出宗门@XXX,将XXX道友(需在自己管理下的宗门)踢出宗门" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "请按照规范进行操作,ex:踢出宗门@XXX,将XXX道友(需在自己管理下的宗门)踢出宗门" + await handle_send(bot, event, send_group_id, msg) await sect_kick_out.finish() @@ -1520,44 +1275,28 @@ async def sect_kick_out_(bot: Bot, event: GroupMessageEvent, args: Message = Com async def sect_out_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """退出宗门""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_out.finish() user_id = user_info['user_id'] if not user_info['sect_id']: - msg = f"道友还未加入一方宗门。" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友还未加入一方宗门。" + await handle_send(bot, event, send_group_id, msg) await sect_out.finish() position_this = [k for k, v in jsondata.sect_config_data().items() if v.get("title", "") == "宗主"] owner_position = int(position_this[0]) if len(position_this) == 1 else 0 sect_out_id = user_info['sect_id'] if user_info['sect_position'] != owner_position: - sql_message.update_usr_sect(user_id, None, None) - sect_info = sql_message.get_sect_info_by_id(int(sect_out_id)) - sql_message.update_user_sect_contribution(user_id, 0) + await XiuxianDataManager().update_ussr_sect_info(user_id, None, None) + sect_info = await XiuxianDataManager().get_sect_info_by_id(int(sect_out_id)) + await XiuxianDataManager().update_user_sect_contribution(user_id, 0) msg = f"道友已退出{sect_info['sect_name']},今后就是自由散修,是福是祸,犹未可知。" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_out.finish() else: - msg = f"宗主无法直接退出宗门,如确有需要,请完成宗主传位后另行尝试。" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "宗主无法直接退出宗门,如确有需要,请完成宗主传位后另行尝试。" + await handle_send(bot, event, send_group_id, msg) await sect_out.finish() @@ -1565,52 +1304,32 @@ async def sect_out_(bot: Bot, event: GroupMessageEvent, args: Message = CommandA async def sect_donate_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """宗门捐献""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_donate.finish() user_id = user_info['user_id'] if not user_info['sect_id']: - msg = f"道友还未加入一方宗门。" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "道友还未加入一方宗门。" + await handle_send(bot, event, send_group_id, msg) await sect_donate.finish() msg = args.extract_plain_text().strip() donate_num = re.findall(r"\d+", msg) # 捐献灵石数 if len(donate_num) > 0: if int(donate_num[0]) > user_info['stone']: msg = f"道友的灵石数量小于欲捐献数量{int(donate_num[0])},请检查" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_donate.finish() else: - sql_message.update_ls(user_id, int(donate_num[0]), 2) - sql_message.donate_update(user_info['sect_id'], int(donate_num[0])) - sql_message.update_user_sect_contribution(user_id, user_info['sect_contribution'] + int(donate_num[0])) + await XiuxianDataManager().update_ls(user_id, int(donate_num[0]), 1) + await XiuxianDataManager().donate_update(user_info['sect_id'], int(donate_num[0])) + await XiuxianDataManager().update_user_sect_contribution(user_id, user_info['sect_contribution'] + int(donate_num[0])) msg = f"道友捐献灵石{int(donate_num[0])}枚,宗门建设度增加:{int(donate_num[0])},宗门贡献度增加:{int(donate_num[0])}点,蒸蒸日上!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_donate.finish() else: - msg = f"捐献的灵石数量解析异常" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "捐献的灵石数量解析异常" + await handle_send(bot, event, send_group_id, msg) await sect_donate.finish() @@ -1618,87 +1337,84 @@ async def sect_donate_(bot: Bot, event: GroupMessageEvent, args: Message = Comma async def sect_position_update_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """宗门职位变更""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await sect_position_update.finish() user_id = user_info['user_id'] position_zhanglao = [k for k, v in jsondata.sect_config_data().items() if v.get("title", "") == "长老"] idx_position = int(position_zhanglao[0]) if len(position_zhanglao) == 1 else 1 if user_info['sect_position'] > idx_position: - msg = f"""你的宗门职位为{jsondata.sect_config_data()[f"{user_info['sect_position']}"]['title']},无权进行职位管理!""" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = """你的宗门职位为{jsondata.sect_config_data()[f"{user_info['sect_position']}"]['title']},无权进行职位管理!""" + await handle_send(bot, event, send_group_id, msg) await sect_position_update.finish() give_qq = None - msg = args.extract_plain_text().strip() - position_num = re.findall(r"\d+", msg) + msg_text = args.extract_plain_text().strip() + position_num = re.findall(r"\d+", msg_text) + remaining_text = re.sub(r"\d+", "", msg_text).strip() for arg in args: if arg.type == "at": give_qq = arg.data.get("qq", "") + + give_user = None if give_qq: - if give_qq == user_id: - msg = f"无法对自己的职位进行管理。" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + give_user = await XiuxianDataManager().get_user_infos_by_ids(give_qq) + elif remaining_text: + give_user_info = await XiuxianDataManager().get_user_info_with_name(remaining_text) + if give_user_info: + give_user = give_user_info + give_qq = give_user['user_id'] + + if give_user: + if str(give_qq) == str(user_id): + msg = "无法对自己的职位进行管理。" + await handle_send(bot, event, send_group_id, msg) await sect_position_update.finish() else: if len(position_num) > 0 and position_num[0] in list(jsondata.sect_config_data().keys()): - give_user = sql_message.get_user_info_with_id(give_qq) if give_user['sect_id'] == user_info['sect_id'] and give_user['sect_position'] > user_info['sect_position']: if int(position_num[0]) > user_info['sect_position']: - sql_message.update_usr_sect(give_user['user_id'], give_user['sect_id'], int(position_num[0])) - msg = f"""传{jsondata.sect_config_data()[f"{user_info['sect_position']}"]['title']}{user_info['user_name']}法旨:即日起{give_user['user_name']}为本宗{jsondata.sect_config_data()[f"{int(position_num[0])}"]['title']}""" + await XiuxianDataManager().update_ussr_sect_info(give_user['user_id'], give_user['sect_id'], int(position_num[0])) + msg = """传{jsondata.sect_config_data()[f"{user_info['sect_position']}"]['title']}{user_info['user_name']}法旨:即日起{give_user['user_name']}为本宗{jsondata.sect_config_data()[f"{int(position_num[0])}"]['title']}""" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_position_update.finish() else: - msg = f"道友试图变更的职位品阶必须在你品阶之下" + msg = "道友试图变更的职位品阶必须在你品阶之下" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_position_update.finish() else: - msg = f"请确保变更目标道友与你在同一宗门,且职位品阶在你之下。" + msg = "请确保变更目标道友与你在同一宗门,且职位品阶在你之下。" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_position_update.finish() else: - msg = f"职位品阶数字解析异常,请输入宗门职位变更帮助,查看支持的数字解析配置" + msg = "职位品阶数字解析异常,请输入宗门职位变更帮助,查看支持的数字解析配置" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await sect_position_update.finish() else: - msg = f"""请按照规范进行操作,ex:宗门职位变更2@XXX,将XXX道友(需在自己管理下的宗门)的变更为{jsondata.sect_config_data().get('2', {'title': '没有找到2品阶'})['title']}""" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = """请按照规范进行操作,有两种方式: +1. 宗门职位变更{position_num}@XXX +2. 宗门职位变更{position_num}道号 +将指定道友(需在自己管理下的宗门)变更为{jsondata.sect_config_data().get(position_num, {'title': '没有找到2品阶'})['title']}""" + await handle_send(bot, event, send_group_id, msg) await sect_position_update.finish() @@ -1706,37 +1422,29 @@ async def sect_position_update_(bot: Bot, event: GroupMessageEvent, args: Messag async def join_sect_(bot: Bot, event: GroupMessageEvent, args: Message = CommandArg()): """加入宗门,后跟宗门ID,要求加入者当前状态无宗门,入门默认为外门弟子""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - msg = f"守山弟子:凡人,回去吧,仙途难入,莫要自误!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "守山弟子:凡人,回去吧,仙途难入,莫要自误!" + await handle_send(bot, event, send_group_id, msg) await sect_position_update.finish() user_id = user_info['user_id'] if not user_info['sect_id']: sect_no = args.extract_plain_text().strip() - sql_sects = sql_message.get_all_sect_id() + sql_sects = await XiuxianDataManager().get_all_sect_id() sects_all = [tup[0] for tup in sql_sects] if not sect_no.isdigit(): - msg = f"申请加入的宗门编号解析异常,应全为数字!" + msg = "申请加入的宗门编号解析异常,应全为数字!" elif int(sect_no) not in sects_all: - msg = f"申请加入的宗门编号似乎有误,未在宗门名录上发现!" + msg = "申请加入的宗门编号似乎有误,未在宗门名录上发现!" else: owner_idx = [k for k, v in jsondata.sect_config_data().items() if v.get("title", "") == "外门弟子"] owner_position = int(owner_idx[0]) if len(owner_idx) == 1 else 4 - sql_message.update_usr_sect(user_id, int(sect_no), owner_position) - new_sect = sql_message.get_sect_info_by_id(int(sect_no)) + await XiuxianDataManager().update_ussr_sect_info(user_id, int(sect_no), owner_position) + new_sect = await XiuxianDataManager().get_sect_info_by_id(int(sect_no)) msg = f"欢迎{user_info['user_name']}师弟入我{new_sect['sect_name']},共参天道。" else: - msg = f"守山弟子:我观道友气运中已有宗门气运加持,又何必与我为难。" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "守山弟子:我观道友气运中已有宗门气运加持,又何必与我为难。" + await handle_send(bot, event, send_group_id, msg) await join_sect.finish() @@ -1745,87 +1453,73 @@ async def join_sect_(bot: Bot, event: GroupMessageEvent, args: Message = Command async def my_sect_(bot: Bot, event: GroupMessageEvent): """我的宗门""" bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - msg = f"守山弟子:凡人,回去吧,仙途难入,莫要自误!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = "守山弟子:凡人,回去吧,仙途难入,莫要自误!" + await handle_send(bot, event, send_group_id, msg) await sect_position_update.finish() - elixir_room_level_up_config = config['宗门丹房参数']['elixir_room_level'] + elixir_room_level_up_config = config['宗门丹房参数']["sect_elixir_room_level"] sect_id = user_info['sect_id'] sect_position = user_info['sect_position'] user_name = user_info['user_name'] - sect_info = sql_message.get_sect_info(sect_id) + sect_info = await XiuxianDataManager().get_sect_info(sect_id) owner_idx = [k for k, v in jsondata.sect_config_data().items() if v.get("title", "") == "宗主"] owner_position = int(owner_idx[0]) if len(owner_idx) == 1 else 0 if sect_id: - sql_res = sql_message.scale_top() + sql_res = await XiuxianDataManager().scale_top() top_idx_list = [_[0] for _ in sql_res] - if int(sect_info['elixir_room_level']) == 0: + if int(sect_info["sect_elixir_room_level"]) == 0: elixir_room_name = "暂无" else: - elixir_room_name = elixir_room_level_up_config[str(sect_info['elixir_room_level'])]['name'] + elixir_room_name = elixir_room_level_up_config[str(sect_info["sect_elixir_room_level"])]['name'] msg = f""" {user_name}所在宗门 宗门名讳:{sect_info['sect_name']} 宗门编号:{sect_id} -宗 主:{sql_message.get_user_info_with_id(sect_info['sect_owner'])['user_name']} +宗 主:{(await XiuxianDataManager().get_user_infos_by_ids(sect_info['sect_owner']))['user_name']} 道友职位:{jsondata.sect_config_data()[f"{sect_position}"]['title']} 宗门建设度:{number_to(sect_info['sect_scale'])} -洞天福地:{sect_info['sect_fairyland'] if sect_info['sect_fairyland'] else "暂无"} 宗门位面排名:{top_idx_list.index(sect_id) + 1} -宗门拥有资材:{number_to(sect_info['sect_materials'])} +宗门拥有资材:{number_to(sect_info["sect_material"])} 宗门贡献度:{number_to(user_info['sect_contribution'])} 宗门丹房:{elixir_room_name} """ if sect_position == owner_position: - msg += f"\n宗门储备:{number_to(sect_info['sect_used_stone'])}枚灵石" + msg += f"\n宗门储备:{number_to(sect_info['sect_stone'])}枚灵石" else: - msg = f"一介散修,莫要再问。" + msg = "一介散修,莫要再问。" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await my_sect.finish() -def create_user_sect_task(user_id): +async def create_user_sect_task(user_id): + """为用户创建宗门任务,存入数据库""" tasklist = config["宗门任务"] key = random.choices(list(tasklist))[0] - userstask[user_id]['任务名称'] = key - userstask[user_id]['任务内容'] = tasklist[key] + task_data = tasklist[key] + await XiuxianDataManager().create_sect_task(user_id, key, task_data) -def isUserTask(user_id): +async def isUserTask(user_id): """判断用户是否已有任务 True:有任务""" - Flag = False - try: - userstask[user_id] - except: - userstask[user_id] = {} - - if userstask[user_id] != {}: - Flag = True - - return Flag + task = await XiuxianDataManager().get_sect_task(user_id) + return task is not None -def get_sect_mainbuff_id_list(sect_id): +async def get_sect_mainbuff_id_list(sect_id): """获取宗门功法id列表""" - sect_info = sql_message.get_sect_info(sect_id) - mainbufflist = str(sect_info['mainbuff'])[1:-1].split(',') + sect_info = await XiuxianDataManager().get_sect_info(sect_id) + mainbufflist_str = str(sect_info["sect_main_skill"])[1:-1].split(',') + mainbufflist = [int(buff_id) for buff_id in mainbufflist_str if buff_id.strip()] return mainbufflist -def get_sect_secbuff_id_list(sect_id): +async def get_sect_secbuff_id_list(sect_id): """获取宗门神通id列表""" - sect_info = sql_message.get_sect_info(sect_id) - secbufflist = str(sect_info['secbuff'])[1:-1].split(',') + sect_info = await XiuxianDataManager().get_sect_info(sect_id) + secbufflist_str = str(sect_info["sect_ultimate_skill"])[1:-1].split(',') + secbufflist = [int(buff_id) for buff_id in secbufflist_str if buff_id.strip()] return secbufflist @@ -1901,6 +1595,6 @@ def get_sectbufftxt(sect_scale, config_): return buffgear, bufftxt[buffgear] -def get_sect_level(sect_id): - sect = sql_message.get_sect_info(sect_id) +async def get_sect_level(sect_id): + sect = await XiuxianDataManager().get_sect_info(sect_id) return divmod(sect['sect_scale'], config["等级建设度"]) diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_sect/sectconfig.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_sect/sectconfig.py index 04391349..cad7b0c5 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_sect/sectconfig.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_sect/sectconfig.py @@ -21,169 +21,169 @@ CONFIG = { "LEVLECOST": { # 攻击修炼的灵石消耗 - '0': 1000000, - '1': 2000000, - '2': 4000000, - '3': 8000000, - '4': 8000000, - '5': 8000000, - '6': 8000000, - '7': 8000000, - '8': 8000000, - '9': 8000000, - '10': 16000000, - '11': 16000000, - '12': 16000000, - '13': 16000000, - '14': 16000000, - '15': 16000000, - '16': 16000000, - '17': 16000000, - '18': 16000000, - '19': 16000000, - '20': 32000000, - '21': 32000000, - '22': 32000000, - '23': 32000000, - '24': 32000000, - '25': 64000000, - '26': 64000000, - '27': 64000000, - '28': 64000000, - '29': 64000000, - '30': 200000000, - '31': 200000000, - '32': 200000000, - '33': 200000000, - '34': 200000000, - '35': 500000000, - '36': 500000000, - '37': 500000000, - '38': 500000000, - '39': 500000000, - '40': 1000000000, - '41': 1000000000, - '42': 1000000000, - '43': 1000000000, - '44': 1000000000, - '45': 3000000000, - '46': 4000000000, - '47': 5000000000, - '48': 6000000000, - '49': 7000000000, - '50': 10000000000 + '0': 100000, + '1': 200000, + '2': 400000, + '3': 800000, + '4': 800000, + '5': 800000, + '6': 800000, + '7': 800000, + '8': 800000, + '9': 800000, + '10': 1600000, + '11': 1600000, + '12': 1600000, + '13': 1600000, + '14': 1600000, + '15': 1600000, + '16': 1600000, + '17': 1600000, + '18': 1600000, + '19': 1600000, + '20': 3200000, + '21': 3200000, + '22': 3200000, + '23': 3200000, + '24': 3200000, + '25': 6400000, + '26': 6400000, + '27': 6400000, + '28': 6400000, + '29': 6400000, + '30': 20000000, + '31': 20000000, + '32': 20000000, + '33': 20000000, + '34': 20000000, + '35': 50000000, + '36': 50000000, + '37': 50000000, + '38': 50000000, + '39': 50000000, + '40': 100000000, + '41': 100000000, + '42': 100000000, + '43': 100000000, + '44': 100000000, + '45': 300000000, + '46': 400000000, + '47': 500000000, + '48': 600000000, + '49': 700000000, + '50': 1000000000 }, - "等级建设度": 500000, # 决定宗门修炼上限等级的参数,500万贡献度每级 + "等级建设度": 50000, # 决定宗门修炼上限等级的参数,500万贡献度每级 "发放宗门资材": { "时间": "11-12", # 定时任务发放宗门资材,每日11-12点根据 对应宗门贡献度的 * 倍率 发放资材 "倍率": 1, # 倍率 }, - "每日宗门任务次上限": 3, - "宗门任务完成cd": 900, # 宗门任务每次完成间隔,单位秒 - "宗门任务刷新cd": 300, # 宗门任务刷新间隔,单位秒 + "每日宗门任务次上限": 4, + "宗门任务完成cd": 0, # 宗门任务每次完成间隔,单位秒 + "宗门任务刷新cd": 3, # 宗门任务刷新间隔,单位秒 "宗门主功法参数": { - "获取消耗的资材": 60000000, # 最终消耗会乘档位 - "获取消耗的灵石": 3000000, # 最终消耗会乘档位 + "获取消耗的资材": 600000, # 最终消耗会乘档位 + "获取消耗的灵石": 300000, # 最终消耗会乘档位 "获取到功法的概率": 10, - "建设度": 10000000, # 建设度除以此参数,一共10档(10档目前无法配置,对应天地玄黄人上下) - "学习资材消耗": 6000000, # 最终消耗会乘档位 + "建设度": 1000000, # 建设度除以此参数,一共10档(10档目前无法配置,对应天地玄黄人上下) + "学习资材消耗": 600000, # 最终消耗会乘档位 }, "宗门神通参数": { - "获取消耗的资材": 60000000, # 最终消耗会乘档位 - "获取消耗的灵石": 3000000, # 最终消耗会乘档位 + "获取消耗的资材": 6000000, # 最终消耗会乘档位 + "获取消耗的灵石": 300000, # 最终消耗会乘档位 "获取到神通的概率": 10, - "建设度": 10000000, # 建设度除以此参数,一共10档(10档目前无法配置,对应天地玄黄人上下) - "学习资材消耗": 6000000, # 最终消耗会乘档位 + "建设度": 1000000, # 建设度除以此参数,一共10档(10档目前无法配置,对应天地玄黄人上下) + "学习资材消耗": 600000, # 最终消耗会乘档位 }, "宗门丹房参数": { - "领取贡献度要求": 50000, - "elixir_room_level": { + "领取贡献度要求": 500, + "sect_elixir_room_level": { "1": { "name": "黄级", "level_up_cost": { - "建设度": 50000000, # 升级消耗建设度 - "stone": 200000 # 升级消耗宗门灵石 + "建设度": 5000000, # 升级消耗建设度 + "stone": 20000 # 升级消耗宗门灵石 }, "give_level": { - "give_num": 1, # 每日领取的丹药数量 + "give_num": 5, # 每日领取的丹药数量 "rank_up": 1 # rank增幅等级,影响丹药获取品质,目前高于6会无法获得丹药 } }, "2": { "name": "玄级", "level_up_cost": { - "建设度": 60000000, - "stone": 400000 + "建设度": 6000000, + "stone": 40000 }, "give_level": { - "give_num": 2, - "rank_up": 1 + "give_num": 6, + "rank_up": 2 } }, "3": { "name": "地级", "level_up_cost": { - "建设度": 70000000, - "stone": 800000 + "建设度": 7000000, + "stone": 80000 }, "give_level": { - "give_num": 3, - "rank_up": 1 + "give_num": 7, + "rank_up": 2 } }, "4": { "name": "天级", "level_up_cost": { - "建设度": 80000000, - "stone": 1600000 + "建设度": 8000000, + "stone": 160000 }, "give_level": { - "give_num": 4, - "rank_up": 1 + "give_num": 8, + "rank_up": 2 } }, "5": { "name": "仙级", "level_up_cost": { - "建设度": 100000000, - "stone": 3200000 + "建设度": 10000000, + "stone": 320000 }, "give_level": { - "give_num": 5, - "rank_up": 1 + "give_num": 9, + "rank_up": 2 } }, "6": { "name": "仙王级", "level_up_cost": { - "建设度": 1000000000, - "stone": 100000000 + "建设度": 100000000, + "stone": 10000000 }, "give_level": { - "give_num": 7, - "rank_up": 2 + "give_num": 10, + "rank_up": 3 } }, "7": { "name": "仙帝级", "level_up_cost": { - "建设度": 2000000000, - "stone": 150000000 + "建设度": 200000000, + "stone": 15000000 }, "give_level": { - "give_num": 9, - "rank_up": 3 + "give_num": 11, + "rank_up": 4 } }, "8": { "name": "无上", "level_up_cost": { - "建设度": 5000000000, - "stone": 300000000 + "建设度": 500000000, + "stone": 30000000 }, "give_level": { - "give_num": 11, - "rank_up": 4 + "give_num": 12, + "rank_up": 5 } } } @@ -239,7 +239,7 @@ def get_config(): if key not in list(config.keys()): config[key] = CONFIG[key] savef(config) - except: + except FileNotFoundError: config = CONFIG savef(config) return config diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/README.md b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/README_battle.md similarity index 98% rename from nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/README.md rename to nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/README_battle.md index d8eb6b6a..d4c9b2df 100644 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/README.md +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/README_battle.md @@ -13,7 +13,7 @@ 1. **获取玩家Buff信息**: - - 调用 `UserBuffDate()`获取玩家1和玩家2的buff信息。 + - 调用 `UserBuffData()`获取玩家1和玩家2的buff信息。 - 获取主Buff的数据:`get_user_main_buff_data()`,分别获取玩家的 `hpbuff`(气血增益)和 `mpbuff`(真元增益)。 - 获取传承增益信息:使用 `xiuxian_impart.get_user_impart_info_with_id()`方法获取玩家的传承数据,进而计算额外的气血和真元增益,累加到各自的buff上。 2. **技能数据初始化**: @@ -90,7 +90,7 @@ #### 玩家数据初始化 1. **获取玩家Buff信息**: - * 调用 `UserBuffDate()` 获取玩家的buff信息。 + * 调用 `UserBuffData()` 获取玩家的buff信息。 * 如果玩家buff数据为空,设置主buff和辅修功法数据为空。 * 如果玩家buff数据不为空,获取主buff数据、辅修功法数据,包含: * 气血增益(`hpbuff`) diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/README_fantasy.md b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/README_fantasy.md new file mode 100644 index 00000000..e2169a00 --- /dev/null +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/README_fantasy.md @@ -0,0 +1,200 @@ +# 修仙名称生成器 (Python版) + +基于JavaScript版本的[random_chinese_fantasy_names](https://github.com/hythl0day/random_chinese_fantasy_names)转写,提供了Python的API接口。 + +## 快速开始 + +```python + +generator = XiuXianNameGenerator(data_dir="data") + +# 生成人名 +names = generator.get_name(5) +for name in names: + print(name) + +# 生成道号 +dao_names = generator.get_dao(3) +for dao in dao_names: + print(f"{dao['name']} + +# 生成技能名称 +skills = generator.get_skill(3) +for skill in skills: + print(f"{skill['name']} ({RARITY_NAMES[skill['rarity']]})") + +``` + +## API 参考 + +### 常量 + +- `SEX_VALUES`: 性别常量列表 +- `RARITY_COLORS`: 稀有度对应的颜色 +- `RARITY_LEVELS`: 稀有度级别列表 +- `RARITY_VALUES`: 稀有度对应的概率值 +- `RARITY_NAMES`: 稀有度对应的中文名称 +- `CREATURE_CATEGORY`: 生物种类列表 +- `CREATURE_CATEGORY_NAMES`: 生物种类对应的中文名称 +- `ZONE_CATEGORIES`: 区域类别列表 + +### XiuXianNameGenerator 类 + +#### 构造函数 + +```python +XiuXianNameGenerator(data_dir="data") +``` + +- `data_dir`: 数据文件目录的路径 + +#### 属性 + +- `dao_titles`: 获取所有道号称号列表 +- `book_prefixes`: 获取所有书籍前缀列表 +- `talisman_kind`: 获取所有符箓类型列表 +- `material_kind`: 获取所有材料类型列表 +- `material_postfixes`: 获取所有材料后缀列表 +- `talisman_postfixes`: 获取所有符箓后缀列表 +- `zone_kind`: 获取所有区域类型列表 +- `book_postfixes`: 获取所有书籍后缀列表 + +#### 方法 + +##### 生成人名 + +```python +get_name(number=1, options=None) -> List[str] +``` + +- `number`: 生成名字的数量 +- `options`: 选项参数,可包含: + - `familyName`: 指定姓氏 + - `isFemale`: 是否女性 + - `style`: 命名风格('single', 'double', 'combine') + - `middleCharacter`: 中间字符 + +##### 生成道号 + +```python +get_dao(number=1, options=None) -> List[Dict] +``` + +- `number`: 生成道号的数量 +- `options`: 选项参数,可包含: + - `firstCharacter`: 第一个字符 + - `isFemale`: 是否女性 + - `title`: 称号 + +##### 生成功法名称 + +```python +get_skill(number=1, options=None) -> List[Dict] +``` + +- `number`: 生成名称的数量 +- `options`: 选项参数,可包含: + - `length`: 长度 + - `kind`: 类型 + - `prefix`: 前缀 + - `numfix`: 数字后缀 + +##### 生成秘籍名称 + +```python +get_book(number=1, options=None) -> List[Dict] +``` + +- `number`: 生成名称的数量 +- `options`: 选项参数,可包含: + - `length`: 长度 + - `mainkind`: 主要类型 + - `prefix`: 前缀 + - `postkind`: 后缀类型 + - `postfix`: 后缀 + +##### 生成生灵名称 + +```python +get_creature(number=1, options=None) -> List[Dict] +``` + +- `number`: 生成名称的数量 +- `options`: 选项参数,可包含: + - `category`: 种类 + - `rarity`: 稀有度 + +##### 生成材料名称 + +```python +get_material(number=1, options=None) -> List[Dict] +``` + +- `number`: 生成名称的数量 +- `options`: 选项参数,可包含: + - `kind`: 类型 + - `rarity`: 稀有度 + - `postfix`: 后缀 + +##### 生成法宝名称 + +```python +get_talisman(number=1, options=None) -> List[Dict] +``` + +- `number`: 生成名称的数量 +- `options`: 选项参数,可包含: + - `kind`: 类型 + - `rarity`: 稀有度 + - `postfix`: 后缀 + +##### 生成丹药名称 + +```python +get_alchemy(number=1, kind=None) -> List[Dict] +``` + +- `number`: 生成名称的数量 +- `kind`: 丹药类型 + +##### 生成门派名称 + +```python +get_clan(number=1, kind=None) -> List[str] +``` + +- `number`: 生成名称的数量 +- `kind`: 门派类型 + +##### 生成国家名称 + +```python +get_nation(number=1, kind=None) -> List[Dict] +``` + +- `number`: 生成名称的数量 +- `kind`: 国家类型 + +##### 生成据点名称 + +```python +get_location(number=1, kind=None) -> List[Dict] +``` + +- `number`: 生成名称的数量 +- `kind`: 类型 + +##### 生成地域名称 + +```python +get_zone(number=1, options_or_kind=None) -> List[Dict] +``` + +- `number`: 生成名称的数量 +- `options_or_kind`: 可以是类型字符串或包含以下键的选项字典: + - `kind`: 类型 + - `category`: 类别 + +## 许可证 + +与原JavaScript版本相同。 diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/backup_strategy.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/backup_strategy.py new file mode 100644 index 00000000..1d655eac --- /dev/null +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/backup_strategy.py @@ -0,0 +1,347 @@ +""" +PostgreSQL数据库自动备份模块 +每分钟自动备份一次数据库 +""" +import asyncio +import os +import subprocess +import logging +import datetime +import tarfile +import shutil +from pathlib import Path +from ..xiuxian_config import XiuConfig +from ..xiuxian_utils.item_json import BACKUPPATH, READPATH + +# 初始化日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler("xiuxian_backup.log"), + logging.StreamHandler() + ] +) +logger = logging.getLogger("xiuxian_backup") + +# 获取数据路径 +try: + # 确保备份路径存在 + if not os.path.exists(BACKUPPATH): + os.makedirs(BACKUPPATH, exist_ok=True) + logger.info(f"备份路径设置为: {BACKUPPATH}") +except Exception as e: + logger.error(f"设置备份路径时出错: {e}") + # 回退到默认路径 + if not os.path.exists(READPATH / "备份"): + os.makedirs(READPATH / "备份", exist_ok=True) + logger.info(f"回退备份路径设置为: {READPATH / '备份'}") + +# 全局连接池引用 +_POOL = None +# 备份服务状态 +_BACKUP_SERVICE_RUNNING = False +# 备份任务 +_BACKUP_TASK = None + +def set_pool(pool): + """设置全局连接池引用""" + global _POOL + _POOL = pool + +# 备份配置 +BACKUP_CONFIG = { + "backup_dir": BACKUPPATH, # 使用正确的备份路径 + "pg_dump_path": "pg_dump", # 可能需要指定完整路径,如 "/usr/bin/pg_dump" + "database_name": "xiuxian", + "pg_url": None, # 将在运行时设置 + "keep_backups": XiuConfig().backup_quantity, # 保留60个备份(1小时) + "backup_interval": XiuConfig().backup_interval * 60, # 60秒 = 1分钟 + "compress_backups": True +} + +def set_pg_url(url): + """设置PostgreSQL连接URL""" + BACKUP_CONFIG["pg_url"] = url + +def ensure_backup_dir(): + """确保备份目录存在""" + backup_dir = Path(BACKUP_CONFIG["backup_dir"]) + backup_dir.mkdir(parents=True, exist_ok=True) + return backup_dir + +def get_backup_filename(): + """生成备份文件名""" + timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + return f"xiuxian_backup_{timestamp}.sql" + +def compress_backup(file_path): + """压缩备份文件""" + if not BACKUP_CONFIG["compress_backups"]: + return file_path + + tar_path = f"{file_path}.tar.gz" + with tarfile.open(tar_path, "w:gz") as tar: + tar.add(file_path, arcname=os.path.basename(file_path)) + + # 删除原始SQL文件 + os.remove(file_path) + return tar_path + +def cleanup_old_backups(): + """清理旧备份""" + backup_dir = Path(BACKUP_CONFIG["backup_dir"]) + backups = sorted([ + f for f in backup_dir.glob("xiuxian_backup_*.sql*") + ], key=lambda x: os.path.getmtime(x)) + + # 保留最近的N个备份 + if len(backups) > BACKUP_CONFIG["keep_backups"]: + for old_backup in backups[:-BACKUP_CONFIG["keep_backups"]]: + try: + os.remove(old_backup) + logger.info(f"已删除旧备份: {old_backup}") + except Exception as e: + logger.error(f"删除旧备份时出错: {e}") + +async def create_backup(): + """创建数据库备份""" + try: + backup_dir = ensure_backup_dir() + backup_filename = get_backup_filename() + backup_path = os.path.join(backup_dir, backup_filename) + + # 构建pg_dump命令 + pg_url = BACKUP_CONFIG["pg_url"] + if not pg_url: + logger.error("未设置PostgreSQL连接URL") + return None + + # 执行pg_dump + cmd = [ + BACKUP_CONFIG["pg_dump_path"], + "-d", pg_url, + "-f", backup_path, + "--format=plain", + "--no-owner", + "--no-acl" + ] + + # 执行命令 + process = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE + ) + stdout, stderr = process.communicate() + + if process.returncode != 0: + logger.error(f"备份创建失败: {stderr.decode()}") + return None + + # 压缩备份 + final_path = compress_backup(backup_path) + + # 清理旧备份 + cleanup_old_backups() + + logger.info(f"备份成功创建: {final_path}") + return final_path + + except Exception as e: + logger.error(f"备份过程中出错: {e}") + return None + +async def automatic_backup_task(): + """自动备份任务""" + backup_count = 0 + last_error = None + + while True: + try: + backup_count += 1 + logger.info(f"开始计划备份 #{backup_count}...") + + # 尝试创建备份 + backup_path = await create_backup() + + if backup_path: + logger.info(f"备份 #{backup_count} 成功创建: {backup_path}, 大小: {os.path.getsize(backup_path) / 1024:.2f} KB") + last_error = None # 重置错误状态 + + # 记录当前拥有的备份数量 + backup_files = list(Path(BACKUP_CONFIG["backup_dir"]).glob("xiuxian_backup_*.sql*")) + logger.info(f"当前备份文件数量: {len(backup_files)}, 最大保留数量: {BACKUP_CONFIG['keep_backups']}") + else: + logger.warning(f"备份 #{backup_count} 创建失败") + + # 检查/更新数据库结构 + try: + await check_db_structure() + except Exception as e: + logger.error(f"数据库结构检查失败: {e}") + + # 等待下一次备份 + interval_minutes = BACKUP_CONFIG['backup_interval'] // 60 + logger.info(f"备份 #{backup_count} 完成,{interval_minutes} 分钟后进行下一次备份") + + # 精确计算下一次备份时间 + next_backup_time = datetime.datetime.now() + datetime.timedelta(seconds=BACKUP_CONFIG["backup_interval"]) + logger.info(f"下一次备份计划时间: {next_backup_time.strftime('%Y-%m-%d %H:%M:%S')}") + + await asyncio.sleep(BACKUP_CONFIG["backup_interval"]) + + except asyncio.CancelledError: + logger.info("备份任务被取消") + break + except Exception as e: + # 避免不停地记录相同的错误 + if str(e) != str(last_error): + logger.error(f"自动备份任务 #{backup_count} 出错: {e}") + last_error = e + + # 出错后等待一小段时间再重试 + logger.info("将在60秒后重试备份") + await asyncio.sleep(60) + +async def check_db_structure(): + """检查并维护数据库结构""" + if _POOL is None: + logger.warning("连接池未初始化,无法检查数据库结构") + return + + try: + async with _POOL.acquire() as conn: + # 检查索引碎片 + await conn.execute("VACUUM ANALYZE xiuxian_user;") + await conn.execute("VACUUM ANALYZE xiuxian_back;") + await conn.execute("VACUUM ANALYZE xiuxian_time;") + logger.info("数据库维护完成:已整理碎片") + except Exception as e: + logger.error(f"数据库维护时出错: {e}") + +async def restore_backup(backup_path): + """恢复指定的备份""" + try: + if not os.path.exists(backup_path): + logger.error(f"备份文件不存在: {backup_path}") + return False + + # 临时解压缩 + if backup_path.endswith('.tar.gz'): + temp_dir = os.path.join(BACKUP_CONFIG["backup_dir"], "temp_restore") + os.makedirs(temp_dir, exist_ok=True) + + with tarfile.open(backup_path, 'r:gz') as tar: + tar.extractall(path=temp_dir) + + # 找到解压后的SQL文件 + sql_files = list(Path(temp_dir).glob("*.sql")) + if not sql_files: + logger.error("备份文件中没有找到SQL文件") + shutil.rmtree(temp_dir) + return False + + backup_sql = str(sql_files[0]) + else: + backup_sql = backup_path + + # 构建psql恢复命令 + pg_url = BACKUP_CONFIG["pg_url"] + cmd = [ + "psql", # 可能需要完整路径 + "-d", pg_url, + "-f", backup_sql + ] + + # 执行恢复 + process = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE + ) + stdout, stderr = process.communicate() + + # 清理临时文件 + if backup_path.endswith('.tar.gz'): + shutil.rmtree(temp_dir) + + if process.returncode != 0: + logger.error(f"恢复失败: {stderr.decode()}") + return False + + logger.info(f"成功从备份恢复: {backup_path}") + return True + + except Exception as e: + logger.error(f"恢复备份时出错: {e}") + return False + +def list_available_backups(): + """列出所有可用的备份""" + backup_dir = Path(BACKUP_CONFIG["backup_dir"]) + backups = [] + + if not backup_dir.exists(): + return backups + + # 查找所有备份文件 + for ext in ["sql", "sql.tar.gz"]: + backups.extend(backup_dir.glob(f"xiuxian_backup_*.{ext}")) + + # 按时间排序(最新的优先) + backups.sort(key=lambda x: os.path.getmtime(x), reverse=True) + + # 返回文件名和大小 + result = [] + for backup in backups: + size_mb = os.path.getsize(backup) / (1024 * 1024) + time_created = datetime.datetime.fromtimestamp( + os.path.getmtime(backup) + ).strftime("%Y-%m-%d %H:%M:%S") + + result.append({ + "path": str(backup), + "filename": backup.name, + "size_mb": round(size_mb, 2), + "created_at": time_created + }) + + return result + +async def start_backup_service(): + """启动备份服务""" + global _BACKUP_SERVICE_RUNNING, _BACKUP_TASK + + # 检查服务是否已经在运行 + if _BACKUP_SERVICE_RUNNING: + logger.info("备份服务已经在运行,跳过重复启动") + return _BACKUP_TASK + + logger.info("正在启动数据库备份服务...") + + # 检查配置 + if not BACKUP_CONFIG["pg_url"]: + logger.error("未设置PostgreSQL连接URL,无法启动备份服务") + return None + + # 确保备份目录存在 + backup_dir = ensure_backup_dir() + logger.info(f"备份将保存到: {backup_dir}") + + # 创建一个初始备份 + try: + initial_backup = await create_backup() + if initial_backup: + logger.info(f"初始备份创建成功: {initial_backup}") + else: + logger.warning("初始备份创建失败") + except Exception as e: + logger.error(f"创建初始备份时出错: {e}") + + # 启动自动备份任务 + _BACKUP_TASK = asyncio.create_task(automatic_backup_task()) + _BACKUP_SERVICE_RUNNING = True + logger.info("数据库备份服务已启动,每分钟进行一次备份") + + return _BACKUP_TASK diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/data_source.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/data_source.py index e0b9b829..80b4444f 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/data_source.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/data_source.py @@ -7,7 +7,7 @@ DATABASE = Path() / "data" / "xiuxian" -class JsonDate: +class JsonData: """处理基础配置 JSON数据""" def __init__(self): @@ -57,4 +57,4 @@ def exercises_level_data(self): return data -jsondata = JsonDate() +jsondata = JsonData() diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/download_xiuxian_data.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/download_xiuxian_data.py index 68549deb..68c2aea1 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/download_xiuxian_data.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/download_xiuxian_data.py @@ -24,15 +24,15 @@ def _main_(): with open(version_path, 'r', encoding='utf-8') as f: data = f.read() f.close() - except: + except ValueError: pass if str(data) == str(XiuConfig().version): - logger.opt(colors=True).info(f"修仙配置校核完成!") + logger.opt(colors=True).info("修仙配置校核完成!") else: - logger.opt(colors=True).info(f"正在更新修仙配置文件,请等待!") + logger.opt(colors=True).info("正在更新修仙配置文件,请等待!") try: get_data() # data为byte字节 - logger.opt(colors=True).info(f"正在解压修仙配置文件!") + logger.opt(colors=True).info("正在解压修仙配置文件!") with zipfile.ZipFile(file=zipPath, mode='r') as zf: for old_name in zf.namelist(): # 获取文件大小,目的是区分文件夹还是文件,如果是空文件应该不好用。 @@ -52,7 +52,7 @@ def _main_(): finally: try: os.remove(zipPath) - logger.opt(colors=True).info(f"原始压缩包已删除!") - except: + logger.opt(colors=True).info("原始压缩包已删除!") + except ValueError: logger.opt(colors=True).info(f"原始压缩包删除失败,请手动删除,路径{zipPath}!") return _main_() diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/item_json.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/item_json.py index c83a070a..ddf2360b 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/item_json.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/item_json.py @@ -6,13 +6,18 @@ from pathlib import Path from typing import List -READPATH = Path() / "data" / "xiuxian" + +BOT_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) +BOT_PATH = os.path.dirname(BOT_PATH) +READPATH = Path(BOT_PATH) / "data" / "xiuxian" SKILLPATH = READPATH / "功法" WEAPONPATH = READPATH / "装备" ELIXIRPATH = READPATH / "丹药" PACKAGESPATH = READPATH / "礼包" XIULIANITEMPATH = READPATH / "修炼物品" BOSSDROPSPATH = READPATH / "boss掉落物" +FANTASYNAMEDATAPATH = READPATH / "修仙随机名词数据" +BACKUPPATH = READPATH / "备份" class Items: @@ -52,7 +57,7 @@ def readf(self, FILEPATH): return json.loads(data) def savef(self, data): - FILEPATH = Path() / "data" / "xiuxian" / "items.json" + FILEPATH = READPATH / "items.json" data = json.dumps(data, ensure_ascii=False, indent=4) save_mode = "w" if os.path.exists(FILEPATH) else "x" with open(FILEPATH, mode=save_mode, encoding="UTF-8") as f: diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/lay_out.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/lay_out.py index 4646a37d..4b4a38d9 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/lay_out.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/lay_out.py @@ -11,12 +11,11 @@ from nonebot.adapters.onebot.v11.event import MessageEvent, GroupMessageEvent from nonebot.adapters.onebot.v11 import Bot, MessageSegment from ..xiuxian_config import XiuConfig, JsonConfig -from .xiuxian2_handle import XiuxianDateManage -from .utils import get_msg_pic, check_user +from .xiuxian2_handle import XiuxianDataManager +from .utils import check_user, get_msg_pic, is_qbot +from nonebot_plugin_uninfo import Uninfo -sql_message = XiuxianDateManage() - limit_all_message = require("nonebot_plugin_apscheduler").scheduler limit_all_stamina = require("nonebot_plugin_apscheduler").scheduler auto_recover_hp = require("nonebot_plugin_apscheduler").scheduler @@ -25,20 +24,29 @@ limit_num = 99999 @auto_recover_hp.scheduled_job('interval', minutes=1) -def auto_recover_hp_(): - sql_message.auto_recover_hp +async def auto_recover_hp_(): + """恢复生命值的定时任务""" + try: + if XiuConfig().postgresql_url != "": + await XiuxianDataManager().auto_recover_hp() + except Exception as e: + logger.opt(colors=True).error(f"生命值恢复定时任务出错:{e}") @limit_all_message.scheduled_job('interval', minutes=1) def limit_all_message_(): # 重置消息字典 global limit_all_data limit_all_data = {} - logger.opt(colors=True).success(f"已重置消息字典!") + logger.opt(colors=True).success("已重置消息字典!") @limit_all_stamina.scheduled_job('interval', minutes=1) -def limit_all_stamina_(): - # 恢复体力 - sql_message.update_all_users_stamina(XiuConfig().max_stamina, XiuConfig().stamina_recovery_points) +async def limit_all_stamina_(): + """恢复体力值的定时任务""" + try: + if XiuConfig().postgresql_url != "": + await XiuxianDataManager().update_all_users_stamina(XiuConfig().max_stamina, XiuConfig().stamina_recovery_points) + except Exception as e: + logger.opt(colors=True).error(f"体力恢复定时任务出错:{e}") def limit_all_run(user_id: str): global limit_all_data @@ -48,18 +56,18 @@ def limit_all_run(user_id: str): try: num = limit_all_data[user_id]["num"] tip = limit_all_data[user_id]["tip"] - except: + except KeyError: limit_all_data[user_id] = {"num": 0, "tip" : False} num = 0 tip = False num += 1 - if num > limit_num and tip == False: + if num > limit_num and tip is False: tip = True limit_all_data[user_id]["num"] = num limit_all_data[user_id]["tip"] = tip return True - if num > limit_num and tip == True: + if num > limit_num and tip is True: limit_all_data[user_id]["num"] = num return False else: @@ -140,12 +148,17 @@ def increase(key: str, value: int = 1): del time_sy[key] return - async def dependency(bot: Bot, matcher: Matcher, event: MessageEvent): - user_id = str(event.get_user_id()) + async def dependency(bot: Bot, matcher: Matcher, event: MessageEvent, session: Uninfo): + user_id = int(event.get_user_id()) group_id = str(event.group_id) conf_data = JsonConfig().read_data() - limit_type = limit_all_run(str(event.get_user_id())) + # 首先检查数据库连接 + if XiuConfig().postgresql_url == "": + await bot.send(event=event, message="请先在xiuxian_config.py文件中配置数据库地址!", reply_message=True) + await matcher.finish() + + limit_type = limit_all_run(user_id) if limit_type is True: bot = await assign_bot_group(group_id=group_id) await bot.send(event=event, message=bu_ji_notice) @@ -155,6 +168,8 @@ async def dependency(bot: Bot, matcher: Matcher, event: MessageEvent): else: pass + isUser, user_info, msg = await check_user(event) + loop = get_running_loop() if isolate_level is CooldownIsolateLevel.GROUP: @@ -173,39 +188,46 @@ async def dependency(bot: Bot, matcher: Matcher, event: MessageEvent): ) else: key = CooldownIsolateLevel.GLOBAL.name + if group_id not in conf_data["group"]: - if ( - event.sender.role == "admin" or - event.sender.role == "owner" or - event.get_user_id() in bot.config.superusers - ): - bot = await assign_bot_group(group_id=group_id) - if at_sender: - await bot.send(event=event, message=MessageSegment.at(event.get_user_id()) + "本群已关闭修仙模组,请联系管理员开启,开启命令为【启用修仙功能】!") + try: + is_official_bot = is_qbot(session) + except Exception: + is_official_bot = False + + if not is_official_bot: + if ( + event.sender.role == "admin" or + event.sender.role == "owner" or + event.get_user_id() in bot.config.superusers + ): + bot = await assign_bot_group(group_id=group_id) + if at_sender: + await bot.send(event=event, message=MessageSegment.at(event.get_user_id()) + "本群已关闭修仙模组,请联系管理员开启,开启命令为【启用修仙功能】!", reply_message=True) + else: + await bot.send(event=event, message="本群已关闭修仙模组,请联系管理员开启,开启命令为【启用修仙功能】!", reply_message=True) + await matcher.finish() else: - await bot.send(event=event, message="本群已关闭修仙模组,请联系管理员开启,开启命令为【启用修仙功能】!") - await matcher.finish() + await matcher.finish() else: - await matcher.finish() - else: - pass + pass if XiuConfig().admin_debug: if event.get_user_id() not in bot.config.superusers: await matcher.finish() if stamina_cost > 0: - user_data = sql_message.get_user_info_with_id(user_id) + user_data = await XiuxianDataManager().get_user_infos_by_ids(user_id) if user_data: - if user_data['user_stamina'] < stamina_cost: + if user_data['stamina'] < stamina_cost: msg = "你没有足够的体力,请等待体力恢复后再试!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(group_id), message=msg) await matcher.finish() - sql_message.update_user_stamina(user_id, stamina_cost, 2) # 减少体力 + await XiuxianDataManager().update_user_stamina(user_id, stamina_cost, 2) # 减少体力 if running[key] <= 0: if cd_time >= 1.5: time = int(cd_time - (loop.time() - time_sy[key])) @@ -213,7 +235,7 @@ async def dependency(bot: Bot, matcher: Matcher, event: MessageEvent): time = 1 formatted_time = format_time(time) if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + get_random_chat_notice().format(formatted_time)) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + get_random_chat_notice().format(formatted_time)) bot = await assign_bot_group(group_id=group_id) await bot.send_group_msg(group_id=int(group_id), message=MessageSegment.image(pic)) await matcher.finish() @@ -247,7 +269,7 @@ async def check_bot(bot: Bot) -> bool: # 检测bot实例是否为主qq def check_rule_bot() -> Rule: # 对传入的消息检测,是主qq传入的消息就响应,其他的不响应 async def _check_bot_(bot: Bot, event: GroupMessageEvent) -> bool: if str(bot.self_id) in put_bot: - if str(event.get_user_id()) in main_bot: + if int(event.get_user_id()) in main_bot: return False else: return True @@ -277,7 +299,7 @@ async def assign_bot(bot=None, event=None): # 按字典分配对应qq发送消 bot = get_bots()[random.choice(bot_id)] else: bot = bot - except: + except KeyError: bot = bot return bot, group_id @@ -301,7 +323,7 @@ async def assign_bot_group(group_id): # 只导入群号,按字典分配对应 try: bot = get_bot() except ValueError: - logger.opt(colors=True).error(f"未找到对应的bot实例,请检查实现端链接状况!") + logger.opt(colors=True).error("未找到对应的bot实例,请检查实现端链接状况!") bot = None return bot diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/optimization_manager.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/optimization_manager.py new file mode 100644 index 00000000..d6db5585 --- /dev/null +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/optimization_manager.py @@ -0,0 +1,356 @@ +""" +数据库优化管理器 +整合事务、查询、备份和垃圾回收优化 +""" +import logging +import os +import importlib.util +import sys +import asyncpg + +# 设置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler("xiuxian_optimization.log"), + logging.StreamHandler() + ] +) +logger = logging.getLogger("xiuxian_optimizer") + +# 优化模块路径 +MODULE_PATHS = { + "transaction": os.path.join(os.path.dirname(__file__), "transaction_optimization.py"), + "query": os.path.join(os.path.dirname(__file__), "query_optimization.py"), + "backup": os.path.join(os.path.dirname(__file__), "backup_strategy.py"), + "vacuum": os.path.join(os.path.dirname(__file__), "vacuum_optimization.py") +} + +# 数据库配置 +DB_CONFIG = { + "pg_url": None, # 将在运行时设置 + "min_connections": 10, + "max_connections": 50, + "command_timeout": 30.0, + "max_inactive_connection_lifetime": 600.0, + "statement_cache_size": 1000 +} + +# 全局连接池 +_POOL = None +# 初始化标志,防止重复初始化 +_INITIALIZED = False + +def set_pg_url(url: str): + """设置PostgreSQL连接URL""" + DB_CONFIG["pg_url"] = url + +async def create_pool() -> asyncpg.Pool: + """创建数据库连接池""" + global _POOL + + if not DB_CONFIG["pg_url"]: + raise ValueError("未设置PostgreSQL连接URL") + + # 如果连接池已存在,直接返回 + if _POOL is not None: + logger.info("数据库连接池已存在,跳过创建") + return _POOL + + logger.info("创建数据库连接池...") + + _POOL = await asyncpg.create_pool( + DB_CONFIG["pg_url"], + min_size=DB_CONFIG["min_connections"], + max_size=DB_CONFIG["max_connections"], + command_timeout=DB_CONFIG["command_timeout"], + max_inactive_connection_lifetime=DB_CONFIG["max_inactive_connection_lifetime"], + statement_cache_size=DB_CONFIG["statement_cache_size"] + ) + + logger.info("数据库连接池创建成功") + return _POOL + +async def close_pool(): + """关闭数据库连接池""" + global _POOL + + if _POOL: + logger.info("关闭数据库连接池...") + await _POOL.close() + _POOL = None + logger.info("数据库连接池已关闭") + +def load_module(module_name: str, module_path: str): + """动态加载Python模块""" + try: + abs_path = os.path.abspath(module_path) + + if not os.path.exists(abs_path): + logger.error(f"模块文件不存在: {abs_path}") + return None + + if module_name in sys.modules: + logger.info(f"模块 {module_name} 已加载,跳过重复加载") + return sys.modules[module_name] + + module_dir = os.path.dirname(abs_path) + if module_dir not in sys.path: + sys.path.insert(0, module_dir) + + spec = importlib.util.spec_from_file_location(module_name, abs_path) + if not spec: + logger.error(f"无法为 {module_path} 创建模块规范") + return None + + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + spec.loader.exec_module(module) + + logger.info(f"已加载模块: {module_name}") + return module + + except Exception as e: + logger.error(f"加载模块 {module_name} 时出错: {e}") + return None + +class OptimizationManager: + """优化管理器类""" + # 单例模式实例 + _instance = None + + def __new__(cls): + if cls._instance is None: + cls._instance = super(OptimizationManager, cls).__new__(cls) + cls._instance.initialized = False + cls._instance.pool = None + cls._instance.modules = {} + cls._instance.services_running = False + return cls._instance + + async def initialize(self, pg_url: str): + """初始化优化管理器""" + # 检查是否已初始化 + if self.initialized: + logger.info("优化管理器已初始化,跳过重复初始化") + return True + + try: + set_pg_url(pg_url) + self.pool = await create_pool() + + # 加载所有模块 + for name, path in MODULE_PATHS.items(): + module = load_module(f"xiuxian_{name}", path) + if module and hasattr(module, "set_pool"): + module.set_pool(self.pool) + self.modules[name] = module + + if self.modules.get("backup") and hasattr(self.modules["backup"], "set_pg_url"): + self.modules["backup"].set_pg_url(pg_url) + + self.initialized = True + logger.info("优化管理器初始化完成") + return True + + except Exception as e: + logger.error(f"初始化优化管理器时出错: {e}") + return False + + async def start_services(self): + """启动所有优化服务""" + if not self.initialized: + logger.error("优化管理器未初始化,无法启动服务") + return False + + if self.services_running: + logger.warning("服务已经在运行中,跳过重复启动") + return True + + try: + # 启动备份服务 + if self.modules.get("backup") and hasattr(self.modules["backup"], "start_backup_service"): + await self.modules["backup"].start_backup_service() + + # 启动VACUUM服务 + if self.modules.get("vacuum") and hasattr(self.modules["vacuum"], "start_vacuum_service"): + await self.modules["vacuum"].start_vacuum_service() + + # 创建物化视图 + if self.modules.get("query") and hasattr(self.modules["query"], "create_materialized_views"): + await self.modules["query"].create_materialized_views() + + self.services_running = True + logger.info("所有优化服务已启动") + return True + + except Exception as e: + logger.error(f"启动优化服务时出错: {e}") + return False + + async def stop_services(self): + """停止所有服务""" + if not self.services_running: + logger.info("服务未运行,无需停止") + return True + + try: + # 关闭连接池 + await close_pool() + + self.services_running = False + logger.info("所有优化服务已停止") + return True + + except Exception as e: + logger.error(f"停止优化服务时出错: {e}") + return False + + async def run_manual_vacuum(self, full: bool = False): + """手动执行VACUUM""" + if not self.modules.get("vacuum"): + logger.error("VACUUM模块未加载") + return False + + try: + if hasattr(self.modules["vacuum"], "vacuum_all_tables"): + result = await self.modules["vacuum"].vacuum_all_tables(full=full) + return result + return False + except Exception as e: + logger.error(f"执行手动VACUUM时出错: {e}") + return False + + async def create_backup(self): + """手动创建备份""" + if not self.modules.get("backup"): + logger.error("备份模块未加载") + return None + + try: + if hasattr(self.modules["backup"], "create_backup"): + result = await self.modules["backup"].create_backup() + return result + return None + except Exception as e: + logger.error(f"创建备份时出错: {e}") + return None + + async def optimize_query(self, query: str, params: list = None): + """分析并优化SQL查询""" + if not self.modules.get("query"): + logger.error("查询优化模块未加载") + return None + + try: + if hasattr(self.modules["query"], "optimize_query"): + result = await self.modules["query"].optimize_query(query, params) + return result + return None + except Exception as e: + logger.error(f"优化查询时出错: {e}") + return None + + async def refresh_views(self): + """刷新物化视图""" + if not self.modules.get("query"): + logger.error("查询优化模块未加载") + return False + + try: + if hasattr(self.modules["query"], "refresh_materialized_view"): + await self.modules["query"].refresh_materialized_view("xiuxian_user_stats") + await self.modules["query"].refresh_materialized_view("xiuxian_top_users") + logger.info("物化视图已刷新") + return True + return False + except Exception as e: + logger.error(f"刷新物化视图时出错: {e}") + return False + + def get_cached_query(self): + """获取缓存查询函数""" + if not self.modules.get("query"): + logger.error("查询优化模块未加载") + return None + + if hasattr(self.modules["query"], "cached_query"): + return self.modules["query"].cached_query + return None + + def get_monitored_query(self): + """获取监控查询函数""" + if not self.modules.get("query"): + logger.error("查询优化模块未加载") + return None + + if hasattr(self.modules["query"], "monitored_query"): + return self.modules["query"].monitored_query + return None + + def get_transaction_context(self): + """获取事务上下文管理器""" + if not self.modules.get("transaction"): + logger.error("事务优化模块未加载") + return None + + if hasattr(self.modules["transaction"], "transaction"): + return self.modules["transaction"].transaction + return None + + def get_lock_context(self): + """获取锁上下文管理器""" + if not self.modules.get("transaction"): + logger.error("事务优化模块未加载") + return None + + if hasattr(self.modules["transaction"], "with_lock"): + return self.modules["transaction"].with_lock + return None + + def get_retry_decorator(self): + """获取重试装饰器""" + if not self.modules.get("transaction"): + logger.error("事务优化模块未加载") + return None + + if hasattr(self.modules["transaction"], "retry_operation"): + return self.modules["transaction"].retry_operation + return None + +# 全局优化管理器实例 +_MANAGER = None + +def get_manager() -> OptimizationManager: + """获取优化管理器实例""" + global _MANAGER + + if _MANAGER is None: + _MANAGER = OptimizationManager() + + return _MANAGER + +async def apply_all_optimizations(pg_url: str): + """应用所有优化""" + global _INITIALIZED + + # 检查是否已初始化 + if _INITIALIZED: + logger.info("优化功能已应用,跳过重复初始化") + return True + + manager = get_manager() + + # 初始化管理器 + success = await manager.initialize(pg_url) + if not success: + logger.error("无法初始化优化管理器") + return False + + # 启动所有服务 + success = await manager.start_services() + if success: + _INITIALIZED = True + + return success \ No newline at end of file diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/player_fight.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/player_fight.py index e2586bbb..dd80c8b5 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/player_fight.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/player_fight.py @@ -1,12 +1,8 @@ import random -from .xiuxian2_handle import XiuxianDateManage, OtherSet, UserBuffDate, XIUXIAN_IMPART_BUFF +from .xiuxian2_handle import XiuxianDataManager, OtherSet, UserBuffData from ..xiuxian_config import convert_rank from .utils import number_to -sql_message = XiuxianDateManage() # sql类 -xiuxian_impart = XIUXIAN_IMPART_BUFF() - - class BossBuff: def __init__(self): self.boss_zs = 0 @@ -31,7 +27,7 @@ def __init__(self): empty_ussr_random_buff = UserRandomBuff() -def Player_fight(player1: dict, player2: dict, type_in, bot_id): +async def Player_fight(player1: dict, player2: dict, type_in, bot_id): """ 回合制战斗 type_in : 1-切磋,不消耗气血、真元 @@ -39,52 +35,52 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): 数据示例: {"user_id": None,"道号": None, "气血": None, "攻击": None, "真元": None, '会心':None, 'exp':None} """ - user1_buff_data = UserBuffDate(player1['user_id']) # 1号的buff信息 - user1_main_buff_data = user1_buff_data.get_user_main_buff_data() - user1_hp_buff = user1_main_buff_data['hpbuff'] if user1_main_buff_data is not None else 0 - user1_mp_buff = user1_main_buff_data['mpbuff'] if user1_main_buff_data is not None else 0 + user1_buff_data = UserBuffData(player1['user_id']) # 1号的buff信息 + user1_main_buff_data = await user1_buff_data.get_user_main_buff_data() + user1_hp_buff = user1_main_buff_data['hpbuf'] if user1_main_buff_data is not None else 0 + user1_mp_buff = user1_main_buff_data['mpbuf'] if user1_main_buff_data is not None else 0 try: - user_1_impart_data = xiuxian_impart.get_user_impart_info_with_id(player1['user_id']) - except: + user_1_impart_data = await XiuxianDataManager().get_user_impart_info_with_id(player1['user_id']) + except ValueError: user_1_impart_data = None - user_1_impart_hp = user_1_impart_data['impart_hp_per'] if user_1_impart_data is not None else 0 - user_1_impart_mp = user_1_impart_data['impart_mp_per'] if user_1_impart_data is not None else 0 + user_1_impart_hp = user_1_impart_data['impart_hp_addition'] if user_1_impart_data is not None else 0 + user_1_impart_mp = user_1_impart_data['impart_mp_addition'] if user_1_impart_data is not None else 0 user1_hp_buff = user1_hp_buff + user_1_impart_hp user1_mp_buff = user1_mp_buff + user_1_impart_mp - user2_buff_data = UserBuffDate(player2['user_id']) # 2号的buff信息 - user2_main_buff_data = user2_buff_data.get_user_main_buff_data() - user2_hp_buff = user2_main_buff_data['hpbuff'] if user2_main_buff_data is not None else 0 - user2_mp_buff = user2_main_buff_data['mpbuff'] if user2_main_buff_data is not None else 0 + user2_buff_data = UserBuffData(player2['user_id']) # 2号的buff信息 + user2_main_buff_data = await user2_buff_data.get_user_main_buff_data() + user2_hp_buff = user2_main_buff_data['hpbuf'] if user2_main_buff_data is not None else 0 + user2_mp_buff = user2_main_buff_data['mpbuf'] if user2_main_buff_data is not None else 0 try: - user_2_impart_data = xiuxian_impart.get_user_impart_info_with_id(player2['user_id']) - except: + user_2_impart_data = await XiuxianDataManager().get_user_impart_info_with_id(player2['user_id']) + except ValueError: user_2_impart_data = None - user_2_impart_hp = user_2_impart_data['impart_hp_per'] if user_2_impart_data is not None else 0 - user_2_impart_mp = user_2_impart_data['impart_mp_per'] if user_2_impart_data is not None else 0 + user_2_impart_hp = user_2_impart_data['impart_hp_addition'] if user_2_impart_data is not None else 0 + user_2_impart_mp = user_2_impart_data['impart_mp_addition'] if user_2_impart_data is not None else 0 user2_hp_buff = user2_hp_buff + user_2_impart_hp user2_mp_buff = user2_mp_buff + user_2_impart_mp player1_skil_open = False player2_skil_open = False user1_skill_data = None - if user1_buff_data.get_user_sec_buff_data() is not None: - user1_skill_data = user1_buff_data.get_user_sec_buff_data() + if await user1_buff_data.get_user_sec_buff_data() is not None: + user1_skill_data = await user1_buff_data.get_user_sec_buff_data() player1_skil_open = True user2_skill_date = None - if user2_buff_data.get_user_sec_buff_data() is not None: - user2_skill_date = user2_buff_data.get_user_sec_buff_data() + if await user2_buff_data.get_user_sec_buff_data() is not None: + user2_skill_date = await user2_buff_data.get_user_sec_buff_data() player2_skil_open = True player1_sub_open = False # 辅修功法14 player2_sub_open = False user1_sub_buff_date = {} user2_sub_buff_date = {} - if user1_buff_data.get_user_sub_buff_data() != None: - user1_sub_buff_date = user1_buff_data.get_user_sub_buff_data() + if await user1_buff_data.get_user_sub_buff_data() is not None: + user1_sub_buff_date = await user1_buff_data.get_user_sub_buff_data() player1_sub_open = True - if user2_buff_data.get_user_sub_buff_data() != None: - user2_sub_buff_date = user2_buff_data.get_user_sub_buff_data() + if await user2_buff_data.get_user_sub_buff_data() is not None: + user2_sub_buff_date = await user2_buff_data.get_user_sub_buff_data() player2_sub_open = True play_list = [] @@ -99,8 +95,8 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): player1_turn_cost = 0 # 先设定为初始值 0 player2_turn_cost = 0 - player1_f_js = get_user_def_buff(player1['user_id']) # 玩家1减伤 - player2_f_js = get_user_def_buff(player2['user_id']) # 玩家2减伤 + player1_f_js = await get_user_def_buff(player1['user_id']) # 玩家1减伤 + player2_f_js = await get_user_def_buff(player2['user_id']) # 玩家2减伤 player1_js = player1_f_js player2_js = player2_f_js user1_skill_sh = 0 @@ -108,38 +104,61 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): user1_buff_turn = True user2_buff_turn = True - user1_battle_buff_date = UserBattleBuffDate(player1['user_id']) # 1号的战斗buff信息 - user2_battle_buff_date = UserBattleBuffDate(player2['user_id']) # 2号的战斗buff信息 + user1_battle_buff_data = UserBattleBuffData(player1['user_id']) # 1号的战斗buff信息 + user2_battle_buff_data = UserBattleBuffData(player2['user_id']) # 2号的战斗buff信息 + + # 最大回合数 + max_rounds = 10 + current_round = 0 while True: - msg1 = "{}发起攻击,造成了{}伤害\n" - msg2 = "{}发起攻击,造成了{}伤害\n" + current_round += 1 - user1_battle_buff_date, user2_battle_buff_date, msg = start_sub_buff_handle(player1_sub_open, + if current_round > max_rounds: + play_list.append( + {"type": "node", "data": {"name": "Bot", "uin": int(bot_id), "content": f"战斗已持续{max_rounds}回合,双方平分秋色!"}}) + suc = "平局" + if isSql: + await XiuxianDataManager().update_user_hp_mp( + player1['user_id'], + int(player1['气血'] / (1 + user1_hp_buff)), + int(player1['真元'] / (1 + user1_mp_buff)) + ) + await XiuxianDataManager().update_user_hp_mp( + player2['user_id'], + int(player2['气血'] / (1 + user2_hp_buff)), + int(player2['真元'] / (1 + user2_mp_buff)) + ) + break + + msg1 = "{}发起攻击,造成了{}点伤害\n" + msg2 = "{}发起攻击,造成了{}点伤害\n" + + user1_battle_buff_data, user2_battle_buff_data, msg = await start_sub_buff_handle(player1_sub_open, user1_sub_buff_date, - user1_battle_buff_date, + user1_battle_buff_data, player2_sub_open, user2_sub_buff_date, - user2_battle_buff_date) + user2_battle_buff_data) play_list.append(get_msg_dict(player1, player1_init_hp, msg)) # 辅修功法14 player2_health_temp = player2['气血'] if player1_skil_open: # 是否开启技能 if user1_turn_skip: # 无需跳过回合 play_list.append(get_msg_dict(player1, player1_init_hp, f"☆------{player1['道号']}的回合------☆")) - user1_hp_cost, user1_mp_cost, user1_skill_type, skill_rate = get_skill_hp_mp_data(player1, + user1_hp_cost, user1_mp_cost, user1_skill_type, skill_rate = await get_skill_hp_mp_data(player1, user1_skill_data) if player1_turn_cost == 0: # 没有持续性技能生效 player1_js = player1_f_js # 没有持续性技能生效,减伤恢复 if isEnableUserSikll(player1, user1_hp_cost, user1_mp_cost, player1_turn_cost, skill_rate): # 满足技能要求,#此处为技能的第一次释放 - skill_msg, user1_skill_sh, player1_turn_cost = get_skill_sh_data(player1, user1_skill_data) + skill_msg, user1_skill_sh, player1_turn_cost = await get_skill_sh_data(player1, user1_skill_data) if user1_skill_type == 1: # 直接伤害类技能 play_list.append(get_msg_dict(player1, player1_init_hp, skill_msg)) player1 = calculate_skill_cost(player1, user1_hp_cost, user1_mp_cost) player2['气血'] = player2['气血'] - int(user1_skill_sh * player2_js) # 玩家1的伤害 * 玩家2的减伤 play_list.append( - get_msg_dict(player1, player1_init_hp, f"{player2['道号']}剩余血量{player2['气血']}")) + get_msg_dict(player1, player1_init_hp, f"{player2['道号']}剩余血量{number_to(player2['气血'])}")) elif user1_skill_type == 2: # 持续性伤害技能 play_list.append(get_msg_dict(player1, player1_init_hp, skill_msg)) @@ -147,41 +166,41 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): player2['气血'] = player2['气血'] - int( user1_skill_sh * (0.2 + player2_js)) # 玩家1的伤害 * 玩家2的减伤 play_list.append( - get_msg_dict(player1, player1_init_hp, f"{player2['道号']}剩余血量{player2['气血']}")) + get_msg_dict(player1, player1_init_hp, f"{player2['道号']}剩余血量{number_to(player2['气血'])}")) elif user1_skill_type == 3: # buff类技能 user1_buff_type = user1_skill_data['bufftype'] if user1_buff_type == 1: # 攻击类buff - isCrit, player1_sh = get_turnatk(player1, user1_skill_sh, - user1_battle_buff_date) # 判定是否暴击 辅修功法14 + isCrit, player1_sh = await get_turnatk(player1, user1_skill_sh, + user1_battle_buff_data) # 判定是否暴击 辅修功法14 if isCrit: - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" else: - msg1 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" player1 = calculate_skill_cost(player1, user1_hp_cost, user1_mp_cost) play_list.append(get_msg_dict(player1, player1_init_hp, skill_msg)) play_list.append( - get_msg_dict(player1, player1_init_hp, msg1.format(player1['道号'], player1_sh))) + get_msg_dict(player1, player1_init_hp, msg1.format(player1['道号'], number_to(player1_sh)))) player2['气血'] = player2['气血'] - int(player1_sh * player2_js) # 玩家1的伤害 * 玩家2的减伤 play_list.append( get_msg_dict(player1, player1_init_hp, - f"{player2['道号']}剩余血量{player2['气血']}")) + f"{player2['道号']}剩余血量{number_to(player2['气血'])}")) elif user1_buff_type == 2: # 减伤类buff,需要在player2处判断 - isCrit, player1_sh = get_turnatk(player1, 0, user1_battle_buff_date) # 判定是否暴击 辅修功法14 + isCrit, player1_sh = await get_turnatk(player1, 0, user1_battle_buff_data) # 判定是否暴击 辅修功法14 if isCrit: - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" else: - msg1 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" player1 = calculate_skill_cost(player1, user1_hp_cost, user1_mp_cost) play_list.append(get_msg_dict(player1, player1_init_hp, skill_msg)) play_list.append( - get_msg_dict(player1, player1_init_hp, msg1.format(player1['道号'], player1_sh))) + get_msg_dict(player1, player1_init_hp, msg1.format(player1['道号'], number_to(player1_sh)))) player2['气血'] = player2['气血'] - int(player1_sh * player2_js) # 玩家1的伤害 * 玩家2的减伤 play_list.append( get_msg_dict(player1, player1_init_hp, - f"{player2['道号']}剩余血量{player2['气血']}")) + f"{player2['道号']}剩余血量{number_to(player2['气血'])}")) player1_js = player1_f_js - user1_skill_sh if player1_f_js - user1_skill_sh > 0.1 else 0.1 elif user1_skill_type == 4: # 封印类技能 @@ -193,16 +212,16 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): user2_buff_turn = False else: # 没放技能,打一拳 - isCrit, player1_sh = get_turnatk(player1, 0, user1_battle_buff_date) # 判定是否暴击 辅修功法14 + isCrit, player1_sh = await get_turnatk(player1, 0, user1_battle_buff_data) # 判定是否暴击 辅修功法14 if isCrit: - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" else: - msg1 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" play_list.append( - get_msg_dict(player1, player1_init_hp, msg1.format(player1['道号'], player1_sh))) + get_msg_dict(player1, player1_init_hp, msg1.format(player1['道号'], number_to(player1_sh)))) player2['气血'] = player2['气血'] - int(player1_sh * player2_js) # 玩家1的伤害 * 玩家2的减伤 play_list.append( - get_msg_dict(player1, player1_init_hp, f"{player2['道号']}剩余血量{player2['气血']}")) + get_msg_dict(player1, player1_init_hp, f"{player2['道号']}剩余血量{number_to(player2['气血'])}")) else: # 持续性技能判断,不是第一次 if user1_skill_type == 2: # 持续性伤害技能 @@ -210,53 +229,53 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): skill_msg = get_persistent_skill_msg(player1['道号'], user1_skill_data['name'], user1_skill_sh, player1_turn_cost) play_list.append(get_msg_dict(player1, player1_init_hp, skill_msg)) - isCrit, player1_sh = get_turnatk(player1, 0, user1_battle_buff_date) # 判定是否暴击 辅修功法14 + isCrit, player1_sh = await get_turnatk(player1, 0, user1_battle_buff_data) # 判定是否暴击 辅修功法14 if isCrit: - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" else: - msg1 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" play_list.append( - get_msg_dict(player1, player1_init_hp, msg1.format(player1['道号'], player1_sh))) + get_msg_dict(player1, player1_init_hp, msg1.format(player1['道号'], number_to(player1_sh)))) # 玩家1的伤害 * 玩家2的减伤,持续性伤害不影响普攻 player2['气血'] = player2['气血'] - int((user1_skill_sh + player1_sh) * player2_js) play_list.append( - get_msg_dict(player1, player1_init_hp, f"{player2['道号']}剩余血量{player2['气血']}")) + get_msg_dict(player1, player1_init_hp, f"{player2['道号']}剩余血量{number_to(player2['气血'])}")) elif user1_skill_type == 3: # buff类技能 user1_buff_type = user1_skill_data['bufftype'] if user1_buff_type == 1: # 攻击类buff - isCrit, player1_sh = get_turnatk(player1, user1_skill_sh, - user1_battle_buff_date) # 判定是否暴击 辅修功法14 + isCrit, player1_sh = await get_turnatk(player1, user1_skill_sh, + user1_battle_buff_data) # 判定是否暴击 辅修功法14 if isCrit: - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" else: - msg1 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" player1_turn_cost = player1_turn_cost - 1 play_list.append(get_msg_dict(player1, player1_init_hp, f"{user1_skill_data['name']}增伤剩余:{player1_turn_cost}回合")) play_list.append( - get_msg_dict(player1, player1_init_hp, msg1.format(player1['道号'], player1_sh))) + get_msg_dict(player1, player1_init_hp, msg1.format(player1['道号'], number_to(player1_sh)))) player2['气血'] = player2['气血'] - int(player1_sh * player2_js) # 玩家1的伤害 * 玩家2的减伤 play_list.append( - get_msg_dict(player1, player1_init_hp, f"{player2['道号']}剩余血量{player2['气血']}")) + get_msg_dict(player1, player1_init_hp, f"{player2['道号']}剩余血量{number_to(player2['气血'])}")) elif user1_buff_type == 2: # 减伤类buff,需要在player2处判断 - isCrit, player1_sh = get_turnatk(player1, 0, user1_battle_buff_date) # 判定是否暴击 辅修功法14 + isCrit, player1_sh = await get_turnatk(player1, 0, user1_battle_buff_data) # 判定是否暴击 辅修功法14 if isCrit: - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" else: - msg1 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" player1_turn_cost = player1_turn_cost - 1 play_list.append(get_msg_dict(player1, player1_init_hp, f"{user1_skill_data['name']}减伤剩余{player1_turn_cost}回合")) play_list.append( - get_msg_dict(player1, player1_init_hp, msg1.format(player1['道号'], player1_sh))) + get_msg_dict(player1, player1_init_hp, msg1.format(player1['道号'], number_to(player1_sh)))) player2['气血'] = player2['气血'] - int(player1_sh * player2_js) # 玩家1的伤害 * 玩家2的减伤 play_list.append( - get_msg_dict(player1, player1_init_hp, f"{player2['道号']}剩余血量{player2['气血']}")) + get_msg_dict(player1, player1_init_hp, f"{player2['道号']}剩余血量{number_to(player2['气血'])}")) player1_js = player1_f_js - user1_skill_sh if player2_f_js - user1_skill_sh > 0.1 else 0.1 elif user1_skill_type == 4: # 封印类技能 @@ -264,17 +283,17 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): skill_msg = get_persistent_skill_msg(player1['道号'], user1_skill_data['name'], user1_skill_sh, player1_turn_cost) play_list.append(get_msg_dict(player1, player1_init_hp, skill_msg)) - isCrit, player1_sh = get_turnatk(player1, 0, user1_battle_buff_date) # 判定是否暴击 辅修功法14 + isCrit, player1_sh = await get_turnatk(player1, 0, user1_battle_buff_data) # 判定是否暴击 辅修功法14 if isCrit: - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" else: - msg1 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" play_list.append( - get_msg_dict(player1, player1_init_hp, msg1.format(player1['道号'], player1_sh))) + get_msg_dict(player1, player1_init_hp, msg1.format(player1['道号'], number_to(player1_sh)))) player2['气血'] = player2['气血'] - int(player1_sh * player2_js) # 玩家1的伤害 * 玩家2的减伤 play_list.append( - get_msg_dict(player1, player1_init_hp, f"{player2['道号']}剩余血量{player2['气血']}")) + get_msg_dict(player1, player1_init_hp, f"{player2['道号']}剩余血量{number_to(player2['气血'])}")) if player1_turn_cost == 0: # 封印时间到 user2_turn_skip = True user2_buff_turn = True @@ -289,20 +308,20 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): else: # 没有技能的derB if user1_turn_skip: play_list.append(get_msg_dict(player1, player1_init_hp, f"☆------{player1['道号']}的回合------☆")) - isCrit, player1_sh = get_turnatk(player1, 0, user1_battle_buff_date) # 判定是否暴击 辅修功法14 + isCrit, player1_sh = await get_turnatk(player1, 0, user1_battle_buff_data) # 判定是否暴击 辅修功法14 if isCrit: - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" else: - msg1 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" play_list.append(get_msg_dict(player1, player1_init_hp, msg1.format(player1['道号'], player1_sh))) player2['气血'] = player2['气血'] - player1_sh - play_list.append(get_msg_dict(player1, player1_init_hp, f"{player2['道号']}剩余血量{player2['气血']}")) + play_list.append(get_msg_dict(player1, player1_init_hp, f"{player2['道号']}剩余血量{number_to(player2['气血'])}")) else: play_list.append(get_msg_dict(player1, player1_init_hp, f"☆------{player1['道号']}动弹不得!------☆")) ## 自己回合结束 处理 辅修功法14 - player1, boss, msg = after_atk_sub_buff_handle(player1_sub_open, player1, user1_main_buff_data, + player1, boss, msg = await after_atk_sub_buff_handle(player1_sub_open, player1, user1_main_buff_data, user1_sub_buff_date, player2_health_temp - player2['气血'], player2) play_list.append(get_msg_dict(player1, player1_init_hp, msg)) @@ -316,12 +335,12 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): if player1['气血'] <= 0: player1['气血'] = 1 # - sql_message.update_user_hp_mp( + await XiuxianDataManager().update_user_hp_mp( player1['user_id'], int(player1['气血'] / (1 + user1_hp_buff)), int(player1['真元'] / (1 + user1_mp_buff)) ) - sql_message.update_user_hp_mp(player2['user_id'], 1, int(player2['真元'] / (1 + user2_mp_buff))) + await XiuxianDataManager().update_user_hp_mp(player2['user_id'], 1, int(player2['真元'] / (1 + user2_mp_buff))) break if player1_turn_cost < 0: # 休息为负数,如果休息,则跳过回合,正常是0 @@ -332,18 +351,18 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): if player2_skil_open: # 有技能 if user2_turn_skip: # 玩家2无需跳过回合 play_list.append(get_msg_dict(player2, player2_init_hp, f"☆------{player2['道号']}的回合------☆")) - user2_hp_cost, user2_mp_cost, user2_skill_type, skill_rate = get_skill_hp_mp_data(player2, + user2_hp_cost, user2_mp_cost, user2_skill_type, skill_rate = await get_skill_hp_mp_data(player2, user2_skill_date) if player2_turn_cost == 0: # 没有持续性技能生效 player2_js = player2_f_js if isEnableUserSikll(player2, user2_hp_cost, user2_mp_cost, player2_turn_cost, skill_rate): # 满足技能要求,#此处为技能的第一次释放 - skill_msg, user2_skill_sh, player2_turn_cost = get_skill_sh_data(player2, user2_skill_date) + skill_msg, user2_skill_sh, player2_turn_cost = await get_skill_sh_data(player2, user2_skill_date) if user2_skill_type == 1: # 直接伤害类技能 play_list.append(get_msg_dict(player2, player2_init_hp, skill_msg)) player1['气血'] = player1['气血'] - int(user2_skill_sh * player1_js) # 玩家2的伤害 * 玩家1的减伤 play_list.append( - get_msg_dict(player2, player2_init_hp, f"{player1['道号']}剩余血量{player1['气血']}")) + get_msg_dict(player2, player2_init_hp, f"{player1['道号']}剩余血量{number_to(player1['气血'])}")) player2 = calculate_skill_cost(player2, user2_hp_cost, user2_mp_cost) elif user2_skill_type == 2: # 持续性伤害技能 @@ -351,41 +370,41 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): player1['气血'] = player1['气血'] - int( user2_skill_sh * (0.2 + player1_js)) # 玩家2的伤害 * 玩家1的减伤 play_list.append( - get_msg_dict(player2, player2_init_hp, f"{player1['道号']}剩余血量{player1['气血']}")) + get_msg_dict(player2, player2_init_hp, f"{player1['道号']}剩余血量{number_to(player1['气血'])}")) player2 = calculate_skill_cost(player2, user2_hp_cost, user2_mp_cost) elif user2_skill_type == 3: # buff类技能 user2_buff_type = user2_skill_date['bufftype'] if user2_buff_type == 1: # 攻击类buff - isCrit, player2_sh = get_turnatk(player2, user2_skill_sh, - user2_battle_buff_date) # 判定是否暴击 辅修功法14 + isCrit, player2_sh = await get_turnatk(player2, user2_skill_sh, + user2_battle_buff_data) # 判定是否暴击 辅修功法14 if isCrit: - msg2 = "{}发起会心一击,造成了{}伤害\n" + msg2 = "{}发起会心一击,造成了{}点伤害\n" else: - msg2 = "{}发起攻击,造成了{}伤害\n" + msg2 = "{}发起攻击,造成了{}点伤害\n" play_list.append(get_msg_dict(player2, player2_init_hp, skill_msg)) play_list.append( - get_msg_dict(player2, player2_init_hp, msg2.format(player2['道号'], player2_sh))) + get_msg_dict(player2, player2_init_hp, msg2.format(player2['道号'], number_to(player2_sh)))) player1['气血'] = player1['气血'] - int(player2_sh * player1_js) play_list.append( get_msg_dict(player2, player2_init_hp, - f"{player1['道号']}剩余血量{player1['气血']}")) + f"{player1['道号']}剩余血量{number_to(player1['气血'])}")) player2 = calculate_skill_cost(player2, user2_hp_cost, user2_mp_cost) elif user2_buff_type == 2: # 减伤类buff,需要在player2处判断 - isCrit, player2_sh = get_turnatk(player2, 0, user2_battle_buff_date) # 判定是否暴击 辅修功法14 + isCrit, player2_sh = await get_turnatk(player2, 0, user2_battle_buff_data) # 判定是否暴击 辅修功法14 if isCrit: - msg2 = "{}发起会心一击,造成了{}伤害\n" + msg2 = "{}发起会心一击,造成了{}点伤害\n" else: - msg2 = "{}发起攻击,造成了{}伤害\n" + msg2 = "{}发起攻击,造成了{}点伤害\n" play_list.append(get_msg_dict(player2, player2_init_hp, skill_msg)) play_list.append( - get_msg_dict(player2, player2_init_hp, msg2.format(player2['道号'], player2_sh))) + get_msg_dict(player2, player2_init_hp, msg2.format(player2['道号'], number_to(player2_sh)))) player1['气血'] = player1['气血'] - int(player2_sh * player1_js) play_list.append( get_msg_dict(player2, player2_init_hp, - f"{player1['道号']}剩余血量{player1['气血']}")) + f"{player1['道号']}剩余血量{number_to(player1['气血'])}")) player2_js = player2_f_js - user2_skill_sh if player2_f_js - user2_skill_sh > 0.1 else 0.1 player2 = calculate_skill_cost(player2, user2_hp_cost, user2_mp_cost) @@ -398,16 +417,16 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): user1_buff_turn = False else: # 没放技能 - isCrit, player2_sh = get_turnatk(player2, 0, user2_battle_buff_date) # 判定是否暴击 辅修功法14 + isCrit, player2_sh = await get_turnatk(player2, 0, user2_battle_buff_data) # 判定是否暴击 辅修功法14 if isCrit: - msg2 = "{}发起会心一击,造成了{}伤害\n" + msg2 = "{}发起会心一击,造成了{}点伤害\n" else: - msg2 = "{}发起攻击,造成了{}伤害\n" + msg2 = "{}发起攻击,造成了{}点伤害\n" play_list.append( - get_msg_dict(player2, player2_init_hp, msg2.format(player2['道号'], player2_sh))) + get_msg_dict(player2, player2_init_hp, msg2.format(player2['道号'], number_to(player2_sh)))) player1['气血'] = player1['气血'] - int(player2_sh * player1_js) # 玩家2的伤害 * 玩家1的减伤 play_list.append( - get_msg_dict(player2, player2_init_hp, f"{player1['道号']}剩余血量{player1['气血']}")) + get_msg_dict(player2, player2_init_hp, f"{player1['道号']}剩余血量{number_to(player1['气血'])}")) else: # 持续性技能判断,不是第一次 if user2_skill_type == 2: # 持续性伤害技能 @@ -416,52 +435,52 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): player2_turn_cost) play_list.append(get_msg_dict(player2, player2_init_hp, skill_msg)) - isCrit, player2_sh = get_turnatk(player2, 0, user2_battle_buff_date) # 判定是否暴击 辅修功法14 + isCrit, player2_sh = await get_turnatk(player2, 0, user2_battle_buff_data) # 判定是否暴击 辅修功法14 if isCrit: - msg2 = "{}发起会心一击,造成了{}伤害\n" + msg2 = "{}发起会心一击,造成了{}点伤害\n" else: - msg2 = "{}发起攻击,造成了{}伤害\n" + msg2 = "{}发起攻击,造成了{}点伤害\n" play_list.append( - get_msg_dict(player2, player2_init_hp, msg2.format(player2['道号'], player2_sh))) + get_msg_dict(player2, player2_init_hp, msg2.format(player2['道号'], number_to(player2_sh)))) player1['气血'] = player1['气血'] - int((user2_skill_sh + player2_sh) * player1_js) play_list.append( - get_msg_dict(player2, player2_init_hp, f"{player1['道号']}剩余血量{player1['气血']}")) + get_msg_dict(player2, player2_init_hp, f"{player1['道号']}剩余血量{number_to(player1['气血'])}")) elif user2_skill_type == 3: # buff类技能 user2_buff_type = user2_skill_date['bufftype'] if user2_buff_type == 1: # 攻击类buff - isCrit, player2_sh = get_turnatk(player2, user2_skill_sh, - user2_battle_buff_date) # 判定是否暴击 辅修功法14 + isCrit, player2_sh = await get_turnatk(player2, user2_skill_sh, + user2_battle_buff_data) # 判定是否暴击 辅修功法14 if isCrit: - msg2 = "{}发起会心一击,造成了{}伤害\n" + msg2 = "{}发起会心一击,造成了{}点伤害\n" else: - msg2 = "{}发起攻击,造成了{}伤害\n" + msg2 = "{}发起攻击,造成了{}点伤害\n" player2_turn_cost = player2_turn_cost - 1 play_list.append(get_msg_dict(player2, player2_init_hp, f"{user2_skill_date['name']}增伤剩余{player2_turn_cost}回合")) play_list.append( - get_msg_dict(player2, player2_init_hp, msg2.format(player2['道号'], player2_sh))) + get_msg_dict(player2, player2_init_hp, msg2.format(player2['道号'], number_to(player2_sh)))) player1['气血'] = player1['气血'] - int(player2_sh * player1_js) # 玩家2的伤害 * 玩家1的减伤 play_list.append( - get_msg_dict(player2, player2_init_hp, f"{player1['道号']}剩余血量{player1['气血']}")) + get_msg_dict(player2, player2_init_hp, f"{player1['道号']}剩余血量{number_to(player1['气血'])}")) elif user2_buff_type == 2: # 减伤类buff,需要在player2处判断 - isCrit, player2_sh = get_turnatk(player2, 0, user2_battle_buff_date) # 判定是否暴击 辅修功法14 + isCrit, player2_sh = await get_turnatk(player2, 0, user2_battle_buff_data) # 判定是否暴击 辅修功法14 if isCrit: - msg2 = "{}发起会心一击,造成了{}伤害\n" + msg2 = "{}发起会心一击,造成了{}点伤害\n" else: - msg2 = "{}发起攻击,造成了{}伤害\n" + msg2 = "{}发起攻击,造成了{}点伤害\n" player2_turn_cost = player2_turn_cost - 1 play_list.append(get_msg_dict(player2, player2_init_hp, f"{user2_skill_date['name']}减伤剩余{player2_turn_cost}回合!")) play_list.append( - get_msg_dict(player2, player2_init_hp, msg2.format(player2['道号'], player2_sh))) + get_msg_dict(player2, player2_init_hp, msg2.format(player2['道号'], number_to(player2_sh)))) player1['气血'] = player1['气血'] - int(player2_sh * player1_js) # 玩家1的伤害 * 玩家2的减伤 play_list.append( - get_msg_dict(player2, player2_init_hp, f"{player1['道号']}剩余血量{player1['气血']}")) + get_msg_dict(player2, player2_init_hp, f"{player1['道号']}剩余血量{number_to(player1['气血'])}")) player2_js = player2_f_js - user2_skill_sh if player2_f_js - user2_skill_sh > 0.1 else 0.1 @@ -471,16 +490,16 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): player2_turn_cost) play_list.append(get_msg_dict(player2, player2_init_hp, skill_msg)) - isCrit, player2_sh = get_turnatk(player2, 0, user2_battle_buff_date) # 判定是否暴击 辅修功法14 + isCrit, player2_sh = await get_turnatk(player2, 0, user2_battle_buff_data) # 判定是否暴击 辅修功法14 if isCrit: - msg2 = "{}发起会心一击,造成了{}伤害\n" + msg2 = "{}发起会心一击,造成了{}点伤害\n" else: - msg2 = "{}发起攻击,造成了{}伤害\n" + msg2 = "{}发起攻击,造成了{}点伤害\n" play_list.append( - get_msg_dict(player2, player2_init_hp, msg2.format(player2['道号'], player2_sh))) + get_msg_dict(player2, player2_init_hp, msg2.format(player2['道号'], number_to(player2_sh)))) player1['气血'] = player1['气血'] - int(player2_sh * player1_js) # 玩家1的伤害 * 玩家2的减伤 play_list.append( - get_msg_dict(player2, player2_init_hp, f"{player1['道号']}剩余血量{player1['气血']}")) + get_msg_dict(player2, player2_init_hp, f"{player1['道号']}剩余血量{number_to(player1['气血'])}")) if player2_turn_cost == 0: # 封印时间到 user1_turn_skip = True @@ -495,14 +514,14 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): else: # 没有技能的derB if user2_turn_skip: play_list.append(get_msg_dict(player2, player2_init_hp, f"☆------{player2['道号']}的回合------☆")) - isCrit, player2_sh = get_turnatk(player2, 0, user2_battle_buff_date) # 判定是否暴击 辅修功法14 + isCrit, player2_sh = await get_turnatk(player2, 0, user2_battle_buff_data) # 判定是否暴击 辅修功法14 if isCrit: - msg2 = "{}发起会心一击,造成了{}伤害\n" + msg2 = "{}发起会心一击,造成了{}点伤害\n" else: - msg2 = "{}发起攻击,造成了{}伤害\n" - play_list.append(get_msg_dict(player2, player2_init_hp, msg2.format(player2['道号'], player2_sh))) + msg2 = "{}发起攻击,造成了{}点伤害\n" + play_list.append(get_msg_dict(player2, player2_init_hp, msg2.format(player2['道号'], number_to(player2_sh)))) player1['气血'] = player1['气血'] - player2_sh - play_list.append(get_msg_dict(player2, player2_init_hp, f"{player1['道号']}剩余血量{player1['气血']}")) + play_list.append(get_msg_dict(player2, player2_init_hp, f"{player1['道号']}剩余血量{number_to(player1['气血'])}")) else: play_list.append(get_msg_dict(player2, player2_init_hp, f"☆------{player2['道号']}动弹不得!------☆")) @@ -512,12 +531,12 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): {"type": "node", "data": {"name": "Bot", "uin": int(bot_id), "content": f"{player2['道号']}胜利"}}) suc = f"{player2['道号']}" if isSql: - sql_message.update_user_hp_mp(player1['user_id'], 1, int(player1['真元'] / (1 + user1_mp_buff))) + await XiuxianDataManager().update_user_hp_mp(player1['user_id'], 1, int(player1['真元'] / (1 + user1_mp_buff))) # if player2['气血'] <= 0: player2['气血'] = 1 # - sql_message.update_user_hp_mp( + await XiuxianDataManager().update_user_hp_mp( player2['user_id'], int(player2['气血'] / (1 + user2_hp_buff)), int(player2['真元'] / (1 + user2_mp_buff)) @@ -525,7 +544,7 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): break ## 对方回合结束 处理 辅修功法14 - player2, player1, msg = after_atk_sub_buff_handle(player2_sub_open, player2, user2_main_buff_data, + player2, player1, msg = await after_atk_sub_buff_handle(player2_sub_open, player2, user2_main_buff_data, user2_sub_buff_date, player1_health_temp - player1['气血'], player1) play_list.append(get_msg_dict(player1, player1_init_hp, msg)) @@ -535,8 +554,8 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): "data": {"name": "Bot", "uin": int(bot_id), "content": f"{player2['道号']}胜利"}}) suc = f"{player2['道号']}" if isSql: - sql_message.update_user_hp_mp(player1['user_id'], 1, int(player1['真元'] / (1 + user1_mp_buff))) - sql_message.update_user_hp_mp(player2['user_id'], int(player2['气血'] / (1 + user2_hp_buff)), + await XiuxianDataManager().update_user_hp_mp(player1['user_id'], 1, int(player1['真元'] / (1 + user1_mp_buff))) + await XiuxianDataManager().update_user_hp_mp(player2['user_id'], int(player2['气血'] / (1 + user2_hp_buff)), int(player2['真元'] / (1 + user2_mp_buff))) break @@ -544,7 +563,7 @@ def Player_fight(player1: dict, player2: dict, type_in, bot_id): user2_turn_skip = False player2_turn_cost += 1 - if user1_turn_skip == False and user2_turn_skip == False: + if user1_turn_skip is False and user2_turn_skip is False: play_list.append( {"type": "node", "data": {"name": "Bot", "uin": int(bot_id), "content": "双方都动弹不得!"}}) user1_turn_skip = True @@ -574,7 +593,7 @@ def get_dict_type_rate(data_dict): for i, v in data_dict.items(): try: temp_dict[i] = v["type_rate"] - except: + except ValueError: continue key = OtherSet().calculated(temp_dict) return key @@ -618,25 +637,25 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): 数据示例: {"user_id": None,"道号": None, "气血": None, "攻击": None, "真元": None, '会心':None, 'exp':None} """ - user1_buff_date = UserBuffDate(player1['user_id']) # 1号的buff信息 + user1_buff_date = UserBuffData(player1['user_id']) # 1号的buff信息 if user1_buff_date is None: # 处理为空的情况 user1_main_buff_data = None user1_sub_buff_data = None else: - user1_main_buff_data = user1_buff_date.get_user_main_buff_data() - user1_sub_buff_data = user1_buff_date.get_user_sub_buff_data() # 获取玩家1的辅修功法 - user1_hp_buff = user1_main_buff_data['hpbuff'] if user1_main_buff_data is not None else 0 - user1_mp_buff = user1_main_buff_data['mpbuff'] if user1_main_buff_data is not None else 0 - user1_random_buff = user1_main_buff_data['random_buff'] if user1_main_buff_data is not None else 0 + user1_main_buff_data = await user1_buff_date.get_user_main_buff_data() + user1_sub_buff_data = await user1_buff_date.get_user_sub_buff_data() # 获取玩家1的辅修功法 + user1_hp_buff = user1_main_buff_data['hpbuf'] if user1_main_buff_data is not None else 0 + user1_mp_buff = user1_main_buff_data['mpbuf'] if user1_main_buff_data is not None else 0 + user1_random_buff = user1_main_buff_data['random_buf'] if user1_main_buff_data is not None else 0 fan_buff = user1_sub_buff_data['fan'] if user1_sub_buff_data is not None else 0 stone_buff = user1_sub_buff_data['stone'] if user1_sub_buff_data is not None else 0 - integral_buff = user1_sub_buff_data['integral'] if user1_sub_buff_data is not None else 0 + # integral_buff = user1_sub_buff_data['integral'] if user1_sub_buff_data is not None else 0 sub_break = user1_sub_buff_data['break'] if user1_sub_buff_data is not None else 0 - impart_data = xiuxian_impart.get_user_impart_info_with_id(player1['user_id']) - impart_hp_per = impart_data['impart_hp_per'] if impart_data is not None else 0 - impart_mp_per = impart_data['impart_mp_per'] if impart_data is not None else 0 - user1_hp_buff = user1_hp_buff + impart_hp_per - user1_mp_buff = user1_mp_buff + impart_mp_per + impart_data = await XiuxianDataManager().get_user_impart_info_with_id(player1['user_id']) + impart_hp_addition = impart_data['impart_hp_addition'] if impart_data is not None else 0 + impart_mp_addition = impart_data['impart_mp_addition'] if impart_data is not None else 0 + user1_hp_buff = user1_hp_buff + impart_hp_addition + user1_mp_buff = user1_mp_buff + impart_mp_addition random_buff = UserRandomBuff() if user1_random_buff == 1: @@ -670,37 +689,37 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): "元磁道人": "元磁道人使用了法宝:元磁神山!", "散发着威压的尸体": "尸体周围爆发了出强烈的罡气!" } - BOSSATK = { - "衣以候": "衣以侯布下了禁制镜花水月,", - "金凰儿": "金凰儿使用了神通:金凰天火罩!", - "九寒": "九寒使用了神通:寒冰八脉!", - "莫女": "莫女使用了神通:圣灯启语诀!", - "术方": "术方使用了神通:天罡咒!", - "卫起": "卫起使用了神通:雷公铸骨!", - "血枫": "血枫使用了神通:混世魔身!", - "以向": "以向使用了神通:云床九练!", - "砂鲛": "不说了!开鳖!", - "神风王": "不说了!开鳖!", - "鲲鹏": "鲲鹏使用了神通:逍遥游!", - "天龙": "天龙使用了神通:真龙九变!", - "历飞雨": "厉飞雨使用了神通:天煞震狱功!", - "外道贩卖鬼": "不说了!开鳖!", - "元磁道人": "元磁道人使用了法宝:元磁神山!", - "散发着威压的尸体": "尸体周围爆发了出强烈的罡气!" - } + # BOSSATK = { + # "衣以候": "衣以侯布下了禁制镜花水月,", + # "金凰儿": "金凰儿使用了神通:金凰天火罩!", + # "九寒": "九寒使用了神通:寒冰八脉!", + # "莫女": "莫女使用了神通:圣灯启语诀!", + # "术方": "术方使用了神通:天罡咒!", + # "卫起": "卫起使用了神通:雷公铸骨!", + # "血枫": "血枫使用了神通:混世魔身!", + # "以向": "以向使用了神通:云床九练!", + # "砂鲛": "不说了!开鳖!", + # "神风王": "不说了!开鳖!", + # "鲲鹏": "鲲鹏使用了神通:逍遥游!", + # "天龙": "天龙使用了神通:真龙九变!", + # "历飞雨": "厉飞雨使用了神通:天煞震狱功!", + # "外道贩卖鬼": "不说了!开鳖!", + # "元磁道人": "元磁道人使用了法宝:元磁神山!", + # "散发着威压的尸体": "尸体周围爆发了出强烈的罡气!" + # } # 有技能,则开启技能模式 player1_skil_open = False user1_skill_date = None - if user1_buff_date.get_user_sec_buff_data() is not None: - user1_skill_date = user1_buff_date.get_user_sec_buff_data() + if await user1_buff_date.get_user_sec_buff_data() is not None: + user1_skill_date = await user1_buff_date.get_user_sec_buff_data() player1_skil_open = True player1_sub_open = False # 辅修功法14 user1_sub_buff_date = {} - if user1_buff_date.get_user_sub_buff_data() is not None: - user1_sub_buff_date = user1_buff_date.get_user_sub_buff_data() + if await user1_buff_date.get_user_sub_buff_data() is not None: + user1_sub_buff_date = await user1_buff_date.get_user_sub_buff_data() player1_sub_open = True play_list = [] @@ -712,7 +731,7 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): user1_turn_skip = True boss_turn_skip = True player1_turn_cost = 0 # 先设定为初始值 0 - player1_f_js = get_user_def_buff(player1['user_id']) + player1_f_js = await get_user_def_buff(player1['user_id']) player1_js = player1_f_js # 减伤率 boss_buff = BossBuff() if boss["jj"] == "祭道境": @@ -1057,20 +1076,42 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): else: fan_data = False - # except: - # boss["减伤"] = 0.9 # boss减伤率 user1_skill_sh = 0 - user1buffturn = True - bossbuffturn = True + # user1buffturn = True + # bossbuffturn = True get_stone = 0 sh = 0 qx = boss['气血'] boss_now_stone = boss['stone'] boss_js = boss['减伤'] - - if boss_js <= 0.6 and boss['name'] in BOSSDEF: + + # 这里是技能释放概率计算,玩家阶级越高释放的概率越大 + player_info = await XiuxianDataManager().get_user_infos_by_ids(player1['user_id']) + player_level = player_info['level'] + player_rank, ranks = convert_rank(player_level) + + total_ranks = len(ranks) + player_ratio = player_rank / total_ranks + boss_base_prob = 90 - (70 * player_ratio) + boss_base_prob = max(20, min(90, boss_base_prob)) + + boss_js_prob = boss_base_prob * 0.9 # 减伤技能 + boss_zs_prob = boss_base_prob * 0.8 # 真龙九变 + boss_hx_prob = boss_base_prob * 0.7 # 无瑕七绝剑 + boss_bs_prob = boss_base_prob * 0.7 # 太乙剑诀 + boss_xx_prob = boss_base_prob * 0.6 # 七煞灭魂聚血杀阵 + boss_jg_prob = boss_base_prob * 0.7 # 子午安息香 + boss_jh_prob = boss_base_prob * 0.5 # 玄冥剑气 + boss_jb_prob = boss_base_prob * 0.7 # 大德琉璃金刚身 + boss_xl_prob = boss_base_prob * 0.6 # 千煌锁灵阵 + boss_break_prob = boss_base_prob * 0.8 # 八九玄功-穿甲 + boss_xx_prob = boss_base_prob * 0.7 # 八九玄功-吸血 + boss_hx_prob = boss_base_prob * 0.7 # 八九玄功-会心 + boss_def_prob = boss_base_prob * 0.8 # 八九玄功-减伤 + + if boss_js <= 0.6 and boss['name'] in BOSSDEF and random.random() * 100 < boss_js_prob: effect_name = BOSSDEF[boss['name']] boss_js_data = {"type": "node", "data": {"name": f"{boss['name']}", "uin": int(bot_id), @@ -1078,56 +1119,56 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): play_list.append(boss_js_data) - if boss_buff.boss_zs > 0: + if boss_buff.boss_zs > 0 and random.random() * 100 < boss_zs_prob: boss_zs_data = {"type": "node", "data": {"name": f"{boss['name']}", "uin": int(bot_id), "content": f"{boss['name']}使用了真龙九变,提升了{int(boss_buff.boss_zs * 100)}%攻击力!"}} play_list.append(boss_zs_data) - if boss_buff.boss_hx > 0: + if boss_buff.boss_hx > 0 and random.random() * 100 < boss_hx_prob: boss_hx_data = {"type": "node", "data": {"name": f"{boss['name']}", "uin": int(bot_id), "content": f"{boss['name']}使用了无瑕七绝剑,提升了{int(boss_buff.boss_hx * 100)}%会心率!"}} play_list.append(boss_hx_data) - if boss_buff.boss_bs > 0: + if boss_buff.boss_bs > 0 and random.random() * 100 < boss_bs_prob: boss_bs_data = {"type": "node", "data": {"name": f"{boss['name']}", "uin": int(bot_id), "content": f"{boss['name']}使用了太乙剑诀,提升了{int(boss_buff.boss_bs * 100)}%会心伤害!"}} play_list.append(boss_bs_data) - if boss_buff.boss_xx > 0: + if boss_buff.boss_xx > 0 and random.random() * 100 < boss_xx_prob: boss_xx_data = {"type": "node", "data": {"name": f"{boss['name']}", "uin": int(bot_id), "content": f"{boss['name']}使用了七煞灭魂聚血杀阵,降低了{player1['道号']}{int((boss_buff.boss_xx) * 100)}%气血吸取!"}} play_list.append(boss_xx_data) - if boss_buff.boss_jg > 0: + if boss_buff.boss_jg > 0 and random.random() * 100 < boss_jg_prob: boss_jg_data = {"type": "node", "data": {"name": f"{boss['name']}", "uin": int(bot_id), "content": f"{boss['name']}使用了子午安息香,降低了{player1['道号']}{int((boss_buff.boss_jg) * 100)}%伤害!"}} play_list.append(boss_jg_data) - if boss_buff.boss_jh > 0: + if boss_buff.boss_jh > 0 and random.random() * 100 < boss_jh_prob: boss_jh_data = {"type": "node", "data": {"name": f"{boss['name']}", "uin": int(bot_id), "content": f"{boss['name']}使用了玄冥剑气,降低了{player1['道号']}{int((boss_buff.boss_jh) * 100)}%会心率!"}} play_list.append(boss_jh_data) - if boss_buff.boss_jb > 0: + if boss_buff.boss_jb > 0 and random.random() * 100 < boss_jb_prob: boss_jb_data = {"type": "node", "data": {"name": f"{boss['name']}", "uin": int(bot_id), "content": f"{boss['name']}使用了大德琉璃金刚身,降低了{player1['道号']}{int((boss_buff.boss_jb) * 100)}%会心伤害!"}} play_list.append(boss_jb_data) - if boss_buff.boss_xl > 0: + if boss_buff.boss_xl > 0 and random.random() * 100 < boss_xl_prob: # effect_name = BOSSDEF[boss['name']] boss_xl_data = {"type": "node", "data": {"name": f"{boss['name']}", "uin": int(bot_id), @@ -1135,25 +1176,25 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): play_list.append(boss_xl_data) - if random_buff.random_break > 0: + if random_buff.random_break > 0 and random.random() * 100 < boss_break_prob: random_break_data = {"type": "node", "data": {"name": f"{player1['道号']}", "uin": int(bot_id), "content": f"{player1['道号']}发动了八九玄功,获得了{int((random_buff.random_break) * 100)}%穿甲!"}} play_list.append(random_break_data) - if random_buff.random_xx > 0: + if random_buff.random_xx > 0 and random.random() * 100 < boss_xx_prob: random_xx_data = {"type": "node", "data": {"name": f"{player1['道号']}", "uin": int(bot_id), "content": f"{player1['道号']}发动了八九玄功,提升了{int((random_buff.random_xx) * 100)}%!吸血效果!"}} play_list.append(random_xx_data) - if random_buff.random_hx > 0: + if random_buff.random_hx > 0 and random.random() * 100 < boss_hx_prob: random_hx_data = {"type": "node", "data": {"name": f"{player1['道号']}", "uin": int(bot_id), "content": f"{player1['道号']}发动了八九玄功,提升了{int((random_buff.random_hx) * 100)}%!会心!"}} play_list.append(random_hx_data) - if random_buff.random_def > 0: + if random_buff.random_def > 0 and random.random() * 100 < boss_def_prob: random_def_data = {"type": "node", "data": {"name": f"{player1['道号']}", "uin": int(bot_id), "content": f"{player1['道号']}发动了八九玄功,获得了{int((random_buff.random_def) * 100)}%!减伤!"}} @@ -1161,21 +1202,21 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): boss['会心'] = 30 - if fan_data == True: + if fan_data: fan_data = {"type": "node", "data": {"name": f"{player1['道号']}", "uin": int(bot_id), "content": f"{player1['道号']}发动了辅修功法反咒禁制,无效化了减益!"}} play_list.append(fan_data) - user1_battle_buff_date = UserBattleBuffDate(player1['user_id']) # 1号的战斗buff信息 辅修功法14 + user1_battle_buff_data = UserBattleBuffData(player1['user_id']) # 1号的战斗buff信息 辅修功法14 while True: - msg1 = "{}发起攻击,造成了{}伤害\n" - msg2 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" + msg2 = "{}发起攻击,造成了{}点伤害\n" - user1_battle_buff_date, user2_battle_buff_date, msg = start_sub_buff_handle(player1_sub_open, + user1_battle_buff_data, user2_battle_buff_data, msg = await start_sub_buff_handle(player1_sub_open, user1_sub_buff_date, - user1_battle_buff_date, False, {}, + user1_battle_buff_data, False, {}, {}) play_list.append(get_msg_dict(player1, player_init_hp, msg)) # 辅修功法14 @@ -1184,18 +1225,18 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): if user1_turn_skip: # 无需跳过回合 turn_start_msg = f"☆------{player1['道号']}的回合------☆" play_list.append(get_msg_dict(player1, player_init_hp, turn_start_msg)) - user1hpconst, user1mpcost, user1skill_type, skillrate = get_skill_hp_mp_data(player1, user1_skill_date) + user1hpconst, user1mpcost, user1skill_type, skillrate = await get_skill_hp_mp_data(player1, user1_skill_date) if player1_turn_cost == 0: # 没有持续性技能生效 player1_js = player1_f_js # 没有持续性技能生效,减伤恢复 if isEnableUserSikll(player1, user1hpconst, user1mpcost, player1_turn_cost, skillrate): # 满足技能要求,#此处为技能的第一次释放 - skillmsg, user1_skill_sh, player1_turn_cost = get_skill_sh_data(player1, user1_skill_date) + skillmsg, user1_skill_sh, player1_turn_cost = await get_skill_sh_data(player1, user1_skill_date) if user1skill_type == 1: # 直接伤害类技能 play_list.append(get_msg_dict(player1, player_init_hp, skillmsg)) player1 = calculate_skill_cost(player1, user1hpconst, user1mpcost) boss['气血'] = boss['气血'] - int( user1_skill_sh * (boss_js + user1_break)) # 玩家1的伤害 * boss的减伤 - boss_hp_msg = f"{boss['name']}剩余血量{boss['气血']}" + boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}" play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg)) sh += user1_skill_sh @@ -1204,36 +1245,36 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): player1 = calculate_skill_cost(player1, user1hpconst, user1mpcost) boss['气血'] = boss['气血'] - int( user1_skill_sh * (0.2 + boss_js + user1_break)) # 玩家1的伤害 * 玩家2的减伤 - boss_hp_msg = f"{boss['name']}剩余血量{boss['气血']}" + boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}" play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg)) sh += user1_skill_sh elif user1skill_type == 3: # buff类技能 user1buff_type = user1_skill_date['bufftype'] if user1buff_type == 1: # 攻击类buff - isCrit, player1_sh = get_turnatk(player1, 0, user1_battle_buff_date, + isCrit, player1_sh = await get_turnatk(player1, 0, user1_battle_buff_data, boss_buff, random_buff) # 判定是否暴击 辅修功法14 if isCrit: - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" else: - msg1 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" player1 = calculate_skill_cost(player1, user1hpconst, user1mpcost) play_list.append(get_msg_dict(player1, player_init_hp, skillmsg)) player1_atk_msg = msg1.format(player1['道号'], player1_sh) play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg)) boss['气血'] = boss['气血'] - int( player1_sh * (boss_js + user1_break)) # 玩家1的伤害 * 玩家2的减伤 - boss_hp_msg = f"{boss['name']}剩余血量{boss['气血']}" + boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}" play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg)) sh += player1_sh elif user1buff_type == 2: # 减伤类buff,需要在player2处判断 - isCrit, player1_sh = get_turnatk(player1, 0, user1_battle_buff_date, + isCrit, player1_sh = await get_turnatk(player1, 0, user1_battle_buff_data, boss_buff, random_buff) # 判定是否暴击 辅修功法14 if isCrit: - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" else: - msg1 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" player1 = calculate_skill_cost(player1, user1hpconst, user1mpcost) play_list.append(get_msg_dict(player1, player_init_hp, skillmsg)) @@ -1241,7 +1282,7 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg)) boss['气血'] = boss['气血'] - int( player1_sh * (boss_js + user1_break)) # 玩家1的伤害 * 玩家2的减伤 - boss_hp_msg = f"{boss['name']}剩余血量{boss['气血']}" + boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}" play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg)) player1_js = player1_f_js - user1_skill_sh sh += player1_sh @@ -1252,19 +1293,19 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): if user1_skill_sh: # 命中 boss_turn_skip = False - bossbuffturn = False + # bossbuffturn = False else: # 没放技能,打一拳 - isCrit, player1_sh = get_turnatk(player1, 0, user1_battle_buff_date, + isCrit, player1_sh = await get_turnatk(player1, 0, user1_battle_buff_data, boss_buff, random_buff) # 判定是否暴击 辅修功法14 if isCrit: - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" else: - msg1 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" player1_atk_msg = msg1.format(player1['道号'], player1_sh) play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg)) boss['气血'] = boss['气血'] - int(player1_sh * (boss_js + user1_break)) # 玩家1的伤害 * 玩家2的减伤 - boss_hp_msg = f"{boss['name']}剩余血量{boss['气血']}" + boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}" play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg)) sh += player1_sh @@ -1274,53 +1315,53 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): skillmsg = get_persistent_skill_msg(player1['道号'], user1_skill_date['name'], user1_skill_sh, player1_turn_cost) play_list.append(get_msg_dict(player1, player_init_hp, skillmsg)) - isCrit, player1_sh = get_turnatk(player1, 0, user1_battle_buff_date, + isCrit, player1_sh = await get_turnatk(player1, 0, user1_battle_buff_data, boss_buff, random_buff) # 判定是否暴击 辅修功法14 if isCrit: - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" else: - msg1 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" player1_atk_msg = msg1.format(player1['道号'], player1_sh) play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg)) boss['气血'] = boss['气血'] - int((user1_skill_sh + player1_sh) * (boss_js + user1_break)) - boss_hp_msg = f"{boss['name']}剩余血量{boss['气血']}" + boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}" play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg)) sh += player1_sh + user1_skill_sh elif user1skill_type == 3: # buff类技能 user1buff_type = user1_skill_date['bufftype'] if user1buff_type == 1: # 攻击类buff - isCrit, player1_sh = get_turnatk(player1, user1_skill_sh, user1_battle_buff_date, + isCrit, player1_sh = await get_turnatk(player1, user1_skill_sh, user1_battle_buff_data, boss_buff, random_buff) # 判定是否暴击 辅修功法14 if isCrit: - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" else: - msg1 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" player1_turn_cost = player1_turn_cost - 1 play_list.append(get_msg_dict(player1, player_init_hp, f"{user1_skill_date['name']}增伤剩余:{player1_turn_cost}回合")) player1_atk_msg = msg1.format(player1['道号'], player1_sh) play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg)) boss['气血'] = boss['气血'] - int(player1_sh * (boss_js + user1_break)) # 玩家1的伤害 * 玩家2的减伤 - boss_hp_msg = f"{boss['name']}剩余血量{boss['气血']}" + boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}" play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg)) sh += player1_sh elif user1buff_type == 2: # 减伤类buff,需要在player2处判断 - isCrit, player1_sh = get_turnatk(player1, 0, user1_battle_buff_date, + isCrit, player1_sh = await get_turnatk(player1, 0, user1_battle_buff_data, boss_buff, random_buff) # 判定是否暴击 辅修功法14 if isCrit: - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" else: - msg1 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" player1_turn_cost = player1_turn_cost - 1 play_list.append(get_msg_dict(player1, player_init_hp, f"减伤剩余{player1_turn_cost}回合!")) player1_atk_msg = msg1.format(player1['道号'], player1_sh) play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg)) boss['气血'] = boss['气血'] - int(player1_sh * (boss_js + user1_break)) # 玩家1的伤害 * 玩家2的减伤 - boss_hp_msg = f"{boss['name']}剩余血量{boss['气血']}" + boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}" play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg)) player1_js = player1_f_js - user1_skill_sh sh += player1_sh @@ -1330,21 +1371,21 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): skillmsg = get_persistent_skill_msg(player1['道号'], user1_skill_date['name'], user1_skill_sh, player1_turn_cost) play_list.append(get_msg_dict(player1, player_init_hp, skillmsg)) - isCrit, player1_sh = get_turnatk(player1, 0, user1_battle_buff_date, + isCrit, player1_sh = await get_turnatk(player1, 0, user1_battle_buff_data, boss_buff, random_buff) # 判定是否暴击 辅修功法14 if isCrit: - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" else: - msg1 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" player1_atk_msg = msg1.format(player1['道号'], player1_sh) play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg)) boss['气血'] = boss['气血'] - int(player1_sh * (boss_js + user1_break)) # 玩家1的伤害 * 玩家2的减伤 - boss_hp_msg = f"{boss['name']}剩余血量{boss['气血']}" + boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}" play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg)) sh += player1_sh if player1_turn_cost == 0: # 封印时间到 boss_turn_skip = True - bossbuffturn = True + # bossbuffturn = True else: # 休息回合-1 play_list.append(get_msg_dict(player1, player_init_hp, f"☆------{player1['道号']}动弹不得!------☆")) @@ -1355,21 +1396,21 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): else: # 没有技能的derB play_list.append(get_msg_dict(player1, player_init_hp, f"☆------{player1['道号']}的回合------☆")) - isCrit, player1_sh = get_turnatk(player1, 0, user1_battle_buff_date, + isCrit, player1_sh = await get_turnatk(player1, 0, user1_battle_buff_data, boss_buff, random_buff) # 判定是否暴击 辅修功法14 if isCrit: - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" else: - msg1 = "{}发起攻击,造成了{}伤害\n" + msg1 = "{}发起攻击,造成了{}点伤害\n" player1_atk_msg = msg1.format(player1['道号'], player1_sh) play_list.append(get_msg_dict(player1, player_init_hp, player1_atk_msg)) boss['气血'] = boss['气血'] - player1_sh - boss_hp_msg = f"{boss['name']}剩余血量{boss['气血']}" + boss_hp_msg = f"{boss['name']}剩余血量{number_to(boss['气血'])}" play_list.append(get_msg_dict(player1, player_init_hp, boss_hp_msg)) sh += player1_sh ## 自己回合结束 处理 辅修功法14 - player1, boss, msg = after_atk_sub_buff_handle(player1_sub_open, player1, user1_main_buff_data, + player1, boss, msg = await after_atk_sub_buff_handle(player1_sub_open, player1, user1_main_buff_data, user1_sub_buff_date, player2_health_temp - boss['气血'], boss, boss_buff, random_buff) @@ -1386,7 +1427,7 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): if player1['气血'] <= 0: player1['气血'] = 1 # - sql_message.update_user_hp_mp( + await XiuxianDataManager().update_user_hp_mp( player1['user_id'], int(player1['气血'] / (1 + user1_hp_buff)), int(player1['真元'] / (1 + user1_mp_buff)) @@ -1403,44 +1444,44 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): boss_sub = random.randint(0, 100) if boss_sub <= 8: play_list.append(get_boss_dict(boss, qx, f"☆------{boss['name']}的回合------☆", bot_id)) - isCrit, boss_sh = get_turnatk_boss(boss, 0, UserBattleBuffDate("9999999"), boss_buff) # 判定是否暴击 辅修功法14 + isCrit, boss_sh = get_turnatk_boss(boss, 0, UserBattleBuffData("9999999"), boss_buff) # 判定是否暴击 辅修功法14 if isCrit: - msg2 = "{}:紫玄掌!!紫星河!!!并且发生了会心一击,造成了{}伤害\n" + msg2 = "{}:紫玄掌!!紫星河!!!并且发生了会心一击,造成了{}点伤害\n" else: - msg2 = "{}:紫玄掌!!紫星河!!!造成了{}伤害\n" + msg2 = "{}:紫玄掌!!紫星河!!!造成了{}点伤害\n" play_list.append(get_boss_dict(boss, qx, msg2.format(boss['name'], boss_sh * (1 + boss_buff.boss_zs) * 5 + ( player1['气血'] * 0.3)), bot_id)) player1['气血'] = player1['气血'] - (( (boss_sh * (1 + boss_buff.boss_zs) * (player1_js - random_buff.random_def) * 5) + ( player1['气血'] * 0.3))) - play_list.append(get_boss_dict(boss, qx, f"{player1['道号']}剩余血量{player1['气血']}", bot_id)) + play_list.append(get_boss_dict(boss, qx, f"{player1['道号']}剩余血量{number_to(player1['气血'])}", bot_id)) elif 8 <= boss_sub <= 16: play_list.append(get_boss_dict(boss, qx, f"☆------{boss['name']}的回合------☆", bot_id)) - isCrit, boss_sh = get_turnatk_boss(boss, 0, UserBattleBuffDate("9999999"), boss_buff) # 判定是否暴击 辅修功法14 + isCrit, boss_sh = get_turnatk_boss(boss, 0, UserBattleBuffData("9999999"), boss_buff) # 判定是否暴击 辅修功法14 if isCrit: - msg2 = "{}:子龙朱雀!!!穿透了对方的护甲!并且发生了会心一击,造成了{}伤害\n" + msg2 = "{}:子龙朱雀!!!穿透了对方的护甲!并且发生了会心一击,造成了{}点伤害\n" else: - msg2 = "{}:子龙朱雀!!!穿透了对方的护甲!造成了{}伤害\n" + msg2 = "{}:子龙朱雀!!!穿透了对方的护甲!造成了{}点伤害\n" play_list.append(get_boss_dict(boss, qx, msg2.format(boss['name'], boss_sh * (1 + boss_buff.boss_zs) * ( player1_js - random_buff.random_def + 0.5) * 3), bot_id)) player1['气血'] = player1['气血'] - ( ((boss_sh * (1 + boss_buff.boss_zs) * (player1_js - random_buff.random_def + 0.5) * 3))) - play_list.append(get_boss_dict(boss, qx, f"{player1['道号']}剩余血量{player1['气血']}", bot_id)) + play_list.append(get_boss_dict(boss, qx, f"{player1['道号']}剩余血量{number_to(player1['气血'])}", bot_id)) else: play_list.append(get_boss_dict(boss, qx, f"☆------{boss['name']}的回合------☆", bot_id)) - isCrit, boss_sh = get_turnatk_boss(boss, 0, UserBattleBuffDate("9999999"), boss_buff) # 判定是否暴击 辅修功法14 + isCrit, boss_sh = get_turnatk_boss(boss, 0, UserBattleBuffData("9999999"), boss_buff) # 判定是否暴击 辅修功法14 if isCrit: - msg2 = "{}发起会心一击,造成了{}伤害\n" + msg2 = "{}发起会心一击,造成了{}点伤害\n" else: - msg2 = "{}发起攻击,造成了{}伤害\n" + msg2 = "{}发起攻击,造成了{}点伤害\n" play_list.append( get_boss_dict(boss, qx, msg2.format(boss['name'], boss_sh * (1 + boss_buff.boss_zs)), bot_id)) player1['气血'] = player1['气血'] - ( boss_sh * (1 + boss_buff.boss_zs) * (player1_js - random_buff.random_def)) - play_list.append(get_boss_dict(boss, qx, f"{player1['道号']}剩余血量{player1['气血']}", bot_id)) + play_list.append(get_boss_dict(boss, qx, f"{player1['道号']}剩余血量{number_to(player1['气血'])}", bot_id)) else: play_list.append(get_boss_dict(boss, qx, f"☆------{boss['name']}动弹不得!------☆", bot_id)) @@ -1459,7 +1500,7 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): boss['stone'] = boss_now_stone - get_stone if isSql: - sql_message.update_user_hp_mp( + await XiuxianDataManager().update_user_hp_mp( player1['user_id'], 1, int(player1['真元'] / (1 + user1_mp_buff)) ) @@ -1474,26 +1515,26 @@ async def Boss_fight(player1: dict, boss: dict, type_in=2, bot_id=0): def get_msg_dict(player, player_init_hp, msg): - return {"type": "node", "data": {"name": f"{player['道号']},当前血量:{int(player['气血'])} / {int(player_init_hp)}", + return {"type": "node", "data": {"name": f"{player['道号']},当前血量:{number_to(player['气血'])} / {number_to(player_init_hp)}", "uin": int(player['user_id']), "content": msg}} def get_boss_dict(boss, boss_init_hp, msg, bot_id): return {"type": "node", - "data": {"name": f"{boss['name']}当前血量:{int(boss['气血'])} / {int(boss_init_hp)}", "uin": int(bot_id), + "data": {"name": f"{boss['name']}当前血量:{number_to(boss['气血'])} / {number_to(boss_init_hp)}", "uin": int(bot_id), "content": msg}} -def get_user_def_buff(user_id): - user_armor_data = UserBuffDate(user_id).get_user_armor_buff_data() # 防具减伤 - user_weapon_data = UserBuffDate(user_id).get_user_weapon_data() # 武器减伤 - user_main_data = UserBuffDate(user_id).get_user_main_buff_data() # 功法减伤 +async def get_user_def_buff(user_id): + user_armor_data = await UserBuffData(user_id).get_user_armor_buff_data() # 防具减伤 + user_weapon_data = await UserBuffData(user_id).get_user_weapon_data() # 武器减伤 + user_main_data = await UserBuffData(user_id).get_user_main_buff_data() # 功法减伤 if user_weapon_data is not None: - weapon_def = user_weapon_data['def_buff'] # 武器减伤 + weapon_def = user_weapon_data['def_buf'] # 武器减伤 else: weapon_def = 0 if user_main_data is not None: - main_def = user_main_data['def_buff'] # 功法减伤 + main_def = user_main_data['def_buf'] # 功法减伤 else: main_def = 0 if user_armor_data is not None: @@ -1503,7 +1544,7 @@ def get_user_def_buff(user_id): return round(1 - (def_buff + weapon_def + main_def), 2) # 初始减伤率 -def get_turnatk(player, buff=0, user_battle_buff_date={}, +async def get_turnatk(player, buff=0, user_battle_buff_date={}, boss_buff: BossBuff = empty_boss_buff, random_buff: UserRandomBuff = empty_ussr_random_buff): # 辅修功法14 sub_atk = 0 @@ -1512,20 +1553,20 @@ def get_turnatk(player, buff=0, user_battle_buff_date={}, zwsh = 0 try: user_id = player['user_id'] - impart_data = xiuxian_impart.get_user_impart_info_with_id(user_id) - user_buff_data = UserBuffDate(user_id) - weapon_critatk_data = UserBuffDate(user_id).get_user_weapon_data() # 武器会心伤害 - weapon_zw = UserBuffDate(user_id).get_user_weapon_data() - main_zw = user_buff_data.get_user_main_buff_data() + impart_data = await XiuxianDataManager().get_user_impart_info_with_id(user_id) + user_buff_data = UserBuffData(user_id) + weapon_critatk_data = await UserBuffData(user_id).get_user_weapon_data() # 武器会心伤害 + weapon_zw = await UserBuffData(user_id).get_user_weapon_data() + main_zw = await user_buff_data.get_user_main_buff_data() # 专武伤害,其实叫伴生武器更好。。。 zwsh = 0.5 if main_zw["ew"] != 0 and weapon_zw["zw"] != 0 and main_zw["ew"] == weapon_zw["zw"] else 0 - main_critatk_data = user_buff_data.get_user_main_buff_data() # 功法会心伤害 - player_sub_open = False # 辅修功法14 + main_critatk_data = await user_buff_data.get_user_main_buff_data() # 功法会心伤害 + # player_sub_open = False # 辅修功法14 user_sub_buff_date = {} - if user_buff_data.get_user_sub_buff_data() != None: - user_sub_buff_date = UserBuffDate(user_id).get_user_sub_buff_data() - player_sub_open = True - buff_value = int(user_sub_buff_date['buff']) + if await user_buff_data.get_user_sub_buff_data() is not None: + user_sub_buff_date = await user_buff_data.get_user_sub_buff_data() + # player_sub_open = True + buff_value = int(user_sub_buff_date['buf']) buff_type = user_sub_buff_date['buff_type'] if buff_type == '1': sub_atk = buff_value / 100 @@ -1539,21 +1580,21 @@ def get_turnatk(player, buff=0, user_battle_buff_date={}, sub_dmg = buff_value / 100 else: sub_dmg = 0 - except: + except ValueError: impart_data = None weapon_critatk_data = None main_critatk_data = None - impart_know_per = impart_data['impart_know_per'] if impart_data is not None else 0 - impart_burst_per = impart_data['impart_burst_per'] if impart_data is not None else 0 + impart_crit_addition = impart_data['impart_crit_addition'] if impart_data is not None else 0 + impart_crit_dmg_addition = impart_data['impart_crit_dmg_addition'] if impart_data is not None else 0 weapon_critatk = weapon_critatk_data['critatk'] if weapon_critatk_data is not None else 0 # 武器会心伤害 main_critatk = main_critatk_data['critatk'] if main_critatk_data is not None else 0 # 功法会心伤害 isCrit = False turnatk = int(round(random.uniform(0.95, 1.05), 2) * (player['攻击'] * (buff + sub_atk + 1) * (1 - boss_buff.boss_jg)) * (1 + zwsh)) # 攻击波动,buff是攻击buff if random.randint(0, 100) <= player['会心'] + ( - impart_know_per + sub_crit - boss_buff.boss_jh + random_buff.random_hx) * 100: # 会心判断 + impart_crit_addition + sub_crit - boss_buff.boss_jh + random_buff.random_hx) * 100: # 会心判断 turnatk = int(turnatk * ( - 1.5 + impart_burst_per + weapon_critatk + main_critatk + sub_dmg - boss_buff.boss_jb)) # boss战、切磋、秘境战斗会心伤害公式(不包含抢劫) + 1.5 + float(impart_crit_dmg_addition) + float(weapon_critatk) + float(main_critatk) + float(sub_dmg) - float(boss_buff.boss_jb))) # boss战、切磋、秘境战斗会心伤害公式(不包含抢劫) isCrit = True return isCrit, turnatk @@ -1580,17 +1621,17 @@ def isEnableUserSikll(player, hpcost, mpcost, turncost, skillrate): # 是否满 return skill -def get_skill_hp_mp_data(player, secbuffdata): +async def get_skill_hp_mp_data(player, secbuffdata): """获取技能消耗气血、真元、技能类型、技能释放概率""" user_id = player['user_id'] - weapon_data = UserBuffDate(user_id).get_user_weapon_data() - if weapon_data is not None and "mp_buff" in weapon_data: - weapon_mp = weapon_data["mp_buff"] + weapon_data = await UserBuffData(user_id).get_user_weapon_data() + if weapon_data is not None and "mp_buf" in weapon_data: + weapon_mp = weapon_data["mp_buf"] else: weapon_mp = 0 hpcost = int(secbuffdata['hpcost'] * player['气血']) if secbuffdata['hpcost'] != 0 else 0 - mpcost = int(secbuffdata['mpcost'] * player['exp'] * (1 - weapon_mp)) if secbuffdata['mpcost'] != 0 else 0 + mpcost = int(secbuffdata['mpcost'] * float(player['exp']) * (1 - weapon_mp)) if secbuffdata['mpcost'] != 0 else 0 return hpcost, mpcost, secbuffdata['skill_type'], secbuffdata['rate'] @@ -1607,16 +1648,16 @@ def get_persistent_skill_msg(username, skillname, sh, turn): return f"{username}的持续性技能:{skillname},造成{number_to(sh)}伤害,剩余回合:{turn}!" -def get_skill_sh_data(player, secbuffdata): +async def get_skill_sh_data(player, secbuffdata): skillmsg = '' if secbuffdata['skill_type'] == 1: # 连续攻击类型 turncost = -secbuffdata['turncost'] - isCrit, turnatk = get_turnatk(player) + isCrit, turnatk = await get_turnatk(player) atkvalue = secbuffdata['atkvalue'] # 列表 skillsh = 0 atkmsg = '' for value in atkvalue: - atkmsg += f"{int(value * turnatk)}伤害、" + atkmsg += f"{number_to(int(value * turnatk))}伤害、" skillsh += int(value * turnatk) if turncost == 0: @@ -1625,21 +1666,21 @@ def get_skill_sh_data(player, secbuffdata): turnmsg = f",休息{secbuffdata['turncost']}回合!" if isCrit: - skillmsg = f"{player['道号']}发动技能:{secbuffdata['name']},消耗气血{int(secbuffdata['hpcost'] * player['气血']) if secbuffdata['hpcost'] != 0 else 0}点、真元{int(secbuffdata['mpcost'] * player['exp']) if secbuffdata['mpcost'] != 0 else 0}点,{secbuffdata['desc']}并且发生了会心一击,造成{atkmsg[:-1]}{turnmsg}" + skillmsg = f"{player['道号']}发动技能:{secbuffdata['name']},消耗气血{number_to(int(secbuffdata['hpcost'] * float(player['气血'])))}点、真元{number_to(int(secbuffdata['mpcost'] * float(player['exp'])))}点,{secbuffdata['desc']}并且发生了会心一击,造成{number_to(skillsh)}点伤害{turnmsg}" else: - skillmsg = f"{player['道号']}发动技能:{secbuffdata['name']},消耗气血{int(secbuffdata['hpcost'] * player['气血']) if secbuffdata['hpcost'] != 0 else 0}点、真元{int(secbuffdata['mpcost'] * player['exp']) if secbuffdata['mpcost'] != 0 else 0}点,{secbuffdata['desc']}造成{atkmsg[:-1]}{turnmsg}" + skillmsg = f"{player['道号']}发动技能:{secbuffdata['name']},消耗气血{number_to(int(secbuffdata['hpcost'] * float(player['气血'])))}点、真元{number_to(int(secbuffdata['mpcost'] * float(player['exp'])))}点,{secbuffdata['desc']}造成{number_to(skillsh)}点伤害{turnmsg}" return skillmsg, skillsh, turncost elif secbuffdata['skill_type'] == 2: # 持续伤害类型 turncost = secbuffdata['turncost'] - isCrit, turnatk = get_turnatk(player) + isCrit, turnatk = await get_turnatk(player) skillsh = int(secbuffdata['atkvalue'] * player['攻击']) # 改动 atkmsg = '' if isCrit: - skillmsg = f"{player['道号']}发动技能:{secbuffdata['name']},消耗气血{int(secbuffdata['hpcost'] * player['气血']) if secbuffdata['hpcost'] != 0 else 0}点、真元{int(secbuffdata['mpcost'] * player['exp']) if secbuffdata['mpcost'] != 0 else 0}点,{secbuffdata['desc']}并且发生了会心一击,造成{skillsh}点伤害,持续{turncost}回合!" + skillmsg = f"{player['道号']}发动技能:{secbuffdata['name']},消耗气血{number_to(int(secbuffdata['hpcost'] * float(player['气血'])))}点、真元{number_to(int(secbuffdata['mpcost'] * float(player['exp'])))}点,{secbuffdata['desc']}并且发生了会心一击,造成{number_to(skillsh)}点伤害,持续{turncost}回合!" else: - skillmsg = f"{player['道号']}发动技能:{secbuffdata['name']},消耗气血{int(secbuffdata['hpcost'] * player['气血']) if secbuffdata['hpcost'] != 0 else 0}点、真元{int(secbuffdata['mpcost'] * player['exp']) if secbuffdata['mpcost'] != 0 else 0}点,{secbuffdata['desc']}造成{skillsh}点伤害,持续{turncost}回合!" + skillmsg = f"{player['道号']}发动技能:{secbuffdata['name']},消耗气血{number_to(int(secbuffdata['hpcost'] * float(player['气血'])))}点、真元{number_to(int(secbuffdata['mpcost'] * float(player['exp'])))}点,{secbuffdata['desc']}造成{number_to(skillsh)}点伤害,持续{turncost}回合!" return skillmsg, skillsh, turncost @@ -1648,9 +1689,9 @@ def get_skill_sh_data(player, secbuffdata): skillsh = secbuffdata['buffvalue'] atkmsg = '' if secbuffdata['bufftype'] == 1: - skillmsg = f"{player['道号']}发动技能:{secbuffdata['name']},消耗气血{int(secbuffdata['hpcost'] * player['气血']) if secbuffdata['hpcost'] != 0 else 0}点、真元{int(secbuffdata['mpcost'] * player['exp']) if secbuffdata['mpcost'] != 0 else 0}点,{secbuffdata['desc']}攻击力增加{skillsh}倍,持续{turncost}回合!" + skillmsg = f"{player['道号']}发动技能:{secbuffdata['name']},消耗气血{number_to(int(secbuffdata['hpcost'] * float(player['气血'])))}点、真元{number_to(int(secbuffdata['mpcost'] * float(player['exp'])))}点,{secbuffdata['desc']}攻击力增加{skillsh}倍,持续{turncost}回合!" elif secbuffdata['bufftype'] == 2: - skillmsg = f"{player['道号']}发动技能:{secbuffdata['name']},消耗气血{int(secbuffdata['hpcost'] * player['气血']) if secbuffdata['hpcost'] != 0 else 0}点、真元{int(secbuffdata['mpcost'] * player['exp']) if secbuffdata['mpcost'] != 0 else 0}点,{secbuffdata['desc']}获得{skillsh * 100}%的减伤,持续{turncost}回合!" + skillmsg = f"{player['道号']}发动技能:{secbuffdata['name']},消耗气血{number_to(int(secbuffdata['hpcost'] * float(player['气血'])))}点、真元{number_to(int(secbuffdata['mpcost'] * float(player['exp'])))}点,{secbuffdata['desc']}获得{skillsh * 100}%的减伤,持续{turncost}回合!" return skillmsg, skillsh, turncost @@ -1658,34 +1699,33 @@ def get_skill_sh_data(player, secbuffdata): turncost = secbuffdata['turncost'] if random.randint(0, 100) <= secbuffdata['success']: # 命中 skillsh = True - skillmsg = f"{player['道号']}发动技能:{secbuffdata['name']},消耗气血{int(secbuffdata['hpcost'] * player['气血']) if secbuffdata['hpcost'] != 0 else 0}点、真元{int(secbuffdata['mpcost'] * player['exp']) if secbuffdata['mpcost'] != 0 else 0}点,使对手动弹不得,{secbuffdata['desc']}持续{turncost}回合!" + skillmsg = f"{player['道号']}发动技能:{secbuffdata['name']},消耗气血{number_to(int(secbuffdata['hpcost'] * float(player['气血'])))}点、真元{number_to(int(secbuffdata['mpcost'] * float(player['exp'])))}点,使对手动弹不得,{secbuffdata['desc']}持续{turncost}回合!" else: # 未命中 skillsh = False - skillmsg = f"{player['道号']}发动技能:{secbuffdata['name']},消耗气血{int(secbuffdata['hpcost'] * player['气血']) if secbuffdata['hpcost'] != 0 else 0}点、真元{int(secbuffdata['mpcost'] * player['exp']) if secbuffdata['mpcost'] != 0 else 0}点,{secbuffdata['desc']}但是被对手躲避!" + skillmsg = f"{player['道号']}发动技能:{secbuffdata['name']},消耗气血{number_to(int(secbuffdata['hpcost'] * float(player['气血'])))}点、真元{number_to(int(secbuffdata['mpcost'] * float(player['exp'])))}点,{secbuffdata['desc']}但是被对手躲避!" return skillmsg, skillsh, turncost # 处理开局的辅修功法效果 -def apply_buff(user_battle_buff, subbuffdata, is_opponent=False): +async def apply_buff(user_battle_buff, subbuffdata, is_opponent=False): buff_type_to_attr = { - '1': ('atk_buff', "攻击力"), - '2': ('crit_buff', "暴击率"), - '3': ('crit_dmg_buff', "暴击伤害"), - '4': ('health_restore_buff', "气血回复"), - '5': ('mana_restore_buff', "真元回复"), - '6': ('health_stolen_buff', "气血吸取"), - '7': ('mana_stolen_buff', "真元吸取"), - '8': ('thorns_buff', "中毒"), - '9': ('hm_stolen_buff', "气血真元吸取"), - '10': ('jx_buff', "重伤效果"), - '11': ('fan_buff', "抵消效果"), - '12': ('stone_buff', "聚宝效果"), - '13': ('break_buff', "斗战效果"), + '1': ('atk_buf', "攻击力"), + '2': ('crit_buf', "暴击率"), + '3': ('crit_dmg_buf', "暴击伤害"), + '4': ('health_restore_buf', "气血回复"), + '5': ('mana_restore_buf', "真元回复"), + '6': ('health_stolen_buf', "气血吸取"), + '7': ('mana_stolen_buf', "真元吸取"), + '8': ('thorns_buf', "中毒"), + '9': ('hm_stolen_buf', "气血真元吸取"), + '10': ('jx_buf', "重伤效果"), + '11': ('fan_buf', "抵消效果"), + '12': ('stone_buf', "聚宝效果"), + '13': ('break_buf', "斗战效果"), } - attr, desc = buff_type_to_attr[subbuffdata['buff_type']] - setattr(user_battle_buff, attr, subbuffdata['buff']) + setattr(user_battle_buff, attr, subbuffdata['buf']) if int(subbuffdata['buff_type']) >= 0 and int(subbuffdata['buff_type']) <= 10: sub_msg = f"提升{subbuffdata['buff']}%{desc}" else: @@ -1694,16 +1734,16 @@ def apply_buff(user_battle_buff, subbuffdata, is_opponent=False): return f"{prefix}使用功法{subbuffdata['name']}, {sub_msg}" -def start_sub_buff_handle(player1_sub_open, subbuffdata1, user1_battle_buff_date, - player2_sub_open, subbuffdata2, user2_battle_buff_date): - msg1 = apply_buff(user1_battle_buff_date, subbuffdata1) if player1_sub_open else "" - msg2 = apply_buff(user2_battle_buff_date, subbuffdata2, is_opponent=True) if player2_sub_open else "" +async def start_sub_buff_handle(player1_sub_open, subbuffdata1, user1_battle_buff_data, + player2_sub_open, subbuffdata2, user2_battle_buff_data): + msg1 = await apply_buff(user1_battle_buff_data, subbuffdata1) if player1_sub_open else "" + msg2 = await apply_buff(user2_battle_buff_data, subbuffdata2, is_opponent=True) if player2_sub_open else "" - return user1_battle_buff_date, user2_battle_buff_date, msg1 + msg2 + return user1_battle_buff_data, user2_battle_buff_data, msg1 + msg2 # 处理攻击后辅修功法效果 -def after_atk_sub_buff_handle(player1_sub_open, player1, user1_main_buff_data, subbuffdata1, damage1, player2, +async def after_atk_sub_buff_handle(player1_sub_open, player1, user1_main_buff_data, subbuffdata1, damage1, player2, boss_buff: BossBuff = empty_boss_buff, random_buff: UserRandomBuff = empty_boss_buff): msg = "" @@ -1711,46 +1751,46 @@ def after_atk_sub_buff_handle(player1_sub_open, player1, user1_main_buff_data, s if not player1_sub_open: return player1, player2, msg - impart_player1_data = xiuxian_impart.get_user_impart_info_with_id(player1['user_id']) - impart_hp_per_1 = impart_player1_data['impart_hp_per'] if impart_player1_data is not None else 0 - impart_mp_per_1 = impart_player1_data['impart_mp_per'] if impart_player1_data is not None else 0 + impart_player1_data = await XiuxianDataManager().get_user_impart_info_with_id(player1['user_id']) + impart_hp_per_1 = impart_player1_data['impart_hp_addition'] if impart_player1_data is not None else 0 + impart_mp_per_1 = impart_player1_data['impart_mp_addition'] if impart_player1_data is not None else 0 if 'max_hp' not in player1: exp = int(player1['exp']) player1['max_hp'] = int(exp / 2) * ( - 1 + user1_main_buff_data.get('hpbuff', 0) + impart_hp_per_1 if user1_main_buff_data is not None else 0) + 1 + user1_main_buff_data.get('hpbuf', 0) + impart_hp_per_1 if user1_main_buff_data is not None else 0) player1['max_mp'] = exp * ( - 1 + user1_main_buff_data.get('mpbuff', 0) + impart_mp_per_1 if user1_main_buff_data is not None else 0) + 1 + user1_main_buff_data.get('mpbuf', 0) + impart_mp_per_1 if user1_main_buff_data is not None else 0) - buff_value = int(subbuffdata1['buff']) + buff_value = int(subbuffdata1['buf']) buff_tow = int(subbuffdata1['buff2']) buff_type = subbuffdata1['buff_type'] if buff_type == '4': restore_health = int(player1['exp'] / 2) * ( - 1 + user1_main_buff_data['hpbuff'] + impart_hp_per_1) * buff_value // 100 + 1 + user1_main_buff_data['hpbuf'] + impart_hp_per_1) * buff_value // 100 player1['气血'] += restore_health player1['气血'] = min(player1['气血'], player1['max_hp']) - msg = "回复气血:" + str(restore_health) + msg = f"回复气血: {number_to(restore_health)}" elif buff_type == '5': - restore_mana = player1['exp'] * (1 + user1_main_buff_data['mpbuff'] + impart_mp_per_1) * buff_value // 100 + restore_mana = player1['exp'] * (1 + user1_main_buff_data['mpbuf'] + impart_mp_per_1) * buff_value // 100 player1['真元'] += restore_mana player1['真元'] = min(player1['真元'], player1['max_mp']) - msg = "回复真元:" + str(restore_mana) + msg = f"回复真元: {number_to(restore_mana)}" elif buff_type == '6': health_stolen = (damage1 * (buff_value + random_buff.random_xx) // 100) * (1 - boss_buff.boss_xx) player1['气血'] += health_stolen player1['气血'] = min(player1['气血'], player1['max_hp']) - msg = "吸取气血:" + str(health_stolen) + msg = f"吸取气血: {number_to(health_stolen)}" elif buff_type == '7': mana_stolen = (damage1 * buff_value // 100) * (1 - boss_buff.boss_xl) player1['真元'] += mana_stolen player1['真元'] = min(player1['真元'], player1['max_mp']) - msg = "吸取真元:" + str(mana_stolen) + msg = f"吸取真元: {number_to(mana_stolen)}" elif buff_type == '8': # 中毒 poison_damage = player2['气血'] * buff_value // 100 player2['气血'] -= poison_damage - msg = "对手中毒消耗血量:" + str(poison_damage) + msg = f"对手中毒消耗血量: {number_to(poison_damage)}" elif buff_type == '9': health_stolen = (damage1 * (buff_value + random_buff.random_xx) // 100) * (1 - boss_buff.boss_xx) mana_stolen = (damage1 * buff_tow // 100) * (1 - boss_buff.boss_xl) @@ -1758,12 +1798,12 @@ def after_atk_sub_buff_handle(player1_sub_open, player1, user1_main_buff_data, s player1['气血'] = min(player1['气血'], player1['max_hp']) player1['真元'] += mana_stolen player1['真元'] = min(player1['真元'], player1['max_mp']) - msg = f"吸取气血: {str(health_stolen)}, 吸取真元: {str(mana_stolen)}" + msg = f"吸取气血: {number_to(health_stolen)}, 吸取真元: {number_to(mana_stolen)}" return player1, player2, msg -class UserBattleBuffDate: # 辅修功法14 +class UserBattleBuffData: # 辅修功法14 def __init__(self, user_id): """用户战斗Buff数据""" self.user_id = user_id diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/query_optimization.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/query_optimization.py new file mode 100644 index 00000000..1c2876b2 --- /dev/null +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/query_optimization.py @@ -0,0 +1,362 @@ +""" +查询优化模块 +用于提供PostgreSQL查询优化功能 +""" +from typing import List, Dict +import time +import logging + +logger = logging.getLogger("xiuxian_query_optimizer") + +# 全局连接池引用 +_POOL = None +# 查询缓存 +_QUERY_CACHE = {} +# 慢查询阈值(秒) +SLOW_QUERY_THRESHOLD = 0.5 + +def set_pool(pool): + """设置全局连接池引用""" + global _POOL + _POOL = pool + +async def explain_query(query: str, params: List = None) -> List[Dict]: + """ + 分析查询执行计划 + + 参数: + query: SQL查询 + params: 查询参数 + + 返回: + 查询计划的JSON表示 + """ + if _POOL is None: + raise ValueError("连接池未初始化") + + params = params or [] + explain_query = f"EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) {query}" + + async with _POOL.acquire() as conn: + result = await conn.fetch(explain_query, *params) + return result[0][0] + + +async def optimize_query(query: str, params: List = None) -> Dict: + """ + 分析并提供查询优化建议 + + 参数: + query: SQL查询 + params: 查询参数 + + 返回: + 优化建议字典 + """ + plan = await explain_query(query, params) + + # 提取执行时间 + execution_time = plan[0]["Execution Time"] + planning_time = plan[0]["Planning Time"] + + # 分析结果 + result = { + "execution_time_ms": execution_time, + "planning_time_ms": planning_time, + "total_time_ms": execution_time + planning_time, + "is_slow": execution_time > SLOW_QUERY_THRESHOLD * 1000, + "suggestions": [] + } + + # 查找全表扫描 + def find_seq_scans(node): + findings = [] + if node.get("Node Type") == "Seq Scan": + findings.append({ + "issue": "全表扫描", + "table": node.get("Relation Name"), + "suggestion": f"考虑为表 {node.get('Relation Name')} 添加索引,覆盖 {node.get('Filter', '未知条件')}" + }) + + for child in node.get("Plans", []): + findings.extend(find_seq_scans(child)) + + return findings + + # 查找高成本操作 + def find_high_cost(node, threshold=1000): + findings = [] + if node.get("Total Cost", 0) > threshold: + findings.append({ + "issue": "高成本操作", + "node_type": node.get("Node Type"), + "cost": node.get("Total Cost"), + "suggestion": f"优化 {node.get('Node Type')} 操作,当前成本 {node.get('Total Cost')}" + }) + + for child in node.get("Plans", []): + findings.extend(find_high_cost(child, threshold)) + + return findings + + # 分析查询计划 + node = plan[0]["Plan"] + result["suggestions"].extend(find_seq_scans(node)) + result["suggestions"].extend(find_high_cost(node)) + + # 基本建议 + if result["is_slow"]: + result["suggestions"].append({ + "issue": "查询慢", + "suggestion": "考虑重写查询或添加适当的索引" + }) + + return result + +class QueryCache: + """ + 简单的查询结果缓存 + 适用于频繁重复且结果不常变化的查询 + """ + def __init__(self, ttl=60): # 默认缓存60秒 + self.cache = {} + self.ttl = ttl + + def get(self, key): + """获取缓存的查询结果""" + if key in self.cache: + entry = self.cache[key] + if time.time() < entry["expires"]: + return entry["data"] + else: + # 过期了,删除 + del self.cache[key] + return None + + def set(self, key, data): + """缓存查询结果""" + self.cache[key] = { + "data": data, + "expires": time.time() + self.ttl + } + + def invalidate(self, key=None): + """使缓存失效""" + if key is None: + self.cache.clear() + elif key in self.cache: + del self.cache[key] + +# 全局缓存实例 +_query_cache = QueryCache() + +async def cached_query(query: str, params: List = None, ttl: int = 60): + """ + 带缓存的查询函数 + + 参数: + query: SQL查询 + params: 查询参数 + ttl: 缓存生存时间(秒) + + 返回: + 查询结果 + """ + if _POOL is None: + raise ValueError("连接池未初始化") + + params = params or [] + + # 使用查询和参数作为缓存键 + cache_key = f"{query}:{str(params)}" + cached_result = _query_cache.get(cache_key) + + if cached_result is not None: + return cached_result + + # 缓存未命中,执行查询 + start_time = time.time() + async with _POOL.acquire() as conn: + result = await conn.fetch(query, *params) + + query_time = time.time() - start_time + + # 记录慢查询 + if query_time > SLOW_QUERY_THRESHOLD: + logger.warning(f"慢查询 ({query_time:.2f}s): {query}") + + # 缓存结果 + _query_cache.set(cache_key, result) + + return result + +async def force_query(query: str, params: List = None): + """ + 强制查询数据库,不使用缓存 + 适用于需要绝对最新数据的场景 + + 参数: + query: SQL查询 + params: 查询参数 + + 返回: + 查询结果 + """ + if _POOL is None: + raise ValueError("连接池未初始化") + + params = params or [] + + # 直接执行查询,跳过缓存 + start_time = time.time() + async with _POOL.acquire() as conn: + result = await conn.fetch(query, *params) + + query_time = time.time() - start_time + + # 记录慢查询 + if query_time > SLOW_QUERY_THRESHOLD: + logger.warning(f"强制查询 ({query_time:.2f}s): {query}") + + return result + +# 查询统计 +_QUERY_STATS = { + "total_queries": 0, + "slow_queries": 0, + "query_times": {} # 查询 -> 平均执行时间 +} + +async def monitored_query(query: str, params: List = None): + """ + 带监控的查询函数 + + 参数: + query: SQL查询 + params: 查询参数 + + 返回: + 查询结果 + """ + if _POOL is None: + raise ValueError("连接池未初始化") + + params = params or [] + + # 更新统计信息 + global _QUERY_STATS + _QUERY_STATS["total_queries"] += 1 + + # 执行查询并计时 + start_time = time.time() + async with _POOL.acquire() as conn: + result = await conn.fetch(query, *params) + + query_time = time.time() - start_time + + # 记录查询时间 + query_key = query.strip() + if query_key in _QUERY_STATS["query_times"]: + # 计算移动平均值 + old_avg = _QUERY_STATS["query_times"][query_key]["avg_time"] + count = _QUERY_STATS["query_times"][query_key]["count"] + new_avg = (old_avg * count + query_time) / (count + 1) + + _QUERY_STATS["query_times"][query_key] = { + "avg_time": new_avg, + "count": count + 1, + "last_time": query_time + } + else: + _QUERY_STATS["query_times"][query_key] = { + "avg_time": query_time, + "count": 1, + "last_time": query_time + } + + # 记录慢查询 + if query_time > SLOW_QUERY_THRESHOLD: + _QUERY_STATS["slow_queries"] += 1 + logger.warning(f"慢查询 ({query_time:.2f}s): {query}") + + return result + +def get_query_stats(): + """获取查询统计信息""" + return _QUERY_STATS + +def reset_query_stats(): + """重置查询统计信息""" + global _QUERY_STATS + _QUERY_STATS = { + "total_queries": 0, + "slow_queries": 0, + "query_times": {} + } + + +# 物化视图 +MATERIALIZED_VIEWS = { + "create_user_stats_view": """ + CREATE MATERIALIZED VIEW IF NOT EXISTS xiuxian_user_stats AS + SELECT + level, + COUNT(*) as user_count, + AVG(exp) as avg_exp, + MAX(exp) as max_exp, + MIN(exp) as min_exp, + AVG(power) as avg_power + FROM xiuxian_user + GROUP BY level + WITH DATA; + + CREATE UNIQUE INDEX IF NOT EXISTS idx_xiuxian_user_stats_level ON xiuxian_user_stats(level); + """, + + "create_top_users_view": """ + CREATE MATERIALIZED VIEW IF NOT EXISTS xiuxian_top_users AS + SELECT + user_id, + user_name, + level, + exp, + power, + ROW_NUMBER() OVER (ORDER BY exp DESC) as rank + FROM xiuxian_user + WITH DATA; + + CREATE UNIQUE INDEX IF NOT EXISTS idx_xiuxian_top_users_rank ON xiuxian_top_users(rank); + CREATE INDEX IF NOT EXISTS idx_xiuxian_top_users_user_id ON xiuxian_top_users(user_id); + """ +} + +async def create_materialized_views(): + """创建物化视图""" + if _POOL is None: + raise ValueError("连接池未初始化") + + async with _POOL.acquire() as conn: + for view_sql in MATERIALIZED_VIEWS.values(): + await conn.execute(view_sql) + +async def refresh_materialized_view(view_name: str): + """刷新物化视图""" + if _POOL is None: + raise ValueError("连接池未初始化") + + async with _POOL.acquire() as conn: + await conn.execute(f"REFRESH MATERIALIZED VIEW {view_name}") + +# 常用视图查询 +async def get_user_stats(): + """获取用户统计数据""" + query = "SELECT * FROM xiuxian_user_stats ORDER BY level" + async with _POOL.acquire() as conn: + return await conn.fetch(query) + +async def get_user_rank(user_id: int): + """获取用户排名""" + query = "SELECT rank FROM xiuxian_top_users WHERE user_id = $1" + async with _POOL.acquire() as conn: + result = await conn.fetchval(query, user_id) + return result \ No newline at end of file diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/transaction_optimization.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/transaction_optimization.py new file mode 100644 index 00000000..944ff86f --- /dev/null +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/transaction_optimization.py @@ -0,0 +1,182 @@ +""" +事务和并发优化模块 +用于提供PostgreSQL事务和并发处理的优化功能 +""" +import asyncio +from typing import Any, List +import asyncpg +from contextlib import asynccontextmanager +from functools import wraps + +# 全局连接池引用 +_POOL = None + +def set_pool(pool): + """设置全局连接池引用""" + global _POOL + _POOL = pool + +@asynccontextmanager +async def transaction(isolation_level="read committed"): + """ + 事务上下文管理器,提供可配置的事务隔离级别 + + isolation_level 选项: + - "serializable": 最高隔离级别,防止所有并发问题,但性能最低 + - "repeatable read": 防止脏读和不可重复读,但不防止幻读 + - "read committed": 防止脏读,默认级别 + - "read uncommitted": 最低隔离级别,性能最高但可能出现脏读 + """ + if _POOL is None: + raise ValueError("连接池未初始化") + + conn = await _POOL.acquire() + tr = None + try: + tr = conn.transaction(isolation=isolation_level) + await tr.start() + yield conn + await tr.commit() + except Exception as e: + if tr and not tr.is_closed(): + await tr.rollback() + raise e + finally: + await _POOL.release(conn) + +async def with_lock(user_id: int, timeout: float = 10.0): + """ + 使用行级锁防止并发更新同一用户数据 + + 示例用法: + async with with_lock(user_id): + # 更新用户操作 + """ + if _POOL is None: + raise ValueError("连接池未初始化") + + conn = await _POOL.acquire() + try: + # 使用pg_advisory_lock,一种轻量级锁机制 + # 将user_id转换为大整数作为锁ID + await conn.execute(f"SELECT pg_advisory_lock({user_id})") + yield conn + finally: + await conn.execute(f"SELECT pg_advisory_unlock({user_id})") + await _POOL.release(conn) + +async def update_user_with_lock(user_id: int, update_query: str, *args): + """ + 使用行锁安全地更新用户数据 + + 参数: + user_id: 用户ID + update_query: 更新SQL + args: SQL参数 + + 示例: + await update_user_with_lock( + 123, + "UPDATE xiuxian_user SET exp = exp + $1 WHERE user_id = $2", + 1000, 123 + ) + """ + async with transaction("read committed") as conn: + # 使用FOR UPDATE锁定行 + await conn.execute( + "SELECT id FROM xiuxian_user WHERE user_id = $1 FOR UPDATE", + user_id + ) + # 执行更新 + return await conn.execute(update_query, *args) + +def retry_operation(max_retries: int = 3, retry_delay: float = 0.5): + """ + 重试装饰器,处理并发冲突等临时错误 + + 参数: + max_retries: 最大重试次数 + retry_delay: 重试间隔(秒) + + 用法: + @retry_operation(max_retries=5) + async def some_function(arg1, arg2): + # 可能失败的数据库操作 + """ + def decorator(func): + @wraps(func) + async def wrapper(*args, **kwargs): + last_error = None + for attempt in range(max_retries): + try: + return await func(*args, **kwargs) + except asyncpg.exceptions.DeadlockDetectedError as e: + last_error = e + await asyncio.sleep(retry_delay * (2 ** attempt)) # 指数退避 + except asyncpg.exceptions.UniqueViolationError as e: + # 唯一约束冲突,这种情况不重试 + raise e + except (asyncpg.exceptions.PostgresError) as e: + last_error = e + if "could not serialize access" in str(e): + # 序列化失败,可以重试 + await asyncio.sleep(retry_delay * (2 ** attempt)) + else: + # 其他PostgreSQL错误,不重试 + raise e + + # 如果所有重试都失败 + raise last_error or RuntimeError("操作失败,超出最大重试次数") + + return wrapper + return decorator + +# 批量操作函数 +async def bulk_insert(table: str, columns: List[str], values: List[List[Any]], + chunk_size: int = 1000): + """ + 高效的批量插入函数 + + 参数: + table: 表名 + columns: 列名列表 + values: 值的列表的列表 + chunk_size: 每次插入的最大行数 + """ + if not values: + return 0 + + if _POOL is None: + raise ValueError("连接池未初始化") + + async with _POOL.acquire() as conn: + async with conn.transaction(): + count = 0 + # 分块处理 + for i in range(0, len(values), chunk_size): + chunk = values[i:i+chunk_size] + + # 构建VALUES部分,每行一个($1, $2, ...)元组 + placeholders = [] + flat_values = [] + + for row in chunk: + # 为这一行创建占位符 ($1, $2, ...) + row_placeholders = [] + for j, val in enumerate(row): + param_idx = len(flat_values) + 1 # PostgreSQL参数从1开始 + row_placeholders.append(f"${param_idx}") + flat_values.append(val) + + placeholders.append(f"({', '.join(row_placeholders)})") + + # 构建完整SQL + columns_str = ', '.join(columns) + values_str = ', '.join(placeholders) + + sql = f"INSERT INTO {table} ({columns_str}) VALUES {values_str}" + + result = await conn.execute(sql, *flat_values) + count += int(result.split()[1]) # 解析"INSERT 0 X"中的X + + return count \ No newline at end of file diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/utils.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/utils.py index 652e536f..37738e6d 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/utils.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/utils.py @@ -8,24 +8,23 @@ from base64 import b64encode from io import BytesIO from pathlib import Path - -from nonebot.adapters import MessageSegment from nonebot.adapters.onebot.v11 import ( Bot, GroupMessageEvent, - MessageSegment, + MessageSegment ) from nonebot.params import Depends from PIL import Image, ImageDraw, ImageFont from wcwidth import wcwidth - from ..xiuxian_config import XiuConfig from .data_source import jsondata -from .xiuxian2_handle import XiuxianDateManage +from .xiuxian2_handle import XiuxianDataManager -sql_message = XiuxianDateManage() # sql类 + # sql类 boss_img_path = Path() / "data" / "xiuxian" / "boss_img" +# 定义全局变量保存 QQ 官方 bot ID 映射 +QBOT_ID_DATA: dict[str, str] = {} class MyEncoder(json.JSONEncoder): def default(self, obj): @@ -41,7 +40,7 @@ def default(self, obj): return super(MyEncoder, self).default(obj) -def check_user_type(user_id, need_type): +async def check_user_type(user_id, need_type): """ :说明: `check_user_type` > 匹配用户状态,返回是否状态一致 @@ -51,11 +50,11 @@ def check_user_type(user_id, need_type): """ isType = False msg = "" - user_cd_message = sql_message.get_user_cd(user_id) + user_cd_message = await XiuxianDataManager().get_user_time(user_id) if user_cd_message is None: user_type = 0 else: - user_type = user_cd_message["type"] + user_type = user_cd_message["schedule_type"] if user_type == need_type: # 状态一致 isType = True @@ -75,7 +74,7 @@ def check_user_type(user_id, need_type): return isType, msg -def check_user(event: GroupMessageEvent): +async def check_user(event: GroupMessageEvent): """ 判断用户信息是否存在 :返回参数: @@ -83,10 +82,17 @@ def check_user(event: GroupMessageEvent): * `user_info: 用户 * `msg: 消息体 """ - + from ..xiuxian_config import XiuConfig + isUser = False - user_id = event.get_user_id() - user_info = sql_message.get_user_info_with_id(user_id) + user_id = int(event.get_user_id()) + + if XiuConfig().postgresql_url is None or XiuConfig().postgresql_url == "": + user_info = None + msg = "请先在xiuxian_config.py文件中配置数据库地址!" + return isUser, user_info, msg + + user_info = await XiuxianDataManager().get_user_infos_by_ids(user_id) if user_info is None: msg = "修仙界没有道友的信息,请输入【我要修仙】加入!" else: @@ -354,7 +360,7 @@ def draw_rectangle(draw, rect, width): ) # 四元组(left, top, right, bottom) user_w = user_bbox[2] - user_bbox[0] # 宽度 = right - left - user_h = user_bbox[3] - user_bbox[1] + # user_h = user_bbox[3] - user_bbox[1] draw.text( ((w - user_w) // 2, out_padding + padding), title, @@ -412,7 +418,7 @@ def save_image_with_compression(self, out_img): out_img.save(img_byte_arr, format="JPEG", quality=compression_quality) else: out_img.save(img_byte_arr, format="WebP", quality=compression_quality) - except: + except ValueError: # 尝试降级为 JPEG out_img.save(img_byte_arr, format="JPEG", quality=compression_quality) @@ -503,11 +509,24 @@ async def send_msg_handler(bot, event, *args): elif len(args) == 1 and isinstance(args[0], list): messages = args[0] img = Txt2Img() - messages = "\n".join([str(msg["data"]["content"]) for msg in messages]) + + # 检查是否是name, uin, msgs格式 + if len(messages) == 3 and not isinstance(messages[0], dict) and isinstance(messages[2], list): + name, uin, msgs = messages + messages_text = "\n".join(msgs) + else: + # 处理节点消息格式 + try: + messages_text = "\n".join([str(msg["data"]["content"]) for msg in messages]) + except (TypeError, KeyError): + # 如果遇到错误,尝试直接转换 + messages_text = "\n".join([str(msg) for msg in messages]) + if XiuConfig().img_send_type == "io": - img_data = await img.io_draw_to(messages) + img_data = await img.io_draw_to(messages_text) elif XiuConfig().img_send_type == "base64": - img_data = img.sync_draw_to(messages) + img_data = img.sync_draw_to(messages_text) + if isinstance(event, GroupMessageEvent): await bot.send_group_msg( group_id=event.group_id, message=MessageSegment.image(img_data) @@ -544,7 +563,13 @@ def number_to(num): """ 递归实现,精确为最大单位值 + 小数点后一位 处理科学计数法表示的数值 + 增加负数支持 """ + # 处理负数情况 + is_negative = False + if num < 0: + is_negative = True + num = abs(num) def strofsize(num, level): if level >= 29: @@ -594,19 +619,42 @@ def strofsize(num, level): num, level = strofsize(num, 0) if level >= len(units): level = len(units) - 1 - return f"{round(num, 1)}{units[level]}" + + # 根据是否为负数添加负号 + if is_negative: + return f"负{round(num, 1)}{units[level]}" + else: + return f"{round(num, 1)}{units[level]}" async def pic_msg_format(msg, event): - user_name = event.sender.card if event.sender.card else event.sender.nickname + isUser, user_info, msg = await check_user(event) + user_name = event.sender.card if event.sender.card else user_info['user_name'] or event.sender.nickname result = "@" + user_name + "\n" + msg return result -async def handle_send(bot, event, send_group_id, msg: str): +async def get_sender_display_name(event, user_info): + """ + 优先返回 user_info['user_name'],否则回退到 event.sender.nickname。 + """ + if user_info is None: + return event.sender.nickname or "不知名道友" + return user_info.get('user_name') or event.sender.nickname + + +async def handle_send(bot, event, send_group_id, msg: str, boss_name=""): """处理文本,根据配置发送文本或者图片消息""" + if event and hasattr(event, 'user_id'): + user_id = event.user_id + user_info = await XiuxianDataManager().get_user_infos_by_ids(user_id) + user_name = await get_sender_display_name(event, user_info) + at_text = f"@{user_name}\n" + else: + at_text = "" + if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(at_text + msg, boss_name=boss_name) await bot.send_group_msg( group_id=int(send_group_id), message=MessageSegment.image(pic), @@ -615,21 +663,101 @@ async def handle_send(bot, event, send_group_id, msg: str): await bot.send_group_msg(group_id=int(send_group_id), message=msg) -def append_draw_card_node(bot: Bot, list_tp: list, summary: str, content): - """添加节点进转发消息 - +def build_forward_msg_list(bot: Bot, summary: str, text_msg: str, images: list = None, image_params: dict = None): + """创建转发消息节点列表,用于构建包含文本和多张图片的转发消息 + Args: - list_tp (list): 要制作的转发消息列表 - summary (str): 转发消息的标题 - content (_type_): 转发消息的内容 + bot (Bot): 机器人实例 + summary (str): 转发消息的标题/用户名 + text_msg (str): 要发送的文本消息 + images (list, optional): 要发送的图片列表,如卡片名列表 + image_params (dict, optional): 图片处理相关参数,可包含以下键: + - use_merge_forward_send (bool): 是否使用合并转发发送 + - img_path (Path): 图片路径 + - img_format (str): 图片格式,默认为"png" + - get_image_func (callable): 获取图片的函数,默认直接使用MessageSegment.image + + Returns: + list: 转发消息节点列表,可用于send_msg_handler """ - list_tp.append( - { + # 检查是否使用合并转发发送 + use_merge_forward_send = image_params.get("use_merge_forward_send", XiuConfig().merge_forward_send) if image_params else XiuConfig().merge_forward_send + + if use_merge_forward_send: + # 使用合并转发发送 + list_tp = [] + + # 添加文本消息 + list_tp.append({ "type": "node", "data": { "name": summary, "uin": bot.self_id, - "content": content, + "content": text_msg, }, - } - ) + }) + + # 如果提供了图片列表,则添加图片 + if images: + img_path = image_params.get("img_path") if image_params else None + img_format = image_params.get("img_format", "png") if image_params else "png" + get_image_func = image_params.get("get_image_func") if image_params else None + + for image in images: + if get_image_func: + # 使用提供的图片获取函数 + img = get_image_func(image) + elif img_path and use_merge_forward_send: + # 使用路径构建图片 + img = MessageSegment.image(img_path / f"{image}.{img_format}") + else: + # 默认情况下只使用图片名称作为内容 + img = str(image) + + list_tp.append({ + "type": "node", + "data": { + "name": summary, + "uin": bot.self_id, + "content": img, + }, + }) + + return list_tp + else: + # 不使用合并转发发送,返回纯文本消息 + # 组合所有图片名称与文本消息 + result_msgs = [] + result_msgs.append(text_msg) + + if images: + result_msgs.extend([str(img) for img in images]) + + # 返回适合send_msg_handler的格式 + return [summary, bot.self_id, result_msgs] + + +def get_qbot_uid(qbot_id: str) -> str: + """获取qq官bot的uid""" + return QBOT_ID_DATA.get(qbot_id, "") + +def is_qbot(session) -> bool: + """判断bot是否为qq官bot + + 参数: + session: Uninfo 或 Bot 实例 + + 返回: + bool: 是否为官bot + """ + try: + if isinstance(session, Bot): + return bool(get_qbot_uid(session.self_id)) + elif hasattr(session, 'self_id'): + if hasattr(session, 'scope'): + return str(session.scope) in ['QQClient', 'qq_client', 'qq_api'] + return bool(get_qbot_uid(session.self_id)) + return False + except (AttributeError, TypeError): + # 如果出现任何错误,默认返回 False + return False diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/vacuum_optimization.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/vacuum_optimization.py new file mode 100644 index 00000000..842e196e --- /dev/null +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/vacuum_optimization.py @@ -0,0 +1,479 @@ +""" +PostgreSQL数据库垃圾回收优化模块 +提供自动和手动VACUUM功能,优化数据库性能 +""" +import asyncio +import logging +import datetime + +# 初始化日志 +logger = logging.getLogger("xiuxian_vacuum") + +# 全局连接池引用 +_POOL = None + +def set_pool(pool): + """设置全局连接池引用""" + global _POOL + _POOL = pool + +# 数据库表清单 +TABLES = [ + "xiuxian_user", + "xiuxian_time", + "xiuxian_buff", + "xiuxian_sect", + "xiuxian_back", + "xiuxian_impart" +] + +# 垃圾回收配置 +VACUUM_CONFIG = { + "auto_vacuum_interval": 12 * 3600, # 12小时自动VACUUM + "vacuum_full_interval": 7 * 24 * 3600, # 7天执行一次VACUUM FULL + "analyze_interval": 6 * 3600, # 6小时自动ANALYZE + "aggressive_vacuum_threshold": 10000, # 当表修改超过这个数时执行更积极的VACUUM + "last_vacuum_time": {}, # 记录上次VACUUM时间 + "last_analyze_time": {}, # 记录上次ANALYZE时间 + "last_vacuum_full_time": None, # 上次完整VACUUM时间 +} + +async def get_table_stats(): + """获取表统计信息""" + if _POOL is None: + raise ValueError("连接池未初始化") + + stats = {} + + async with _POOL.acquire() as conn: + for table in TABLES: + # 检查表是否存在 + exists = await check_table_exists(table) + if not exists: + stats[table] = { + "exists": False, + "size": "0 bytes", + "size_bytes": 0, + "row_count": 0, + "inserts": 0, + "updates": 0, + "deletes": 0, + "live_tuples": 0, + "dead_tuples": 0, + } + continue + + try: + # 获取表的大小 + size_query = f"SELECT pg_size_pretty(pg_total_relation_size('{table}')) as size, pg_total_relation_size('{table}') as bytes" + size_result = await conn.fetchrow(size_query) + + # 获取表的行数 + count_query = f"SELECT COUNT(*) as count FROM {table}" + count_result = await conn.fetchval(count_query) + + # 获取表的修改统计 + stat_query = f""" + SELECT + n_tup_ins as inserts, + n_tup_upd as updates, + n_tup_del as deletes, + n_live_tup as live_tuples, + n_dead_tup as dead_tuples + FROM pg_stat_user_tables + WHERE relname = '{table}' + """ + stat_result = await conn.fetchrow(stat_query) + + stats[table] = { + "exists": True, + "size": size_result["size"], + "size_bytes": size_result["bytes"], + "row_count": count_result, + "inserts": stat_result["inserts"] if stat_result else 0, + "updates": stat_result["updates"] if stat_result else 0, + "deletes": stat_result["deletes"] if stat_result else 0, + "live_tuples": stat_result["live_tuples"] if stat_result else 0, + "dead_tuples": stat_result["dead_tuples"] if stat_result else 0, + } + except Exception as e: + logger.error(f"获取表 {table} 的统计信息时出错: {e}") + stats[table] = { + "exists": True, + "size": "0 bytes", + "size_bytes": 0, + "row_count": 0, + "inserts": 0, + "updates": 0, + "deletes": 0, + "live_tuples": 0, + "dead_tuples": 0, + } + + return stats + +async def check_table_exists(table: str) -> bool: + """检查表是否存在""" + if _POOL is None: + return False + + try: + async with _POOL.acquire() as conn: + result = await conn.fetchval( + "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = $1)", + table + ) + return bool(result) + except Exception as e: + logger.error(f"检查表 {table} 是否存在时出错: {e}") + return False + +async def check_all_tables_exist() -> bool: + """检查所有必要的表是否都存在""" + if _POOL is None: + return False + + all_exist = True + for table in TABLES: + exists = await check_table_exists(table) + if not exists: + all_exist = False + logger.warning(f"表 {table} 不存在") + + return all_exist + +async def vacuum_table(table: str, full: bool = False, analyze: bool = True): + """ + 对指定表执行VACUUM操作 + + 参数: + table: 表名 + full: 是否执行VACUUM FULL (会锁表) + analyze: 是否同时执行ANALYZE + """ + if _POOL is None: + raise ValueError("连接池未初始化") + + # 先检查表是否存在 + if not await check_table_exists(table): + logger.error(f"对表 {table} 执行 VACUUM 失败: 表不存在") + return False + + try: + start_time = datetime.datetime.now() + operation = "VACUUM FULL" if full else "VACUUM" + if analyze: + operation += " ANALYZE" + + logger.info(f"开始对表 {table} 执行 {operation}") + + async with _POOL.acquire() as conn: + await conn.execute(f"{operation} {table}") + + end_time = datetime.datetime.now() + duration = (end_time - start_time).total_seconds() + + logger.info(f"表 {table} 的 {operation} 完成,耗时 {duration:.2f} 秒") + + # 更新上次操作时间 + now = datetime.datetime.now().timestamp() + if full: + VACUUM_CONFIG["last_vacuum_full_time"] = now + elif analyze: + VACUUM_CONFIG["last_vacuum_time"][table] = now + VACUUM_CONFIG["last_analyze_time"][table] = now + else: + VACUUM_CONFIG["last_vacuum_time"][table] = now + + return True + except Exception as e: + logger.error(f"对表 {table} 执行 {operation} 失败: {e}") + return False + +async def analyze_table(table: str): + """ + 对指定表执行ANALYZE操作 + + 参数: + table: 表名 + """ + if _POOL is None: + raise ValueError("连接池未初始化") + + # 先检查表是否存在 + if not await check_table_exists(table): + logger.error(f"对表 {table} 执行 ANALYZE 失败: 表不存在") + return False + + try: + start_time = datetime.datetime.now() + logger.info(f"开始对表 {table} 执行 ANALYZE") + + async with _POOL.acquire() as conn: + await conn.execute(f"ANALYZE {table}") + + end_time = datetime.datetime.now() + duration = (end_time - start_time).total_seconds() + + logger.info(f"表 {table} 的 ANALYZE 完成,耗时 {duration:.2f} 秒") + + # 更新上次分析时间 + VACUUM_CONFIG["last_analyze_time"][table] = datetime.datetime.now().timestamp() + return True + except Exception as e: + logger.error(f"对表 {table} 执行 ANALYZE 失败: {e}") + return False + +async def vacuum_all_tables(full: bool = False): + """ + 对所有表执行VACUUM操作 + + 参数: + full: 是否执行VACUUM FULL + """ + results = {} + + # 检查是否所有表都存在 + tables_exist = await check_all_tables_exist() + if not tables_exist: + logger.warning("一些表不存在,只对存在的表执行VACUUM") + + try: + stats_before = await get_table_stats() + + for table in TABLES: + # 检查表是否存在 + if not await check_table_exists(table): + logger.warning(f"表 {table} 不存在,跳过VACUUM") + results[table] = False + continue + + try: + results[table] = await vacuum_table(table, full=full) + except Exception as e: + logger.error(f"对表 {table} 执行VACUUM时出错: {e}") + results[table] = False + + # 尝试获取操作后的表统计信息,如果失败不影响整体结果 + try: + stats_after = await get_table_stats() + + # 计算节省的空间 + total_saved = 0 + for table in TABLES: + if table not in stats_before or table not in stats_after: + continue + if not stats_before[table]["exists"] or not stats_after[table]["exists"]: + continue + + saved = stats_before[table]["size_bytes"] - stats_after[table]["size_bytes"] + total_saved += saved if saved > 0 else 0 + + if total_saved > 0: + logger.info(f"VACUUM 操作总共节省了 {total_saved / (1024*1024):.2f} MB 空间") + except Exception as e: + logger.error(f"获取VACUUM后表统计信息时出错: {e}") + + return results + except Exception as e: + logger.error(f"执行全部表VACUUM时出错: {e}") + return {table: False for table in TABLES} + +async def start_vacuum_service(): + """启动VACUUM服务""" + # 检查表是否存在 + tables_exist = await check_all_tables_exist() + if not tables_exist: + logger.warning("一些必要的表不存在,VACUUM服务将在表创建后启动") + # 启动一个延迟任务,每5分钟检查一次表是否已创建 + asyncio.create_task(wait_for_tables_and_start()) + return + + # 优化自动VACUUM设置 + await optimize_autovacuum_settings() + + # 启动自动VACUUM任务 + asyncio.create_task(automatic_vacuum_task()) + + logger.info("VACUUM优化服务已启动") + +async def wait_for_tables_and_start(): + """等待表创建完成后启动VACUUM服务""" + retry_count = 0 + max_retries = 12 # 最多尝试12次,即1小时 + + while retry_count < max_retries: + logger.info(f"等待表创建完成,第{retry_count+1}次检查...") + tables_exist = await check_all_tables_exist() + + if tables_exist: + logger.info("所有必要的表已创建,现在启动VACUUM服务") + # 优化自动VACUUM设置 + await optimize_autovacuum_settings() + + # 启动自动VACUUM任务 + asyncio.create_task(automatic_vacuum_task()) + + logger.info("VACUUM优化服务已启动") + return + + # 等待5分钟后再次检查 + await asyncio.sleep(300) + retry_count += 1 + + logger.warning("在1小时内未能检测到所有必要的表,VACUUM服务未启动") + +async def automatic_vacuum_task(): + """自动VACUUM任务""" + try: + # 初始化上次操作时间 + for table in TABLES: + VACUUM_CONFIG["last_vacuum_time"][table] = 0 + VACUUM_CONFIG["last_analyze_time"][table] = 0 + + VACUUM_CONFIG["last_vacuum_full_time"] = 0 + + while True: + # 检查表是否都存在 + tables_exist = await check_all_tables_exist() + if not tables_exist: + logger.warning("一些表不存在,跳过本次VACUUM检查") + await asyncio.sleep(1800) # 30分钟后再检查 + continue + + now = datetime.datetime.now().timestamp() + + try: + # 获取表统计信息 + stats = await get_table_stats() + + # 检查每个表是否需要VACUUM + for table in TABLES: + # 跳过不存在的表 + if not await check_table_exists(table): + continue + + # 判断是否需要VACUUM + last_vacuum = VACUUM_CONFIG["last_vacuum_time"].get(table, 0) + if now - last_vacuum > VACUUM_CONFIG["auto_vacuum_interval"]: + logger.info(f"表 {table} 超过自动VACUUM间隔,执行常规VACUUM") + await vacuum_table(table, full=False, analyze=False) + continue + + # 检查是否有大量修改需要紧急VACUUM + dead_ratio = 0 + if stats[table]["live_tuples"] > 0: + dead_ratio = stats[table]["dead_tuples"] / stats[table]["live_tuples"] + + if (dead_ratio > 0.2 or stats[table]["dead_tuples"] > VACUUM_CONFIG["aggressive_vacuum_threshold"]): + logger.info(f"表 {table} 检测到大量死元组 ({stats[table]['dead_tuples']}行),执行紧急VACUUM") + await vacuum_table(table, full=False, analyze=True) + + # 判断是否需要ANALYZE + last_analyze = VACUUM_CONFIG["last_analyze_time"].get(table, 0) + if now - last_analyze > VACUUM_CONFIG["analyze_interval"]: + logger.info(f"表 {table} 超过自动ANALYZE间隔,执行ANALYZE") + await analyze_table(table) + + # 判断是否需要完整VACUUM + if now - VACUUM_CONFIG["last_vacuum_full_time"] > VACUUM_CONFIG["vacuum_full_interval"]: + logger.info("超过完整VACUUM间隔,执行VACUUM FULL") + await vacuum_all_tables(full=True) + except Exception as e: + logger.error(f"执行VACUUM检查时出错: {e}") + + # 等待下一次检查 + await asyncio.sleep(3600) # 每小时检查一次 + + except Exception as e: + logger.error(f"自动VACUUM任务出错: {e}") + # 出错后等待一小段时间再重试 + await asyncio.sleep(60) + asyncio.create_task(automatic_vacuum_task()) + +async def optimize_autovacuum_settings(): + """优化PostgreSQL的自动VACUUM设置""" + if _POOL is None: + raise ValueError("连接池未初始化") + + try: + async with _POOL.acquire() as conn: + # 检查当前设置 + current_settings = await conn.fetch(""" + SELECT name, setting, unit + FROM pg_settings + WHERE name LIKE 'autovacuum%' OR name LIKE '%vacuum%' + """) + + settings = {} + for row in current_settings: + settings[row['name']] = row['setting'] + + # 记录当前设置而不尝试更改它们 + logger.info("当前自动VACUUM设置:") + for name, value in settings.items(): + logger.info(f" {name}: {value}") + + # 以下参数需要在配置文件中修改,无法在运行时更改 + # 记录建议设置 + logger.info("建议的自动VACUUM设置:") + logger.info(" autovacuum = on") + logger.info(" autovacuum_vacuum_threshold = 50") + logger.info(" autovacuum_analyze_threshold = 50") + logger.info(" autovacuum_vacuum_scale_factor = 0.1") + logger.info(" autovacuum_analyze_scale_factor = 0.05") + logger.info(" autovacuum_naptime = 60s") + logger.info(" autovacuum_max_workers = 3") + + # 可以在不修改参数的情况下仅执行ANALYZE来更新统计信息 + for table in TABLES: + await analyze_table(table) + + logger.info("已执行表分析以更新统计信息") + return True + except Exception as e: + logger.error(f"优化自动VACUUM设置时出错: {e}") + return False + +async def reindex_table(table: str): + """ + 对指定表重建索引 + + 参数: + table: 表名 + """ + if _POOL is None: + raise ValueError("连接池未初始化") + + try: + start_time = datetime.datetime.now() + logger.info(f"开始重建表 {table} 的索引") + + async with _POOL.acquire() as conn: + # 获取表的所有索引 + indexes = await conn.fetch(""" + SELECT indexname + FROM pg_indexes + WHERE tablename = '{table}' + """) + + for index in indexes: + index_name = index['indexname'] + await conn.execute(f"REINDEX INDEX {index_name}") + logger.info(f"已重建索引: {index_name}") + + end_time = datetime.datetime.now() + duration = (end_time - start_time).total_seconds() + + logger.info(f"表 {table} 的索引重建完成,耗时 {duration:.2f} 秒") + return True + except Exception as e: + logger.error(f"重建表 {table} 的索引时出错: {e}") + return False + +async def reindex_all_tables(): + """重建所有表的索引""" + results = {} + for table in TABLES: + results[table] = await reindex_table(table) + return results \ No newline at end of file diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/xiuxian2_handle.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/xiuxian2_handle.py index 82a62e28..28856cee 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/xiuxian2_handle.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/xiuxian2_handle.py @@ -4,15 +4,15 @@ import json import os import random -import sqlite3 -from datetime import datetime +import asyncpg +from datetime import datetime, timedelta from pathlib import Path from nonebot.log import logger from .data_source import jsondata from ..xiuxian_config import XiuConfig, convert_rank from .. import DRIVER from .item_json import Items -from .xn_xiuxian_impart_config import config_impart +from typing import Dict, List, Optional, Any WORKDATA = Path() / "data" / "xiuxian" / "work" PLAYERSDATA = Path() / "data" / "xiuxian" / "players" @@ -20,625 +20,844 @@ DATABASE_IMPARTBUFF = Path() / "data" / "xiuxian" SKILLPATHH = DATABASE / "功法" WEAPONPATH = DATABASE / "装备" +SEX_VALUES = [ + {"text": "随机", "value": None}, + {"text": "女", "value": True}, + {"text": "男", "value": False} +] +RARITY_COLORS = { + "common": "#CCCCCC", + "uncommon": "#222A35", + "rare": "#00A6A9", + "epic": "#804DC8", + "legendary": "#C5C660", + "mythic": "#F28234", + "exotic": "#C65043", +} +RARITY_LEVELS = [ + "common", + "uncommon", + "rare", + "epic", + "legendary", + "mythic", + "exotic", +] +RARITY_VALUES = { + "common": 1.0, # 灰 + "uncommon": 0.35, # 白 + "rare": 0.15, # 蓝 + "epic": 0.075, # 紫 + "legendary": 0.03, # 橙 + "mythic": 0.012, # 金 + "exotic": 0.005, # 虹 +} +RARITY_NAMES = { + "common": "凡品", + "uncommon": "良品", + "rare": "上品", + "epic": "极品", + "legendary": "秘宝", + "mythic": "灵宝", + "exotic": "古宝", +} +CREATURE_CATEGORY = ["plant", "worm", "fish", "beast", "bird", "reptile", "insect"] +CREATURE_CATEGORY_NAMES = { + "plant": "草木", + "worm": "赢虫", + "fish": "鱼", + "beast": "兽", + "bird": "鸟", + "reptile": "爬虫", + "insect": "甲虫", +} +ZONE_CATEGORIES = ["land", "water", "void"] +# 特殊符号常量 +_PARENTHESIS_LEFT = "(" +_PARENTHESIS_RIGHT = ")" +_BOOK_LEFT = "《" +_BOOK_RIGHT = "》" +_LINK_WORD = "之" +_NUMBER_BEGIN_SUPPLEMENT = "路" +_NUMBER_END_SUPPLEMENT = "式" +_COUNTRY = "国" +_AGE1 = "百年" +_AGE10 = "千年" +_AGE100 = "万年" xiuxian_num = "578043031" # 这里其实是修仙1作者的QQ号 -impart_num = "123451234" items = Items() -current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') -class XiuxianDateManage: + +class XiuxianDataManager: global xiuxian_num _instance = {} _has_init = {} + _pool = None + __slots__ = [] def __new__(cls): if cls._instance.get(xiuxian_num) is None: - cls._instance[xiuxian_num] = super(XiuxianDateManage, cls).__new__(cls) + cls._instance[xiuxian_num] = super(XiuxianDataManager, cls).__new__(cls) return cls._instance[xiuxian_num] def __init__(self): if not self._has_init.get(xiuxian_num): self._has_init[xiuxian_num] = True - self.database_path = DATABASE - if not self.database_path.exists(): - self.database_path.mkdir(parents=True) - self.database_path /= "xiuxian.db" - self.conn = sqlite3.connect(self.database_path, check_same_thread=False) - else: - self.database_path /= "xiuxian.db" - self.conn = sqlite3.connect(self.database_path, check_same_thread=False) - logger.opt(colors=True).info(f"修仙数据库已连接!") - self._check_data() + + async def _init_db_and_pool(self): + """初始化数据库和连接池""" + if XiuxianDataManager._pool is None: + try: + pg_url = XiuConfig().postgresql_url + if not pg_url: + raise ValueError("数据库连接字符串为空,请先在xiuxian_config.py文件中配置数据库地址!") + pg_url_parts = pg_url.split('/') + base_pg_url = '/'.join(pg_url_parts[:-1]) + '/postgres' + conn = await asyncpg.connect(base_pg_url) + try: + exists = await conn.fetchval( + "SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)", + "xiuxian" + ) + + if not exists: + # 创建数据库 + await conn.execute("CREATE DATABASE xiuxian") + logger.opt(colors=True).info("数据库xiuxian创建成功!") + finally: + await conn.close() + + # 创建PostgreSQL连接池 + XiuxianDataManager._pool = await asyncpg.create_pool( + dsn=pg_url, + min_size=XiuConfig().min_database_connection, + max_size=XiuConfig().max_database_connection + ) + logger.opt(colors=True).info("修仙PostgreSQL数据库连接池已创建!") + + # 先创建所有必要的表结构 + await self._check_data() + logger.opt(colors=True).info("修仙数据库表结构创建完成!") + + # 初始化优化模块 + try: + from .optimization_manager import apply_all_optimizations + + # 使用管理器应用所有优化 + try: + await apply_all_optimizations(pg_url) + except Exception as e: + logger.opt(colors=True).warning(f"应用数据库优化失败: {e}") + + logger.opt(colors=True).info("修仙数据库优化模块已初始化!") + except Exception as e: + logger.opt(colors=True).warning(f"初始化数据库优化模块时出错: {e}") + + logger.opt(colors=True).info("修仙数据库初始化完成!") + + except Exception as e: + logger.opt(colors=True).error(f"PostgreSQL连接池创建失败:{e}") + + @property + def pool(self): + """获取连接池""" + if XiuxianDataManager._pool is None: + raise Exception("数据库连接池尚未初始化,请先调用_init_pool方法") + return XiuxianDataManager._pool + + async def ensure_pool(self): + """确保连接池已初始化""" + if XiuxianDataManager._pool is None: + await self._init_db_and_pool() + if XiuxianDataManager._pool is None: + raise Exception("无法初始化数据库连接池") + return XiuxianDataManager._pool + + async def close(self): + """关闭数据库连接池""" + if XiuxianDataManager._pool: + await XiuxianDataManager._pool.close() + XiuxianDataManager._pool = None + logger.opt(colors=True).info("修仙PostgreSQL数据库连接池已关闭!") - def close(self): - self.conn.close() - logger.opt(colors=True).info(f"修仙数据库关闭!") + @classmethod + async def close_dbs(cls): + """关闭所有数据库连接""" + await XiuxianDataManager().close() - def _check_data(self): - """检查数据完整性""" - c = self.conn.cursor() + async def _check_data(self): + """检查数据完整性并创建必要的表和列""" + import datetime + from nonebot.log import logger + + current_time = datetime.datetime.now() + + async with self.pool.acquire() as conn: + try: + await conn.execute("SELECT count(1) FROM xiuxian_user LIMIT 1") + except asyncpg.exceptions.UndefinedTableError: + await conn.execute(""" + CREATE TABLE xiuxian_user ( + "id" SERIAL PRIMARY KEY, + "user_id" BIGINT NOT NULL, + "user_name" TEXT DEFAULT NULL, + "user_create_time" TIMESTAMP DEFAULT NULL, + "sect_id" BIGINT DEFAULT NULL, + "sect_position" SMALLINT DEFAULT NULL, + "stone" NUMERIC DEFAULT 0, + "root" TEXT NOT NULL, + "root_type" TEXT NOT NULL, + "level" TEXT NOT NULL, + "exp" NUMERIC DEFAULT 0, + "power" NUMERIC DEFAULT 0, + "hp" NUMERIC DEFAULT 100, + "mp" NUMERIC DEFAULT 100, + "atk" NUMERIC DEFAULT 10, + "atk_practice_level" SMALLINT DEFAULT 0, + "is_sign" SMALLINT DEFAULT 0, + "is_beg" SMALLINT DEFAULT 0, + "is_ban" SMALLINT DEFAULT 0, + "is_elixir" SMALLINT DEFAULT 0, + "level_up_rate" SMALLINT DEFAULT 0, + "sect_task_quantity" SMALLINT DEFAULT 0, + "sect_contribution" NUMERIC DEFAULT 0, + "blessed_spot_flag" SMALLINT DEFAULT 0, + "blessed_spot_name" TEXT DEFAULT NULL, + "blessed_spot_level" SMALLINT DEFAULT 0, + "stamina" NUMERIC DEFAULT 2400, + "work_quantity" SMALLINT DEFAULT 0 + )""") + + await conn.execute(""" + CREATE UNIQUE INDEX IF NOT EXISTS idx_xiuxian_user_user_id ON xiuxian_user(user_id); + CREATE INDEX IF NOT EXISTS idx_xiuxian_user_sect_id ON xiuxian_user(sect_id); + CREATE INDEX IF NOT EXISTS idx_xiuxian_user_user_create_time ON xiuxian_user(user_create_time); + CREATE INDEX IF NOT EXISTS idx_xiuxian_user_exp ON xiuxian_user(exp); + CREATE INDEX IF NOT EXISTS idx_xiuxian_user_power ON xiuxian_user(power); + CREATE INDEX IF NOT EXISTS idx_xiuxian_user_stone ON xiuxian_user(stone); + CREATE INDEX IF NOT EXISTS idx_xiuxian_user_level ON xiuxian_user(level); + CREATE INDEX IF NOT EXISTS idx_xiuxian_user_user_name ON xiuxian_user(user_name); + CREATE INDEX IF NOT EXISTS idx_xiuxian_user_is_sign ON xiuxian_user(is_sign); + CREATE INDEX IF NOT EXISTS idx_xiuxian_user_is_beg ON xiuxian_user(is_beg); + CREATE INDEX IF NOT EXISTS idx_xiuxian_user_is_ban ON xiuxian_user(is_ban); + CREATE INDEX IF NOT EXISTS idx_xiuxian_user_is_elixir ON xiuxian_user(is_elixir); + CREATE INDEX IF NOT EXISTS idx_xiuxian_user_sect_task_quantity ON xiuxian_user(sect_task_quantity); + """) + logger.opt(colors=True).info("xiuxian_user表及索引创建成功") - for i in XiuConfig().sql_table: - if i == "user_xiuxian": - try: - c.execute(f"select count(1) from {i}") - except sqlite3.OperationalError: - c.execute("""CREATE TABLE "user_xiuxian" ( - "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - "user_id" INTEGER NOT NULL, - "sect_id" INTEGER DEFAULT NULL, - "sect_position" INTEGER DEFAULT NULL, - "stone" integer DEFAULT 0, - "root" TEXT, - "root_type" TEXT, - "level" TEXT, - "power" integer DEFAULT 0, - "create_time" integer, - "is_sign" integer DEFAULT 0, - "is_beg" integer DEFAULT 0, - "is_ban" integer DEFAULT 0, - "exp" integer DEFAULT 0, - "user_name" TEXT DEFAULT NULL, - "level_up_cd" integer DEFAULT NULL, - "level_up_rate" integer DEFAULT 0 - );""") - elif i == "user_cd": - try: - c.execute(f"select count(1) from {i}") - except sqlite3.OperationalError: - c.execute("""CREATE TABLE "user_cd" ( - "user_id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - "type" integer DEFAULT 0, - "create_time" integer DEFAULT NULL, - "scheduled_time" integer, - "last_check_info_time" integer DEFAULT NULL -);""") - elif i == "sects": - try: - c.execute(f"select count(1) from {i}") - except sqlite3.OperationalError: - c.execute("""CREATE TABLE "sects" ( - "sect_id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - "sect_name" TEXT NOT NULL, - "sect_owner" integer, - "sect_scale" integer NOT NULL, - "sect_used_stone" integer, - "sect_fairyland" integer -);""") - elif i == "back": - try: - c.execute(f"select count(1) from {i}") - except sqlite3.OperationalError: - c.execute("""CREATE TABLE "back" ( - "user_id" INTEGER NOT NULL, - "goods_id" INTEGER NOT NULL, - "goods_name" TEXT, - "goods_type" TEXT, - "goods_num" INTEGER, - "create_time" TEXT, - "update_time" TEXT, - "remake" TEXT, - "day_num" INTEGER DEFAULT 0, - "all_num" INTEGER DEFAULT 0, - "action_time" TEXT, - "state" INTEGER DEFAULT 0 -);""") - - elif i == "BuffInfo": - try: - c.execute(f"select count(1) from {i}") - except sqlite3.OperationalError: - c.execute("""CREATE TABLE "BuffInfo" ( - "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - "user_id" integer DEFAULT 0, - "main_buff" integer DEFAULT 0, - "sec_buff" integer DEFAULT 0, - "faqi_buff" integer DEFAULT 0, - "fabao_weapon" integer DEFAULT 0, - "sub_buff" integer DEFAULT 0 -);""") - - for i in XiuConfig().sql_user_xiuxian: try: - c.execute(f"select {i} from user_xiuxian") - except sqlite3.OperationalError: - logger.opt(colors=True).info("sql_user_xiuxian有字段不存在,开始创建\n") - sql = f"ALTER TABLE user_xiuxian ADD COLUMN {i} INTEGER DEFAULT 0;" - logger.opt(colors=True).info(f"{sql}") - c.execute(sql) - - for d in XiuConfig().sql_user_cd: + await conn.execute("SELECT count(1) FROM xiuxian_time LIMIT 1") + except asyncpg.exceptions.UndefinedTableError: + await conn.execute(""" + CREATE TABLE xiuxian_time ( + "id" SERIAL PRIMARY KEY, + "user_id" BIGINT NOT NULL, + "schedule" TEXT DEFAULT NULL, + "schedule_type" SMALLINT DEFAULT 0, + "schedule_create_time" TIMESTAMP DEFAULT NULL, + "last_active_time" TIMESTAMP DEFAULT NULL, + "level_up_time" TIMESTAMP DEFAULT NULL + )""") + + await conn.execute(""" + CREATE INDEX IF NOT EXISTS idx_xiuxian_time_schedule_create_time ON xiuxian_time(schedule_create_time); + CREATE INDEX IF NOT EXISTS idx_xiuxian_time_schedule_type ON xiuxian_time(schedule_type); + CREATE INDEX IF NOT EXISTS idx_xiuxian_time_level_up_time ON xiuxian_time(level_up_time); + """) + logger.opt(colors=True).info("xiuxian_time表及索引创建成功") + try: - c.execute(f"select {d} from user_cd") - except sqlite3.OperationalError: - logger.opt(colors=True).info("sql_user_cd有字段不存在,开始创建") - sql = f"ALTER TABLE user_cd ADD COLUMN {d} INTEGER DEFAULT 0;" - logger.opt(colors=True).info(f"{sql}") - c.execute(sql) - - for s in XiuConfig().sql_sects: + await conn.execute("SELECT count(1) FROM xiuxian_buff LIMIT 1") + except asyncpg.exceptions.UndefinedTableError: + await conn.execute(""" + CREATE TABLE xiuxian_buff ( + "id" SERIAL PRIMARY KEY, + "user_id" BIGINT NOT NULL, + "main_skill" INTEGER DEFAULT 0, + "ultimate_skill" INTEGER DEFAULT 0, + "support_skill" INTEGER DEFAULT 0, + "weapon" INTEGER DEFAULT 0, + "armor" INTEGER DEFAULT 0, + "atk" INTEGER DEFAULT 0, + "blessed_spot" INTEGER DEFAULT 0 + )""") + + await conn.execute(""" + CREATE UNIQUE INDEX IF NOT EXISTS idx_xiuxian_buff_user_id ON xiuxian_buff(user_id); + CREATE INDEX IF NOT EXISTS idx_xiuxian_buff_main_skill ON xiuxian_buff(main_skill); + CREATE INDEX IF NOT EXISTS idx_xiuxian_buff_ultimate_skill ON xiuxian_buff(ultimate_skill); + CREATE INDEX IF NOT EXISTS idx_xiuxian_buff_support_skill ON xiuxian_buff(support_skill); + CREATE INDEX IF NOT EXISTS idx_xiuxian_buff_weapon ON xiuxian_buff(weapon); + CREATE INDEX IF NOT EXISTS idx_xiuxian_buff_armor ON xiuxian_buff(armor); + CREATE INDEX IF NOT EXISTS idx_xiuxian_buff_atk ON xiuxian_buff(atk); + """) + logger.opt(colors=True).info("xiuxian_buff表及索引创建成功") + + try: - c.execute(f"select {s} from sects") - except sqlite3.OperationalError: - logger.opt(colors=True).info("sql_sects有字段不存在,开始创建") - sql = f"ALTER TABLE sects ADD COLUMN {s} INTEGER DEFAULT 0;" - logger.opt(colors=True).info(f"{sql}") - c.execute(sql) - - for m in XiuConfig().sql_buff: + await conn.execute("SELECT count(1) FROM xiuxian_sect LIMIT 1") + except asyncpg.exceptions.UndefinedTableError: + await conn.execute(""" + CREATE TABLE xiuxian_sect ( + "id" SERIAL PRIMARY KEY, + "sect_name" TEXT NOT NULL, + "sect_owner" BIGINT NOT NULL, + "sect_scale" NUMERIC DEFAULT 0, + "sect_stone" NUMERIC DEFAULT 0, + "sect_material" NUMERIC DEFAULT 0, + "sect_main_skill" JSONB DEFAULT '{}'::jsonb, + "sect_ultimate_skill" JSONB DEFAULT '{}'::jsonb, + "sect_elixir_room_level" INTEGER DEFAULT 0 + )""") + + await conn.execute(""" + CREATE INDEX IF NOT EXISTS idx_xiuxian_sect_scale ON xiuxian_sect(sect_scale); + CREATE INDEX IF NOT EXISTS idx_xiuxian_sect_name ON xiuxian_sect(sect_name); + CREATE INDEX IF NOT EXISTS idx_xiuxian_sect_owner ON xiuxian_sect(sect_owner); + """) + logger.opt(colors=True).info("xiuxian_sect表及索引创建成功") + try: - c.execute(f"select {m} from BuffInfo") - except sqlite3.OperationalError: - logger.opt(colors=True).info("sql_buff有字段不存在,开始创建") - sql = f"ALTER TABLE BuffInfo ADD COLUMN {m} INTEGER DEFAULT 0;" - logger.opt(colors=True).info(f"{sql}") - c.execute(sql) - - for b in XiuConfig().sql_back: + await conn.execute("SELECT count(1) FROM xiuxian_sect_task LIMIT 1") + except asyncpg.exceptions.UndefinedTableError: + await conn.execute(""" + CREATE TABLE xiuxian_sect_task ( + "user_id" BIGINT PRIMARY KEY, + "task_name" TEXT NOT NULL, + "task_type" INTEGER NOT NULL, + "task_desc" TEXT NOT NULL, + "task_cost" NUMERIC NOT NULL, + "task_give" NUMERIC NOT NULL, + "task_sect" NUMERIC NOT NULL, + "create_time" TIMESTAMP WITH TIME ZONE DEFAULT NOW() + )""") + + await conn.execute(""" + CREATE INDEX IF NOT EXISTS idx_xiuxian_sect_task_user_id ON xiuxian_sect_task(user_id); + """) + logger.opt(colors=True).info("xiuxian_sect_task表及索引创建成功") + try: - c.execute(f"select {b} from back") - except sqlite3.OperationalError: - logger.opt(colors=True).info("sql_back有字段不存在,开始创建") - sql = f"ALTER TABLE back ADD COLUMN {b} INTEGER DEFAULT 0;" - logger.opt(colors=True).info(f"{sql}") - c.execute(sql) - - # 检查并更新 last_check_info_time 列的记录 - c.execute(f"""UPDATE user_cd -SET last_check_info_time = ? -WHERE last_check_info_time = '0' OR last_check_info_time IS NULL - """, (current_time,)) + await conn.execute("SELECT count(1) FROM xiuxian_work_info LIMIT 1") + except asyncpg.exceptions.UndefinedTableError: + await conn.execute(""" + CREATE TABLE xiuxian_work_info ( + "user_id" BIGINT PRIMARY KEY, + "work_msg" TEXT NOT NULL, + "work_list" JSONB NOT NULL, + "create_time" TIMESTAMP WITH TIME ZONE DEFAULT NOW() + )""") + + await conn.execute(""" + CREATE INDEX IF NOT EXISTS idx_xiuxian_work_info_user_id ON xiuxian_work_info(user_id); + """) + logger.opt(colors=True).info("xiuxian_work_info表及索引创建成功") - self.conn.commit() + + try: + await conn.execute("SELECT count(1) FROM xiuxian_back LIMIT 1") + except asyncpg.exceptions.UndefinedTableError: + await conn.execute(""" + CREATE TABLE xiuxian_back ( + "id" SERIAL PRIMARY KEY, + "user_id" BIGINT NOT NULL, + "goods_id" BIGINT NOT NULL, + "goods_name" TEXT NOT NULL, + "goods_type" TEXT NOT NULL, + "goods_num" NUMERIC DEFAULT 0, + "goods_receive_time" TIMESTAMP DEFAULT NULL, + "goods_update_time" TIMESTAMP DEFAULT NULL, + "goods_day_limit" NUMERIC DEFAULT 0, + "goods_all_limit" NUMERIC DEFAULT 0, + "goods_action_time" TIMESTAMP DEFAULT NULL, + "goods_state" SMALLINT DEFAULT 0, + "goods_bind_num" NUMERIC DEFAULT 0 + )""") + + await conn.execute(""" + CREATE INDEX IF NOT EXISTS idx_xiuxian_back_user_id ON xiuxian_back(user_id); + CREATE INDEX IF NOT EXISTS idx_xiuxian_back_goods_id ON xiuxian_back(goods_id); + CREATE INDEX IF NOT EXISTS idx_xiuxian_back_user_goods ON xiuxian_back(user_id, goods_id); + CREATE INDEX IF NOT EXISTS idx_xiuxian_back_goods_type ON xiuxian_back(goods_type); + CREATE INDEX IF NOT EXISTS idx_xiuxian_back_goods_receive_time ON xiuxian_back(goods_receive_time); + CREATE INDEX IF NOT EXISTS idx_xiuxian_back_goods_update_time ON xiuxian_back(goods_update_time); + """) + logger.opt(colors=True).info("xiuxian_back表及索引创建成功") + + try: + await conn.execute("SELECT count(1) FROM xiuxian_impart LIMIT 1") + except asyncpg.exceptions.UndefinedTableError: + await conn.execute(""" + CREATE TABLE xiuxian_impart ( + "id" SERIAL PRIMARY KEY, + "user_id" BIGINT NOT NULL, + "impart_hp_addition" NUMERIC DEFAULT 0, + "impart_atk_addition" NUMERIC DEFAULT 0, + "impart_mp_addition" NUMERIC DEFAULT 0, + "impart_exp_addition" NUMERIC DEFAULT 0, + "impart_boss_atk_addition" NUMERIC DEFAULT 0, + "impart_crit_addition" NUMERIC DEFAULT 0, + "impart_crit_dmg_addition" NUMERIC DEFAULT 0, + "impart_mix_addition" NUMERIC DEFAULT 0, + "impart_reap_addition" NUMERIC DEFAULT 0, + "impart_two_exp_quantity" NUMERIC DEFAULT 0, + "impart_all_exp_quantity" NUMERIC DEFAULT 0, + "impart_wish_quantity" SMALLINT DEFAULT 0, + "impart_stone_quantity" NUMERIC DEFAULT 0, + "impart_exp_day_quantity" NUMERIC DEFAULT 0 + )""") + + await conn.execute(""" + CREATE INDEX IF NOT EXISTS idx_xiuxian_impart_user_id ON xiuxian_impart(user_id); + """) + logger.opt(colors=True).info("xiuxian_impart表及索引创建成功") + try: + await conn.execute(""" + UPDATE xiuxian_time + SET last_active_time = $1 + WHERE last_active_time IS NULL + """, current_time) + except asyncpg.exceptions.UndefinedTableError: + pass + + async def _create_user(self, user_id: int, root: str, type: str, power: str, user_create_time: str, user_name: str) -> None: + """在数据库中创建用户并初始化""" + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = """ + INSERT INTO xiuxian_user + (user_id, stone, root, root_type, level, power, user_create_time, user_name, exp, sect_id, sect_position, stamina) + VALUES ($1, 0, $2, $3, '江湖好手', $4, $5, $6, 100, NULL, NULL, $7) + """ + await conn.execute(sql, user_id, root, type, power, user_create_time, user_name, XiuConfig().max_stamina) - @classmethod - def close_dbs(cls): - XiuxianDateManage().close() - def _create_user(self, user_id: str, root: str, type: str, power: str, create_time, user_name) -> None: - """在数据库中创建用户并初始化""" - c = self.conn.cursor() - sql = f"INSERT INTO user_xiuxian (user_id,stone,root,root_type,level,power,create_time,user_name,exp,sect_id,sect_position,user_stamina) VALUES (?,0,?,?,'江湖好手',?,?,?,100,NULL,NULL,?)" - c.execute(sql, (user_id, root, type, power, create_time, user_name,XiuConfig().max_stamina)) - self.conn.commit() - - def get_user_info_with_id(self, user_id): - """根据USER_ID获取用户信息,不获取功法加成""" - cur = self.conn.cursor() - sql = f"select * from user_xiuxian WHERE user_id=?" - cur.execute(sql, (user_id,)) - result = cur.fetchone() - if result: - columns = [column[0] for column in cur.description] - user_dict = dict(zip(columns, result)) - return user_dict - else: - return None - - def get_user_info_with_name(self, user_id): + async def get_user_info_with_name(self, user_name: str): """根据user_name获取用户信息""" - cur = self.conn.cursor() - sql = f"select * from user_xiuxian WHERE user_name=?" - cur.execute(sql, (user_id,)) - result = cur.fetchone() - if result: - columns = [column[0] for column in cur.description] - user_dict = dict(zip(columns, result)) - return user_dict - else: - return None + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT * FROM xiuxian_user WHERE user_name = $1" + result = await conn.fetchrow(sql, user_name) + if result: + return dict(result) + else: + return None - def update_all_users_stamina(self, max_stamina, stamina): - """体力未满用户更新体力值""" - cur = self.conn.cursor() - sql = f""" - UPDATE user_xiuxian - SET user_stamina = MIN(user_stamina + ?, ?) - WHERE user_stamina < ? - """ - cur.execute(sql, (stamina, max_stamina, max_stamina)) - self.conn.commit() - - def update_user_stamina(self, user_id, stamina_change, key): - """更新用户体力值 1为增加,2为减少""" - cur = self.conn.cursor() - - if key == 1: - sql = f"UPDATE user_xiuxian SET user_stamina=user_stamina+? WHERE user_id=?" - cur.execute(sql, (stamina_change, user_id)) - self.conn.commit() - elif key == 2: - sql = f"UPDATE user_xiuxian SET user_stamina=user_stamina-? WHERE user_id=?" - cur.execute(sql, (stamina_change, user_id)) - self.conn.commit() - - def get_user_real_info(self, user_id): + async def update_all_users_stamina(self, max_stamina: int, stamina: int): + """更新所有用户体力""" + await self.ensure_pool() + async with self.pool.acquire() as conn: + async with conn.transaction(): + await conn.execute( + f"UPDATE xiuxian_user SET stamina = LEAST(stamina + {stamina}, {max_stamina})" + ) + logger.opt(colors=True).info(f"已为所有用户恢复体力:+{stamina},最大值:{max_stamina}") + + async def update_user_stamina(self, user_id: int, stamina_change: int, key: int): + """更新用户体力值 0为增加,1为减少""" + await self.ensure_pool() + async with self.pool.acquire() as conn: + if key == 0: + sql = "UPDATE xiuxian_user SET stamina = stamina + $1 WHERE user_id = $2" + await conn.execute(sql, stamina_change, user_id) + elif key == 1: + sql = "UPDATE xiuxian_user SET stamina = stamina - $1 WHERE user_id = $2" + await conn.execute(sql, stamina_change, user_id) + + async def get_user_real_info(self, user_id: int): """根据USER_ID获取用户信息,获取功法加成""" - cur = self.conn.cursor() - sql = f"select * from user_xiuxian WHERE user_id=?" - cur.execute(sql, (user_id,)) - result = cur.fetchone() - if result: - columns = cur.description - user_data_dict = final_user_data(result, columns) - return user_data_dict - else: - return None + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT * FROM xiuxian_user WHERE user_id = $1" + result = await conn.fetchrow(sql, int(user_id)) + if result: + user_dict = dict(result) + user_data_dict = await final_user_data(user_dict, None) + return user_data_dict + else: + return None - def get_sect_info(self, sect_id): + async def get_sect_info(self, sect_id: int): """ 通过宗门编号获取宗门信息 :param sect_id: 宗门编号 :return: """ - cur = self.conn.cursor() - sql = f"select * from sects WHERE sect_id=?" - cur.execute(sql, (sect_id,)) - result = cur.fetchone() - if result: - sect_id_dict = dict(zip((col[0] for col in cur.description), result)) - return sect_id_dict - else: - return None + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT * from xiuxian_sect WHERE id = $1" + result = await conn.fetchrow(sql, sect_id) + if result: + return dict(result) + else: + return None - def get_sect_owners(self): + async def get_sect_owners(self): """获取所有宗主的 user_id""" - cur = self.conn.cursor() - sql = f"SELECT user_id FROM user_xiuxian WHERE sect_position = 0" - cur.execute(sql) - result = cur.fetchall() - return [row[0] for row in result] + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT user_id FROM xiuxian_user WHERE sect_position = 0" + result = await conn.fetch(sql) + return [row[0] for row in result] - def get_elders(self): - """获取所有长老的 user_id""" - cur = self.conn.cursor() - sql = f"SELECT user_id FROM user_xiuxian WHERE sect_position = 1" - cur.execute(sql) - result = cur.fetchall() - return [row[0] for row in result] - - def create_user(self, user_id, *args): + + async def get_elders(self): + """获取所有长老的user_id""" + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT user_id FROM xiuxian_user WHERE sect_position = 1" + result = await conn.fetch(sql) + return [row[0] for row in result] + + async def create_user(self, user_id: int, *args: str): """校验用户是否存在""" - cur = self.conn.cursor() - sql = f"select * from user_xiuxian WHERE user_id=?" - cur.execute(sql, (user_id,)) - result = cur.fetchone() - if not result: - self._create_user(user_id, args[0], args[1], args[2], args[3], args[4]) # root, type, power, create_time, user_name - self.conn.commit() - welcome_msg = f"欢迎进入修仙世界的,你的灵根为:{args[0]},类型是:{args[1]},你的战力为:{args[2]},当前境界:江湖好手" - return True, welcome_msg - else: - return False, f"您已迈入修仙世界,输入【我的修仙信息】获取数据吧!" + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT * FROM xiuxian_user WHERE user_id = $1" + result = await conn.fetchrow(sql, int(user_id)) + if not result: + await self._create_user(user_id, args[0], args[1], args[2], args[3], args[4]) # root, type, power, create_time, user_name + welcome_msg = f"欢迎进入修仙世界的,你的灵根为:{args[0]},类型是:{args[1]},你的战力为:{args[2]},当前境界:江湖好手" + return True, welcome_msg + else: + return False, "您已经迈入修仙世界\n输入【我的修仙信息】获取数据吧!" - def get_sign(self, user_id): + async def get_sign(self, user_id: int): """获取用户签到信息""" - cur = self.conn.cursor() - sql = "select is_sign from user_xiuxian WHERE user_id=?" - cur.execute(sql, (user_id,)) - result = cur.fetchone() - if not result: - return f"修仙界没有你的足迹,输入 我要修仙 加入修仙世界吧!" - elif result[0] == 0: - ls = random.randint(XiuConfig().sign_in_lingshi_lower_limit, XiuConfig().sign_in_lingshi_upper_limit) - sql2 = f"UPDATE user_xiuxian SET is_sign=1,stone=stone+? WHERE user_id=?" - cur.execute(sql2, (ls,user_id)) - self.conn.commit() - return f"签到成功,获取{ls}块灵石!" - elif result[0] == 1: - return f"贪心的人是不会有好运的!" - - def get_beg(self, user_id): + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT is_sign FROM xiuxian_user WHERE user_id = $1" + result = await conn.fetchval(sql, int(user_id)) + if result is None: + return "修仙界没有你的足迹,输入 我要修仙 加入修仙世界吧!" + elif result == 0: + ls = random.randint(XiuConfig().sign_in_lingshi_lower_limit, XiuConfig().sign_in_lingshi_upper_limit) + sql2 = "UPDATE xiuxian_user SET is_sign = 1, stone = stone + $1 WHERE user_id = $2" + await conn.execute(sql2, ls, user_id) + + return f"签到成功,获取{ls}块灵石!" + elif result == 1: + return "贪心的人是不会有好运的!" + + async def get_beg(self, user_id: int): """获取仙途奇缘信息""" - cur = self.conn.cursor() - sql = f"select is_beg from user_xiuxian WHERE user_id=?" - cur.execute(sql, (user_id,)) - result = cur.fetchone() - if result[0] == 0: - ls = random.randint(XiuConfig().beg_lingshi_lower_limit, XiuConfig().beg_lingshi_upper_limit) - sql2 = f"UPDATE user_xiuxian SET is_beg=1,stone=stone+? WHERE user_id=?" - cur.execute(sql2, (ls,user_id)) - self.conn.commit() - return ls - elif result[0] == 1: - return None - - def ramaker(self, lg, type, user_id): + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT is_beg FROM xiuxian_user WHERE user_id = $1" + is_beg = await conn.fetchval(sql, int(user_id)) + if is_beg == 0: + ls = random.randint(XiuConfig().beg_lingshi_lower_limit, XiuConfig().beg_lingshi_upper_limit) + sql2 = "UPDATE xiuxian_user SET is_beg = 1, stone = stone + $1 WHERE user_id = $2" + await conn.execute(sql2, ls, user_id) + + return ls + elif is_beg == 1: + return None + + async def ramaker(self, lg: str, type: str, user_id: int): """洗灵根""" - cur = self.conn.cursor() - sql = f"UPDATE user_xiuxian SET root=?,root_type=?,stone=stone-? WHERE user_id=?" - cur.execute(sql, (lg, type, XiuConfig().remake, user_id)) - self.conn.commit() - - self.update_power2(user_id) # 更新战力 - return f"逆天之行,重获新生,新的灵根为:{lg},类型为:{type}" - - def get_root_rate(self, name): + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "UPDATE xiuxian_user SET root = $1, root_type = $2, stone = stone - $3 WHERE user_id = $4" + await conn.execute(sql, lg, type, XiuConfig().remake, user_id) + await self.update_power2(user_id) + return f"逆天之行,重获新生,新的灵根为:{lg},类型为:{type}" + + async def get_root_rate(self, name: str): """获取灵根倍率""" + await self.ensure_pool() data = jsondata.root_data() return data[name]['type_speeds'] - def get_level_power(self, name): + async def get_level_power(self, name: str): """获取境界倍率|exp""" + await self.ensure_pool() data = jsondata.level_data() return data[name]['power'] - def get_level_cost(self, name): + async def get_level_cost(self, name: str): """获取炼体境界倍率""" + await self.ensure_pool() data = jsondata.exercises_level_data() return data[name]['cost_exp'], data[name]['cost_stone'] - def update_power2(self, user_id) -> None: + async def update_power2(self, user_id: int) -> None: """更新战力""" - UserMessage = self.get_user_info_with_id(user_id) - cur = self.conn.cursor() - level = jsondata.level_data() - root = jsondata.root_data() - sql = f"UPDATE user_xiuxian SET power=round(exp*?*?,0) WHERE user_id=?" - cur.execute(sql, (root[UserMessage['root_type']]["type_speeds"], level[UserMessage['level']]["spend"], user_id)) - self.conn.commit() - - def update_ls(self, user_id, price, key): - """更新灵石 1为增加,2为减少""" - cur = self.conn.cursor() - - if key == 1: - sql = f"UPDATE user_xiuxian SET stone=stone+? WHERE user_id=?" - cur.execute(sql, (price, user_id)) - self.conn.commit() - elif key == 2: - sql = f"UPDATE user_xiuxian SET stone=stone-? WHERE user_id=?" - cur.execute(sql, (price, user_id)) - self.conn.commit() - - def update_root(self, user_id, key): + await self.ensure_pool() + UserMessage = await self.get_user_infos_by_ids(user_id) + if not UserMessage: + return + + async with self.pool.acquire() as conn: + level = jsondata.level_data() + power = int(level[UserMessage['level']]['power']) * float(await self.get_root_rate(UserMessage['root_type'])) + sql = "UPDATE xiuxian_user SET power = $1 WHERE user_id = $2" + await conn.execute(sql, int(power), user_id) + + async def update_ls(self, user_id: int, price: int, key: int): + """更新灵石 0为增加,1为减少""" + price = int(price) + await self.ensure_pool() + async with self.pool.acquire() as conn: + if key == 0: + sql = "UPDATE xiuxian_user SET stone = stone + $1 WHERE user_id = $2" + elif key == 1: + sql = "UPDATE xiuxian_user SET stone = stone - $1 WHERE user_id = $2" + + await conn.execute(sql, price, user_id) + + async def update_root(self, user_id: int, key: int): """更新灵根 1为混沌,2为融合,3为超,4为龙,5为天,6为千世,7为万世""" - cur = self.conn.cursor() - if int(key) == 1: - sql = f"UPDATE user_xiuxian SET root=?,root_type=? WHERE user_id=?" - cur.execute(sql, ("全属性灵根", "混沌灵根", user_id)) - root_name = "混沌灵根" - self.conn.commit() - - elif int(key) == 2: - sql = f"UPDATE user_xiuxian SET root=?,root_type=? WHERE user_id=?" - cur.execute(sql, ("融合万物灵根", "融合灵根", user_id)) - root_name = "融合灵根" - self.conn.commit() - - elif int(key) == 3: - sql = f"UPDATE user_xiuxian SET root=?,root_type=? WHERE user_id=?" - cur.execute(sql, ("月灵根", "超灵根", user_id)) - root_name = "超灵根" - self.conn.commit() - - elif int(key) == 4: - sql = f"UPDATE user_xiuxian SET root=?,root_type=? WHERE user_id=?" - cur.execute(sql, ("言灵灵根", "龙灵根", user_id)) - root_name = "龙灵根" - self.conn.commit() - - elif int(key) == 5: - sql = f"UPDATE user_xiuxian SET root=?,root_type=? WHERE user_id=?" - cur.execute(sql, ("金灵根", "天灵根", user_id)) - root_name = "天灵根" - self.conn.commit() - - elif int(key) == 6: - sql = f"UPDATE user_xiuxian SET root=?,root_type=? WHERE user_id=?" - cur.execute(sql, ("轮回千次不灭,只为臻至巅峰", "轮回道果", user_id)) - root_name = "轮回道果" - self.conn.commit() - - elif int(key) == 7: - sql = f"UPDATE user_xiuxian SET root=?,root_type=? WHERE user_id=?" - cur.execute(sql, ("轮回万次不灭,只为超越巅峰", "真·轮回道果", user_id)) - root_name = "真·轮回道果" - self.conn.commit() - - return root_name # 返回灵根名称 - - def update_ls_all(self, price): + await self.ensure_pool() + async with self.pool.acquire() as conn: + if int(key) == 1: + sql = "UPDATE xiuxian_user SET root = $1, root_type = $2 WHERE user_id = $3" + await conn.execute(sql, "全属性灵根", "混沌灵根", user_id) + root_name = "混沌灵根" + + + elif int(key) == 2: + sql = "UPDATE xiuxian_user SET root = $1, root_type = $2 WHERE user_id = $3" + await conn.execute(sql, "融合万物灵根", "融合灵根", user_id) + root_name = "融合灵根" + + + elif int(key) == 3: + sql = "UPDATE xiuxian_user SET root = $1, root_type = $2 WHERE user_id = $3" + await conn.execute(sql, "月灵根", "超灵根", user_id) + root_name = "超灵根" + + + elif int(key) == 4: + sql = "UPDATE xiuxian_user SET root = $1, root_type = $2 WHERE user_id = $3" + await conn.execute(sql, "言灵灵根", "龙灵根", user_id) + root_name = "龙灵根" + + + elif int(key) == 5: + sql = "UPDATE xiuxian_user SET root = $1, root_type = $2 WHERE user_id = $3" + await conn.execute(sql, "金灵根", "天灵根", user_id) + root_name = "天灵根" + + + elif int(key) == 6: + sql = "UPDATE xiuxian_user SET root = $1, root_type = $2 WHERE user_id = $3" + await conn.execute(sql, "轮回千次不灭,只为臻至巅峰", "轮回道果", user_id) + root_name = "轮回道果" + + + elif int(key) == 7: + sql = "UPDATE xiuxian_user SET root = $1, root_type = $2 WHERE user_id = $3" + await conn.execute(sql, "轮回万次不灭,只为超越巅峰", "真·轮回道果", user_id) + root_name = "真·轮回道果" + + + return root_name + + async def update_ls_all(self, price: int): """所有用户增加灵石""" - cur = self.conn.cursor() - sql = f"UPDATE user_xiuxian SET stone=stone+?" - cur.execute(sql, (price,)) - self.conn.commit() + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "UPDATE xiuxian_user SET stone = stone + $1" + await conn.execute(sql, price) + - def get_exp_rank(self, user_id): + async def get_exp_rank(self, user_id: int): """修为排行""" - sql = f"select rank from(select user_id,exp,dense_rank() over (ORDER BY exp desc) as 'rank' FROM user_xiuxian) WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (user_id,)) - result = cur.fetchone() - return result + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT rank from(SELECT user_id,exp,dense_rank() over (ORDER BY exp desc) as rank FROM xiuxian_user) WHERE user_id = $1" + rank = await conn.fetchval(sql, int(user_id)) + return rank - def get_stone_rank(self, user_id): + async def get_stone_rank(self, user_id: int): """灵石排行""" - sql = f"select rank from(select user_id,stone,dense_rank() over (ORDER BY stone desc) as 'rank' FROM user_xiuxian) WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (user_id,)) - result = cur.fetchone() - return result + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT rank from(SELECT user_id,stone,dense_rank() over (ORDER BY stone desc) as rank FROM xiuxian_user) WHERE user_id = $1" + rank = await conn.fetchval(sql, int(user_id)) + return rank - def get_ls_rank(self): + async def get_ls_rank(self): """灵石排行榜""" - sql = f"SELECT user_id,stone FROM user_xiuxian WHERE stone>0 ORDER BY stone DESC LIMIT 5" - cur = self.conn.cursor() - cur.execute(sql, ) - result = cur.fetchall() - return result + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT user_id,stone FROM xiuxian_user WHERE stone > 0 ORDER BY stone DESC LIMIT 5" + result = await conn.fetch(sql, ) + return result - def sign_remake(self): + async def sign_remake(self): """重置签到""" - sql = f"UPDATE user_xiuxian SET is_sign=0" - cur = self.conn.cursor() - cur.execute(sql, ) - self.conn.commit() + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "UPDATE xiuxian_user SET is_sign = 0" + await conn.execute(sql, ) + - def beg_remake(self): + async def beg_remake(self): """重置仙途奇缘""" - sql = f"UPDATE user_xiuxian SET is_beg=0" - cur = self.conn.cursor() - cur.execute(sql, ) - self.conn.commit() + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "UPDATE xiuxian_user SET is_beg = 0" + await conn.execute(sql, ) + - def ban_user(self, user_id): + async def ban_user(self, user_id: int): """小黑屋""" - sql = f"UPDATE user_xiuxian SET is_ban=1 WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (user_id,)) - self.conn.commit() + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "UPDATE xiuxian_user SET is_ban = 1 WHERE user_id = $1" + await conn.execute(sql, int(user_id)) + - def update_user_name(self, user_id, user_name): + async def update_user_name(self, user_id: int, user_name: str): """更新用户道号""" - cur = self.conn.cursor() - get_name = f"select user_name from user_xiuxian WHERE user_name=?" - cur.execute(get_name, (user_name,)) - result = cur.fetchone() - if result: - return "已存在该道号!" - else: - sql = f"UPDATE user_xiuxian SET user_name=? WHERE user_id=?" - - cur.execute(sql, (user_name, user_id)) - self.conn.commit() - return '道友的道号更新成功拉~' + await self.ensure_pool() + async with self.pool.acquire() as conn: + get_name = "SELECT user_name FROM xiuxian_user WHERE user_name = $1" + result = await conn.fetchval(get_name, user_name) + if result: + return "已存在该道号!" + else: + sql = "UPDATE xiuxian_user SET user_name = $1 WHERE user_id = $2" + await conn.execute(sql, user_name, user_id) + + return '道友的道号更新成功拉~' - def updata_level_cd(self, user_id): + async def updata_level_cd(self, user_id: int): """更新突破境界CD""" - sql = f"UPDATE user_xiuxian SET level_up_cd=? WHERE user_id=?" - cur = self.conn.cursor() - now_time = datetime.now() - cur.execute(sql, (now_time, user_id)) - self.conn.commit() + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "UPDATE xiuxian_time SET level_up_time = $1 WHERE user_id = $2" + await conn.execute(sql, datetime.now(), user_id) + - def update_last_check_info_time(self, user_id): + async def update_last_check_info_time(self, user_id: int): """更新查看修仙信息时间""" - sql = "UPDATE user_cd SET last_check_info_time = ? WHERE user_id = ?" - cur = self.conn.cursor() - now_time = datetime.now() - cur.execute(sql, (now_time, user_id)) - self.conn.commit() + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "UPDATE xiuxian_time SET last_active_time = $1 WHERE user_id = $2" + await conn.execute(sql, datetime.now(), user_id) + - def get_last_check_info_time(self, user_id): + async def get_last_check_info_time(self, user_id: int): """获取最后一次查看修仙信息时间""" - cur = self.conn.cursor() - sql = "SELECT last_check_info_time FROM user_cd WHERE user_id = ?" - cur.execute(sql, (user_id,)) - result = cur.fetchone() - if result: - return datetime.strptime(result[0], '%Y-%m-%d %H:%M:%S.%f') - else: - return None - - - def updata_level(self, user_id, level_name): + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT last_active_time FROM xiuxian_time WHERE user_id = $1" + time_str = await conn.fetchval(sql, int(user_id)) + if time_str: + if isinstance(time_str, datetime): + return time_str + else: + return datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S.%') + else: + return None + + + async def updata_level(self, user_id: int, level_name: str): """更新境界""" - sql = f"UPDATE user_xiuxian SET level=? WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (level_name, user_id)) - self.conn.commit() + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "UPDATE xiuxian_user SET level = $1 WHERE user_id = $2" + await conn.execute(sql, level_name, user_id) + - def get_user_cd(self, user_id): + async def get_user_time(self, user_id: int): """ 获取用户操作CD :param user_id: QQ :return: 用户CD信息的字典 """ - sql = f"SELECT * FROM user_cd WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (user_id,)) - result = cur.fetchone() - if result: - columns = [column[0] for column in cur.description] - user_cd_dict = dict(zip(columns, result)) - return user_cd_dict - else: - self.insert_user_cd(user_id) - return None + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT * FROM xiuxian_time WHERE user_id = $1" + result = await conn.fetchrow(sql, int(user_id)) + if result: + return dict(result) + else: + await self.insert_user_cd(user_id) + return None - def insert_user_cd(self, user_id) -> None: + async def insert_user_cd(self, user_id: int) -> None: """ 添加用户至CD表 :param user_id: qq :return: """ - sql = f"INSERT INTO user_cd (user_id) VALUES (?)" - cur = self.conn.cursor() - cur.execute(sql, (user_id,)) - self.conn.commit() + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "INSERT INTO xiuxian_time (user_id) VALUES ($1)" + await conn.execute(sql, int(user_id)) + - def create_sect(self, user_id, sect_name) -> None: + async def create_sect(self, user_id: int, sect_name: str) -> None: """ 创建宗门 :param user_id:qq :param sect_name:宗门名称 :return: """ - sql = f"INSERT INTO sects(sect_name, sect_owner, sect_scale, sect_used_stone) VALUES (?,?,0,0)" - cur = self.conn.cursor() - cur.execute(sql, (sect_name, user_id)) - self.conn.commit() + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "INSERT INTO xiuxian_sect(sect_name, sect_owner, sect_scale, sect_stone) VALUES ($1,$2,0,0)" + await conn.execute(sql, sect_name, user_id) + - def update_sect_name(self, sect_id, sect_name) -> None: + async def update_sect_name(self, sect_id: int, sect_name: str) -> None: """ 修改宗门名称 :param sect_id: 宗门id :param sect_name: 宗门名称 :return: 返回是否更新成功的标志,True表示更新成功,False表示更新失败(已存在同名宗门) """ - cur = self.conn.cursor() - get_sect_name = f"select sect_name from sects WHERE sect_name=?" - cur.execute(get_sect_name, (sect_name,)) - result = cur.fetchone() - if result: - return False - else: - sql = f"UPDATE sects SET sect_name=? WHERE sect_id=?" - cur = self.conn.cursor() - cur.execute(sql, (sect_name, sect_id)) - self.conn.commit() - return True + await self.ensure_pool() + async with self.pool.acquire() as conn: + get_sect_name = "SELECT sect_name from xiuxian_sect WHERE sect_name = $1" + result = await conn.fetchrow(get_sect_name, sect_name) + if result: + return False + else: + sql = "UPDATE xiuxian_sect SET sect_name = $1 WHERE id = $2" + await conn.execute(sql, sect_name, sect_id) + + return True - def get_sect_info_by_qq(self, user_id): + async def get_sect_info_by_qq(self, user_id: int): """ - 通过用户qq获取宗门信息 + 通过用户id获取所在宗门信息 :param user_id: :return: """ - cur = self.conn.cursor() - sql = f"select * from sects WHERE sect_owner=?" - cur.execute(sql, (user_id,)) - result = cur.fetchone() - if result: - columns = [column[0] for column in cur.description] - sect_onwer_dict = dict(zip(columns, result)) - return sect_onwer_dict - else: - return None + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT * from xiuxian_sect WHERE sect_owner = $1" + result = await conn.fetchrow(sql, int(user_id)) + if result: + return dict(result) + else: + return None - def get_sect_info_by_id(self, sect_id): + async def get_sect_info_by_id(self, sect_id: int): """ 通过宗门id获取宗门信息 :param sect_id: :return: """ - cur = self.conn.cursor() - sql = f"select * from sects WHERE sect_id=?" - cur.execute(sql, (sect_id,)) - result = cur.fetchone() - if result: - columns = [column[0] for column in cur.description] - sect_dict = dict(zip(columns, result)) - return sect_dict - else: - return None + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT * from xiuxian_sect WHERE id = $1" + result = await conn.fetchrow(sql, sect_id) + if result: + return dict(result) + else: + return None - def update_usr_sect(self, user_id, usr_sect_id, usr_sect_position): + async def update_ussr_sect_info(self, user_id: int, usr_sect_id: int, usr_sect_position: int): """ 更新用户信息表的宗门信息字段 :param user_id: @@ -646,116 +865,141 @@ def update_usr_sect(self, user_id, usr_sect_id, usr_sect_position): :param usr_sect_position: :return: """ - sql = f"UPDATE user_xiuxian SET sect_id=?,sect_position=? WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (usr_sect_id, usr_sect_position, user_id)) - self.conn.commit() + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "UPDATE xiuxian_user SET sect_id = $1,sect_position = $2 WHERE user_id = $3" + await conn.execute(sql, usr_sect_id, usr_sect_position, user_id) + - def update_sect_owner(self, user_id, sect_id): + async def update_sect_owner(self, user_id: int, sect_id: int): """ 更新宗门所有者 :param user_id: :param usr_sect_id: :return: """ - sql = f"UPDATE sects SET sect_owner=? WHERE sect_id=?" - cur = self.conn.cursor() - cur.execute(sql, (user_id, sect_id)) - self.conn.commit() + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "UPDATE xiuxian_sect SET sect_owner = $1 WHERE id = $2" + await conn.execute(sql, user_id, sect_id) + - def get_highest_contrib_user_except_current(self, sect_id, current_owner_id): + async def get_highest_contrib_user_except_current(self, sect_id: int, current_owner_id: int): """ 获取指定宗门的贡献最高的人,排除当前宗主 :param sect_id: 宗门ID :param current_owner_id: 当前宗主的ID :return: 贡献最高的人的ID,如果没有则返回None """ - cur = self.conn.cursor() - sql = """ - SELECT user_id - FROM user_xiuxian - WHERE sect_id = ? AND sect_position = 1 AND user_id != ? - ORDER BY sect_contribution DESC - LIMIT 1 - """ - cur.execute(sql, (sect_id, current_owner_id)) - result = cur.fetchone() - if result: + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = """ + SELECT user_id + FROM xiuxian_user + WHERE sect_id = $1 AND sect_position = 1 AND user_id != $2 + ORDER BY sect_contribution DESC + LIMIT 1 + """ + result = await conn.fetchval(sql, sect_id, current_owner_id) + return result + + async def get_highest_contrib_active_user_except_current(self, sect_id: int, current_owner_id: int): + """ + 获取指定宗门的贡献最高且最近7天内活跃的成员,排除当前宗主 + :param sect_id: 宗门ID + :param current_owner_id: 当前宗主的ID + :return: 贡献最高且活跃的成员ID,如果没有则返回None + """ + await self.ensure_pool() + async with self.pool.acquire() as conn: + days_ago = datetime.now() - timedelta(days=XiuConfig().auto_change_sect_owner_cd) + + sql = """ + SELECT u.user_id + FROM xiuxian_user u + JOIN xiuxian_time c ON u.user_id = c.user_id + WHERE u.id = $1 + AND u.sect_position = 1 + AND u.user_id != $2 + AND c.last_active_time > $3 + ORDER BY u.sect_contribution DESC + LIMIT 1 + """ + result = await conn.fetchval(sql, sect_id, current_owner_id, days_ago) return result - else: - return None - def get_all_sect_id(self): + async def get_all_sect_id(self): """获取全部宗门id""" - sql = "SELECT sect_id FROM sects" - cur = self.conn.cursor() - cur.execute(sql, ) - result = cur.fetchall() - if result: - return result - else: - return None + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT id FROM xiuxian_sect" + result = await conn.fetch(sql) + if result: + return result + else: + return None - def get_all_user_id(self): + async def get_all_user_id(self): """获取全部用户id""" - sql = "SELECT user_id FROM user_xiuxian" - cur = self.conn.cursor() - cur.execute(sql, ) - result = cur.fetchall() - if result: - return [row[0] for row in result] - else: - return None + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT user_id FROM xiuxian_user" + result = await conn.fetch(sql) + if result: + return [row[0] for row in result] + else: + return None - def in_closing(self, user_id, the_type): + async def in_closing(self, user_id: int, the_type: int): """ 更新用户操作CD :param user_id: qq :param the_type: 0:无状态 1:闭关中 2:历练中 :return: """ + await self.ensure_pool() now_time = None if the_type == 1: now_time = datetime.now() elif the_type == 0: - now_time = 0 + now_time = None elif the_type == 2: now_time = datetime.now() - sql = "UPDATE user_cd SET type=?,create_time=? WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (the_type, now_time, user_id)) - self.conn.commit() - - - def update_exp(self, user_id, exp): - """增加修为""" - sql = "UPDATE user_xiuxian SET exp=exp+? WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (int(exp), user_id)) - self.conn.commit() - - def update_j_exp(self, user_id, exp): - """减少修为""" - sql = "UPDATE user_xiuxian SET exp=exp-? WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (int(exp), user_id)) - self.conn.commit() - - def del_exp_decimal(self, user_id, exp): + async with self.pool.acquire() as conn: + sql = "UPDATE xiuxian_time SET schedule_type = $1, schedule_create_time = $2 WHERE user_id = $3" + await conn.execute(sql, the_type, now_time, user_id) + + + + async def update_exp(self, user_id: int, exp: int, key: int): + """更新修为,key=0增加修为,key=1减少修为""" + await self.ensure_pool() + async with self.pool.acquire() as conn: + if key == 0: + sql = "UPDATE xiuxian_user SET exp = exp + $1 WHERE user_id = $2" + elif key == 1: + sql = "UPDATE xiuxian_user SET exp = exp - $1 WHERE user_id = $2" + await conn.execute(sql, int(exp), user_id) + + + + async def del_exp_decimal(self, user_id: int, exp: float): """去浮点""" - sql = "UPDATE user_xiuxian SET exp=? WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (int(exp), user_id)) - self.conn.commit() + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "UPDATE xiuxian_user SET exp = exp - $1 WHERE user_id = $2" + await conn.execute(sql, int(exp), user_id) + - def realm_top(self): + async def realm_top(self): """境界排行榜前50""" + await self.ensure_pool() rank_mapping = {rank: idx for idx, rank in enumerate(convert_rank('江湖好手')[1])} - - sql = """SELECT user_name, level, exp FROM user_xiuxian + + sql = """SELECT user_name, level, exp FROM xiuxian_user WHERE user_name IS NOT NULL ORDER BY exp DESC, (CASE level """ @@ -764,105 +1008,111 @@ def realm_top(self): sql += """ELSE level END) ASC LIMIT 50""" - cur = self.conn.cursor() - cur.execute(sql, ) - result = cur.fetchall() - return result + async with self.pool.acquire() as conn: + result = await conn.fetch(sql) + return result - def stone_top(self): + async def stone_top(self): """这也是灵石排行榜""" - sql = f"SELECT user_name,stone FROM user_xiuxian WHERE user_name is NOT NULL ORDER BY stone DESC LIMIT 50" - cur = self.conn.cursor() - cur.execute(sql, ) - result = cur.fetchall() - return result - - def power_top(self): + await self.ensure_pool() + try: + sql = "SELECT user_name, stone FROM xiuxian_user WHERE user_name is NOT NULL ORDER BY stone DESC LIMIT 50" + async with self.pool.acquire() as conn: + result = await conn.fetch(sql) + return result + except ImportError: + async with self.pool.acquire() as conn: + sql = "SELECT user_name, stone FROM xiuxian_user WHERE user_name is NOT NULL ORDER BY stone DESC LIMIT 50" + result = await conn.fetch(sql) + return result + + async def power_top(self): """战力排行榜""" - sql = f"SELECT user_name,power FROM user_xiuxian WHERE user_name is NOT NULL ORDER BY power DESC LIMIT 50" - cur = self.conn.cursor() - cur.execute(sql, ) - result = cur.fetchall() - return result + await self.ensure_pool() + sql = "SELECT user_name,power FROM xiuxian_user WHERE user_name is NOT NULL ORDER BY power DESC LIMIT 50" + async with self.pool.acquire() as conn: + result = await conn.fetch(sql) + return result - def scale_top(self): + async def scale_top(self): """ 宗门建设度排行榜 :return: """ - sql = f"SELECT sect_id, sect_name, sect_scale FROM sects WHERE sect_owner is NOT NULL ORDER BY sect_scale DESC" - cur = self.conn.cursor() - cur.execute(sql, ) - result = cur.fetchall() - return result + await self.ensure_pool() + sql = "SELECT id, sect_name, sect_scale FROM xiuxian_sect WHERE sect_owner is NOT NULL ORDER BY sect_scale DESC" + async with self.pool.acquire() as conn: + result = await conn.fetch(sql) + return result - def get_all_sects(self): + async def get_all_sects(self): """ 获取所有宗门信息 :return: 宗门信息字典列表 """ - sql = f"SELECT * FROM sects WHERE sect_owner is NOT NULL" - cur = self.conn.cursor() - cur.execute(sql) - result = cur.fetchall() - results = [] - columns = [column[0] for column in cur.description] - for row in result: - sect_dict = dict(zip(columns, row)) - results.append(sect_dict) - return results - - def get_all_sects_with_member_count(self): + await self.ensure_pool() + sql = "SELECT * FROM xiuxian_sect WHERE sect_owner is NOT NULL" + async with self.pool.acquire() as conn: + result = await conn.fetch(sql) + results = [] + columns = [column[0] for column in result.description] + for row in result: + sect_dict = dict(zip(columns, row)) + results.append(sect_dict) + return results + + + async def get_all_sects_with_member_count(self): """ 获取所有宗门及其各个宗门成员数 """ - cur = self.conn.cursor() - cur.execute(""" - SELECT s.sect_id, s.sect_name, s.sect_scale, (SELECT user_name FROM user_xiuxian WHERE user_id = s.sect_owner) as user_name, COUNT(ux.user_id) as member_count - FROM sects s - LEFT JOIN user_xiuxian ux ON s.sect_id = ux.sect_id - GROUP BY s.sect_id - """) - results = cur.fetchall() - return results + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = """ + SELECT s.id, s.sect_name, s.sect_scale, (SELECT user_name FROM xiuxian_user WHERE user_id = s.sect_owner) as user_name, COUNT(ux.user_id) as member_count + FROM xiuxian_sect s LEFT JOIN xiuxian_user ux ON s.id = ux.id GROUP BY s.id + """ + results = await conn.fetch(sql) + return results - def update_user_is_beg(self, user_id, is_beg): + + async def update_user_is_beg(self, user_id: int, is_beg: int): """ 更新用户的最后奇缘时间 :param user_id: 用户ID :param is_beg: 'YYYY-MM-DD HH:MM:SS' """ - cur = self.conn.cursor() - sql = "UPDATE user_xiuxian SET is_beg=? WHERE user_id=?" - cur.execute(sql, (is_beg, user_id)) - self.conn.commit() + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "UPDATE xiuxian_user SET is_beg = $1 WHERE user_id = $2" + await conn.execute(sql, is_beg, user_id) + - def get_top1_user(self): + async def get_top1_user(self): """ 获取修为第一的用户 """ - cur = self.conn.cursor() - sql = f"select * from user_xiuxian ORDER BY exp DESC LIMIT 1" - cur.execute(sql) - result = cur.fetchone() - if result: - columns = [column[0] for column in cur.description] - top1_dict = dict(zip(columns, result)) - return top1_dict - else: - return None + await self.ensure_pool() + async with self.pool.acquire() as conn: + sql = "SELECT * FROM xiuxian_user ORDER BY exp DESC LIMIT 1" + result = await conn.fetch(sql) + if result: + return dict(result[0]) + else: + return None - def get_realm_top1_user(self): + async def get_realm_top1_user(self): """ 获取境界第一的用户 """ + await self.ensure_pool() rank_mapping = {rank: idx for idx, rank in enumerate(convert_rank('江湖好手')[1])} - sql = """SELECT user_name, level, exp FROM user_xiuxian + sql = """SELECT user_name, level, exp FROM xiuxian_user WHERE user_name IS NOT NULL ORDER BY exp DESC, (CASE level """ @@ -871,51 +1121,51 @@ def get_realm_top1_user(self): sql += """ELSE level END) ASC LIMIT 1""" - cur = self.conn.cursor() - cur.execute(sql, ) - result = cur.fetchone() - if result: - columns = [column[0] for column in cur.description] - top1_dict = dict(zip(columns, result)) - return top1_dict - else: - return None + async with self.pool.acquire() as conn: + result = await conn.fetch(sql) + if result: + return dict(result[0]) + else: + return None - def donate_update(self, sect_id, stone_num): + async def donate_update(self, sect_id: int, stone_num: int): """宗门捐献更新建设度及可用灵石""" - sql = f"UPDATE sects SET sect_used_stone=sect_used_stone+?,sect_scale=sect_scale+? WHERE sect_id=?" - cur = self.conn.cursor() - cur.execute(sql, (stone_num, stone_num * 1, sect_id)) - self.conn.commit() - - def update_sect_used_stone(self, sect_id, sect_used_stone, key): - """更新宗门灵石储备 1为增加,2为减少""" - cur = self.conn.cursor() - - if key == 1: - sql = f"UPDATE sects SET sect_used_stone=sect_used_stone+? WHERE sect_id=?" - cur.execute(sql, (sect_used_stone, sect_id)) - self.conn.commit() - elif key == 2: - sql = f"UPDATE sects SET sect_used_stone=sect_used_stone-? WHERE sect_id=?" - cur.execute(sql, (sect_used_stone, sect_id)) - self.conn.commit() - - def update_sect_materials(self, sect_id, sect_materials, key): - """更新资材 1为增加,2为减少""" - cur = self.conn.cursor() - - if key == 1: - sql = f"UPDATE sects SET sect_materials=sect_materials+? WHERE sect_id=?" - cur.execute(sql, (sect_materials, sect_id)) - self.conn.commit() - elif key == 2: - sql = f"UPDATE sects SET sect_materials=sect_materials-? WHERE sect_id=?" - cur.execute(sql, (sect_materials, sect_id)) - self.conn.commit() - - def get_all_sects_id_scale(self): + await self.ensure_pool() + sql = "UPDATE xiuxian_sect SET sect_stone=sect_stone + $1,sect_scale=sect_scale + $2 WHERE id = $3" + async with self.pool.acquire() as conn: + await conn.execute(sql, stone_num, stone_num * 1, sect_id) + + + + async def update_sect_stone(self, sect_id: int, sect_stone: int, key: int): + """更新宗门灵石储备 0为增加,1为减少""" + await self.ensure_pool() + async with self.pool.acquire() as conn: + if key == 0: + sql = "UPDATE xiuxian_sect SET sect_stone = sect_stone + $1 WHERE id = $2" + await conn.execute(sql, sect_stone, sect_id) + + elif key == 1: + sql = "UPDATE xiuxian_sect SET sect_stone = sect_stone - $1 WHERE id = $2" + await conn.execute(sql, sect_stone, sect_id) + + + + async def update_sect_material(self, sect_id: int, sect_material: int, key: int): + """更新资材 0为增加,1为减少""" + await self.ensure_pool() + async with self.pool.acquire() as conn: + if key == 0: + sql = "UPDATE xiuxian_sect SET sect_material = sect_material + $1 WHERE id = $2" + await conn.execute(sql, sect_material, sect_id) + + elif key == 1: + sql = "UPDATE xiuxian_sect SET sect_material = sect_material - $1 WHERE id = $2" + await conn.execute(sql, sect_material, sect_id) + + + async def get_all_sects_id_scale(self): """ 获取所有宗门信息 :return @@ -923,29 +1173,28 @@ def get_all_sects_id_scale(self): :result[1] = 建设度 sect_scale, :result[2] = 丹房等级 elixir_room_level """ - sql = f"SELECT sect_id, sect_scale, elixir_room_level FROM sects WHERE sect_owner is NOT NULL ORDER BY sect_scale DESC" - cur = self.conn.cursor() - cur.execute(sql, ) - result = cur.fetchall() - return result + await self.ensure_pool() + sql = "SELECT id, sect_scale, sect_elixir_room_level FROM xiuxian_sect WHERE sect_owner is NOT NULL ORDER BY sect_scale DESC" + async with self.pool.acquire() as conn: + result = await conn.fetch(sql) + return result - def get_all_users_by_sect_id(self, sect_id): + async def get_all_users_by_sect_id(self, sect_id: int): """ 获取宗门所有成员信息 :return: 成员列表 """ - sql = f"SELECT * FROM user_xiuxian WHERE sect_id = ?" - cur = self.conn.cursor() - cur.execute(sql, (sect_id,)) - result = cur.fetchall() - results = [] - for user in result: - columns = [column[0] for column in cur.description] - user_dict = dict(zip(columns, user)) - results.append(user_dict) - return results - - def do_work(self, user_id, the_type, sc_time=None): + await self.ensure_pool() + sql = "SELECT * FROM xiuxian_user WHERE id = $1" + async with self.pool.acquire() as conn: + result = await conn.fetch(sql, sect_id) + results = [] + for user in result: + user_dict = dict(user) + results.append(user_dict) + return results + + async def do_work(self, user_id: int, the_type: int, sc_time: str | None = None): """ 更新用户操作CD :param sc_time: 任务 @@ -954,308 +1203,431 @@ def do_work(self, user_id, the_type, sc_time=None): :param the_time: 本次操作的时长 :return: """ + await self.ensure_pool() now_time = None if the_type == 1: now_time = datetime.now() elif the_type == 0: - now_time = 0 + now_time = None elif the_type == 2: now_time = datetime.now() elif the_type == 3: now_time = datetime.now() - - sql = f"UPDATE user_cd SET type=?,create_time=?,scheduled_time=? WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (the_type, now_time, sc_time, user_id)) - self.conn.commit() - - def update_levelrate(self, user_id, rate): + + # 确保sc_time是正确的类型,修复整数类型转换错误 + sql = "UPDATE xiuxian_time SET schedule_type = $1, schedule_create_time = $2, schedule = $3 WHERE user_id = $4" + async with self.pool.acquire() as conn: + try: + await conn.execute(sql, the_type, now_time, sc_time, user_id) + except Exception as e: + # 在出现类型转换错误时,尝试将sc_time设为None + if "cannot be interpreted as an integer" in str(e): + await conn.execute(sql, the_type, now_time, None, user_id) + else: + raise e + + async def update_levelrate(self, user_id: int, rate: int): """更新突破成功率""" - sql = f"UPDATE user_xiuxian SET level_up_rate=? WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (rate, user_id)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_user SET level_up_rate = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, rate, user_id) + - def update_user_attribute(self, user_id, hp, mp, atk): + async def update_user_attribute(self, user_id: int, hp: int, mp: int, atk: int): """更新用户HP,MP,ATK信息""" - sql = f"UPDATE user_xiuxian SET hp=?,mp=?,atk=? WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (hp, mp, atk, user_id)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_user SET hp = $1,mp = $2,atk = $3 WHERE user_id = $4" + async with self.pool.acquire() as conn: + await conn.execute(sql, hp, mp, atk, user_id) + - def update_user_hp_mp(self, user_id, hp, mp): + async def update_user_hp_mp(self, user_id: int, hp: int, mp: int): """更新用户HP,MP信息""" - sql = f"UPDATE user_xiuxian SET hp=?,mp=? WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (hp, mp, user_id)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_user SET hp = $1,mp = $2 WHERE user_id = $3" + async with self.pool.acquire() as conn: + await conn.execute(sql, hp, mp, user_id) + - def update_user_sect_contribution(self, user_id, sect_contribution): + async def update_user_sect_contribution(self, user_id: int, sect_contribution: int): """更新用户宗门贡献度""" - sql = f"UPDATE user_xiuxian SET sect_contribution=? WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (sect_contribution, user_id)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_user SET sect_contribution = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, sect_contribution, user_id) + - def update_user_hp(self, user_id): + async def update_user_hp(self, user_id: int): """重置用户hp,mp信息""" - sql = f"UPDATE user_xiuxian SET hp=exp/2,mp=exp,atk=exp/10 WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (user_id,)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_user SET hp = exp / 2,mp = exp, atk = exp / 10 WHERE user_id = $1" + async with self.pool.acquire() as conn: + await conn.execute(sql, int(user_id)) + - def restate(self, user_id=None): + async def restate(self, user_id: int | None = None): """重置所有用户状态或重置对应人状态""" + await self.ensure_pool() if user_id is None: - sql = f"UPDATE user_xiuxian SET hp=exp/2,mp=exp,atk=exp/10" - cur = self.conn.cursor() - cur.execute(sql, ) - self.conn.commit() + sql = "UPDATE xiuxian_user SET hp = exp / 2,mp = exp, atk = exp / 10" + async with self.pool.acquire() as conn: + await conn.execute(sql, ) else: - sql = f"UPDATE user_xiuxian SET hp=exp/2,mp=exp,atk=exp/10 WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (user_id,)) - self.conn.commit() + sql = "UPDATE xiuxian_user SET hp = exp / 2,mp = exp, atk = exp / 10 WHERE user_id = $1" + async with self.pool.acquire() as conn: + await conn.execute(sql, int(user_id)) + - def auto_recover_hp(self): - """自动回血函数""" - sql = f"SELECT user_id, exp, hp FROM user_xiuxian WHERE hp < exp/2" - cur = self.conn.cursor() - users = cur.fetchall() + async def get_user_infos_by_ids(self, user_ids): + """批量获取用户信息,优化高并发场景下的多用户查询 - for user in users: - user_id, exp, hp = user - sql = f"UPDATE user_xiuxian SET hp=hp + ?*0.001 WHERE user_id=?" - cur.execute(sql, (exp, user_id)) + Args: + user_ids: 用户ID或用户ID列表 + + Returns: + Dict[int, dict]或单个dict: 用户ID到用户信息的映射字典,如果输入单个ID则返回单个用户信息 + """ + await self.ensure_pool() - self.conn.commit() - - def get_back_msg(self, user_id): + # 处理单个ID的情况 + is_single_id = False + if isinstance(user_ids, int) or (isinstance(user_ids, str) and user_ids.isdigit()): + is_single_id = True + user_ids = [int(user_ids)] + + if not user_ids: + return {} if not is_single_id else None + + try: + placeholders = ','.join(f'${i+1}' for i in range(len(user_ids))) + sql = f""" + SELECT * FROM xiuxian_user WHERE user_id IN ({placeholders}) + """ + + async with self.pool.acquire() as conn: + rows = await conn.fetch(sql, *user_ids) + + # 处理结果 + result = {} + for row in rows: + user_id = row['user_id'] + user_info = dict(row) + result[user_id] = user_info + + # 根据输入类型返回结果 + if is_single_id: + return result.get(user_ids[0]) + else: + return result + + except Exception as e: + logger.error(f"获取用户信息时出错: {e}") + return {} if not is_single_id else None + + + async def auto_recover_hp(self): + """自动回血函数""" + await self.ensure_pool() + sql = """ + UPDATE xiuxian_user + SET hp = LEAST(hp + exp * 0.001, exp / 2) + WHERE hp < exp / 2 + """ + async with self.pool.acquire() as conn: + await conn.execute(sql) + logger.opt(colors=True).info("已为所有用户自动回血") + + async def get_back_msg(self, user_id: int): """获取用户背包信息""" - sql = f"SELECT * FROM back WHERE user_id=? and goods_num >= 1" - cur = self.conn.cursor() - cur.execute(sql, (user_id,)) - result = cur.fetchall() - if not result: - return None + await self.ensure_pool() + sql = "SELECT * FROM xiuxian_back WHERE user_id = $1 and goods_num >= 1" + async with self.pool.acquire() as conn: + result = await conn.fetch(sql, int(user_id)) + if not result: + return None - columns = [column[0] for column in cur.description] - results = [] - for row in result: - back_dict = dict(zip(columns, row)) - results.append(back_dict) - return results + results = [] + for row in result: + back_dict = dict(row) + results.append(back_dict) + return results - def goods_num(self, user_id, goods_id): + async def get_goods_num(self, user_id: int, goods_id: int): """ 判断用户物品数量 :param user_id: 用户qq :param goods_id: 物品id :return: 物品数量 """ - sql = "SELECT num FROM back WHERE user_id=? and goods_id=?" - cur = self.conn.cursor() - cur.execute(sql, (user_id, goods_id)) - result = cur.fetchone() - if result: - return result[0] - else: - return 0 + await self.ensure_pool() + sql = "SELECT num FROM xiuxian_back WHERE user_id = $1 and goods_id = $2" + async with self.pool.acquire() as conn: + result = await conn.fetchmany(sql, user_id, goods_id) + if result: + return result[0] + else: + return 0 - def get_all_user_exp(self, level): + async def get_all_user_exp(self, level: str): """查询所有对应大境界玩家的修为""" - sql = f"SELECT exp FROM user_xiuxian WHERE level like '{level}%'" - cur = self.conn.cursor() - cur.execute(sql, ) - result = cur.fetchall() - return result + await self.ensure_pool() + sql = f"SELECT exp FROM xiuxian_user WHERE level like '{level}%'" + async with self.pool.acquire() as conn: + result = await conn.fetch(sql, ) + return result - def update_user_atkpractice(self, user_id, atkpractice): + async def update_user_atkpractice(self, user_id: int, atk_practice_level: int): """更新用户攻击修炼等级""" - sql = f"UPDATE user_xiuxian SET atkpractice={atkpractice} WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (user_id,)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_user SET atk_practice_level = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, atk_practice_level, user_id) + - def update_user_sect_task(self, user_id, sect_task): + async def update_user_sect_task(self, user_id: int, sect_task: int): """更新用户宗门任务次数""" - sql = f"UPDATE user_xiuxian SET sect_task=sect_task+? WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (sect_task, user_id)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_user SET sect_task_quantity = sect_task_quantity + $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, sect_task, user_id) + + async def get_sect_task(self, user_id: int): + """获取用户的宗门任务""" + await self.ensure_pool() + sql = f"SELECT * FROM xiuxian_sect_task WHERE user_id = {user_id}" + async with self.pool.acquire() as conn: + result = await conn.fetchrow(sql) + return result + + async def create_sect_task(self, user_id: int, task_name: str, task_data: dict): + """创建用户的宗门任务""" + await self.delete_sect_task(user_id) + + await self.ensure_pool() + sql = f""" + INSERT INTO xiuxian_sect_task(user_id, task_name, task_type, task_desc, task_cost, task_give, task_sect) + VALUES({user_id}, $1, {task_data['type']}, $2, {task_data['cost']}, {task_data['give']}, {task_data['sect']}) + """ + async with self.pool.acquire() as conn: + await conn.execute(sql, task_name, task_data['desc']) + + async def delete_sect_task(self, user_id: int): + """删除用户的宗门任务""" + await self.ensure_pool() + sql = f"DELETE FROM xiuxian_sect_task WHERE user_id = {user_id}" + async with self.pool.acquire() as conn: + await conn.execute(sql) + - def sect_task_reset(self): + async def sect_task_reset(self): """重置宗门任务次数""" - sql = f"UPDATE user_xiuxian SET sect_task=0" - cur = self.conn.cursor() - cur.execute(sql, ) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_user SET sect_task_quantity = 0" + async with self.pool.acquire() as conn: + await conn.execute(sql, ) + - def update_sect_scale_and_used_stone(self, sect_id, sect_used_stone, sect_scale): + async def update_sect_scale_and_used_stone(self, sect_id: int, sect_stone: int, sect_scale: int): """更新宗门灵石、建设度""" - sql = f"UPDATE sects SET sect_used_stone=?,sect_scale=? WHERE sect_id=?" - cur = self.conn.cursor() - cur.execute(sql, (sect_used_stone, sect_scale, sect_id)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_sect SET sect_stone = $1, sect_scale = $2 WHERE id = $3" + async with self.pool.acquire() as conn: + await conn.execute(sql, sect_stone, sect_scale, sect_id) + - def update_sect_elixir_room_level(self, sect_id, level): + async def update_sect_elixir_room_level(self, sect_id: int, level: int): """更新宗门丹房等级""" - sql = f"UPDATE sects SET elixir_room_level=? WHERE sect_id=?" - cur = self.conn.cursor() - cur.execute(sql, (level, sect_id)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_sect SET sect_elixir_room_level = $1 WHERE id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, level, sect_id) + - def update_user_sect_elixir_get_num(self, user_id): + async def update_user_sect_elixir_get_num(self, user_id: int): """更新用户每日领取丹药领取次数""" - sql = f"UPDATE user_xiuxian SET sect_elixir_get=1 WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (user_id,)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_user SET is_elixir = 1 WHERE user_id = $1" + async with self.pool.acquire() as conn: + await conn.execute(sql, int(user_id)) + - def sect_elixir_get_num_reset(self): + async def sect_elixir_get_num_reset(self): """重置宗门丹药领取次数""" - sql = f"UPDATE user_xiuxian SET sect_elixir_get=0" - cur = self.conn.cursor() - cur.execute(sql, ) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_user SET is_elixir = 0" + async with self.pool.acquire() as conn: + await conn.execute(sql, ) + - def update_sect_mainbuff(self, sect_id, mainbuffid): + async def update_sect_mainbuff(self, sect_id: int, mainbuffid: int): """更新宗门当前的主修功法""" - sql = f"UPDATE sects SET mainbuff=? WHERE sect_id=?" - cur = self.conn.cursor() - cur.execute(sql, (mainbuffid, sect_id)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_sect SET sect_main_skill = $1 WHERE id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, mainbuffid, sect_id) + - def update_sect_secbuff(self, sect_id, secbuffid): + async def update_sect_secbuff(self, sect_id: int, secbuffid: int): """更新宗门当前的神通""" - sql = f"UPDATE sects SET secbuff=? WHERE sect_id=?" - cur = self.conn.cursor() - cur.execute(sql, (secbuffid, sect_id)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_sect SET sect_ultimate_skill = $1 WHERE id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, secbuffid, sect_id) + - def initialize_user_buff_info(self, user_id): + async def initialize_user_buff_info(self, user_id: int): """初始化用户buff信息""" - sql = f"INSERT INTO BuffInfo (user_id,main_buff,sec_buff,faqi_buff,fabao_weapon) VALUES (?,0,0,0,0)" - cur = self.conn.cursor() - cur.execute(sql, (user_id,)) - self.conn.commit() + await self.ensure_pool() + sql = "INSERT INTO xiuxian_buff (user_id, main_skill, ultimate_skill, weapon) VALUES ($1,0,0,0)" + async with self.pool.acquire() as conn: + await conn.execute(sql, int(user_id)) + - def get_user_buff_info(self, user_id): + async def get_user_buff_info(self, user_id: int): """获取用户buff信息""" - sql = f"select * from BuffInfo WHERE user_id =?" - cur = self.conn.cursor() - cur.execute(sql, (user_id,)) - result = cur.fetchone() - if result: - columns = [column[0] for column in cur.description] - buff_dict = dict(zip(columns, result)) - return buff_dict - else: - return None + await self.ensure_pool() + sql = "SELECT * from xiuxian_buff WHERE user_id = $1" + async with self.pool.acquire() as conn: + result = await conn.fetchrow(sql, int(user_id)) + if result: + return dict(result) + else: + return None - def updata_user_main_buff(self, user_id, id): + async def updata_user_main_buff(self, user_id: int, id: int): """更新用户主功法信息""" - sql = f"UPDATE BuffInfo SET main_buff = ? WHERE user_id = ?" - cur = self.conn.cursor() - cur.execute(sql, (id, user_id,)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_buff SET main_skill = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, id, user_id) + - def updata_user_sub_buff(self, user_id, id): #辅修功法3 + async def updata_user_sub_buff(self, user_id: int, id: int): #辅修功法3 """更新用户辅修功法信息""" - sql = f"UPDATE BuffInfo SET sub_buff = ? WHERE user_id = ?" - cur = self.conn.cursor() - cur.execute(sql, (id, user_id,)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_buff SET support_skill = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, id, user_id) + - def updata_user_sec_buff(self, user_id, id): + async def updata_user_sec_buff(self, user_id: int, id: int): """更新用户副功法信息""" - sql = f"UPDATE BuffInfo SET sec_buff = ? WHERE user_id = ?" - cur = self.conn.cursor() - cur.execute(sql, (id, user_id,)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_buff SET ultimate_skill = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, id, user_id) + - def updata_user_faqi_buff(self, user_id, id): + async def updata_user_faqi_buff(self, user_id: int, id: int): """更新用户法器信息""" - sql = f"UPDATE BuffInfo SET faqi_buff = ? WHERE user_id = ?" - cur = self.conn.cursor() - cur.execute(sql, (id, user_id,)) - self.conn.commit() - - def updata_user_fabao_weapon(self, user_id, id): - """更新用户法宝信息""" - sql = f"UPDATE BuffInfo SET fabao_weapon = ? WHERE user_id = ?" - cur = self.conn.cursor() - cur.execute(sql, (id, user_id,)) - self.conn.commit() - - def updata_user_armor_buff(self, user_id, id): + await self.ensure_pool() + sql = "UPDATE xiuxian_buff SET weapon = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, id, user_id) + + async def updata_user_armor_buff(self, user_id: int, id: int): """更新用户防具信息""" - sql = f"UPDATE BuffInfo SET armor_buff = ? WHERE user_id = ?" - cur = self.conn.cursor() - cur.execute(sql, (id, user_id,)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_buff SET armor = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, id, user_id) + - def updata_user_atk_buff(self, user_id, buff): + async def updata_user_atk_buff(self, user_id: int, buff: int): """更新用户永久攻击buff信息""" - sql = f"UPDATE BuffInfo SET atk_buff=atk_buff+? WHERE user_id = ?" - cur = self.conn.cursor() - cur.execute(sql, (buff, user_id,)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_buff SET atk = atk + $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, buff, user_id) + - def updata_user_blessed_spot(self, user_id, blessed_spot): + async def updata_user_blessed_spot(self, user_id: int, blessed_spot: int): """更新用户洞天福地等级""" - sql = f"UPDATE BuffInfo SET blessed_spot=? WHERE user_id = ?" - cur = self.conn.cursor() - cur.execute(sql, (blessed_spot, user_id,)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_buff SET blessed_spot = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, blessed_spot, user_id) + - def update_user_blessed_spot_flag(self, user_id): + async def update_user_blessed_spot_flag(self, user_id: int): """更新用户洞天福地是否开启""" - sql = f"UPDATE user_xiuxian SET blessed_spot_flag=1 WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (user_id,)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_user SET blessed_spot_flag = 1 WHERE user_id = $1" + async with self.pool.acquire() as conn: + await conn.execute(sql, int(user_id)) + - def update_user_blessed_spot_name(self, user_id, blessed_spot_name): + async def update_user_blessed_spot_name(self, user_id: int, blessed_spot_name: str): """更新用户洞天福地的名字""" - sql = f"UPDATE user_xiuxian SET blessed_spot_name=? WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (blessed_spot_name, user_id,)) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_user SET blessed_spot_name = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, blessed_spot_name, user_id) + - def day_num_reset(self): + async def day_num_reset(self): """重置丹药每日使用次数""" - sql = f"UPDATE back SET day_num=0 WHERE goods_type='丹药'" - cur = self.conn.cursor() - cur.execute(sql, ) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_back SET day_num = 0 WHERE goods_type = '丹药'" + async with self.pool.acquire() as conn: + await conn.execute(sql, ) + - def reset_work_num(self): + async def reset_work_num(self): """重置用户悬赏令刷新次数""" - sql = f"UPDATE user_xiuxian SET work_num=0" - cur = self.conn.cursor() - cur.execute(sql, ) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_user SET work_quantity = 0" + async with self.pool.acquire() as conn: + await conn.execute(sql, ) + - def get_work_num(self, user_id): + async def get_work_num(self, user_id: int): """获取用户悬赏令刷新次数""" - sql = f"SELECT work_num FROM user_xiuxian WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (user_id,)) - result = cur.fetchone() - if result: - work_num = result[0] - return work_num + await self.ensure_pool() + sql = "SELECT work_quantity FROM xiuxian_user WHERE user_id = $1" + async with self.pool.acquire() as conn: + work_num = await conn.fetchval(sql, int(user_id)) + return work_num - def update_work_num(self, user_id, work_num): - sql = f"UPDATE user_xiuxian SET work_num=? WHERE user_id=?" - cur = self.conn.cursor() - cur.execute(sql, (work_num, user_id,)) - self.conn.commit() - + + async def update_work_num(self, user_id: int, work_num: int): + """更新用户悬赏令刷新次数""" + await self.ensure_pool() + sql = "UPDATE xiuxian_user SET work_quantity = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, work_num, user_id) + + async def get_work_info(self, user_id: int): + """获取用户的悬赏令信息""" + await self.ensure_pool() + sql = "SELECT * FROM xiuxian_work_info WHERE user_id = $1" + async with self.pool.acquire() as conn: + result = await conn.fetchrow(sql, user_id) + return result + + async def save_work_info(self, user_id: int, work_msg: str, work_list: list): + """保存用户的悬赏令信息""" + await self.ensure_pool() + sql = """ + INSERT INTO xiuxian_work_info (user_id, work_msg, work_list) + VALUES ($1, $2, $3) + ON CONFLICT (user_id) + DO UPDATE SET work_msg = $2, work_list = $3, create_time = NOW() + """ + async with self.pool.acquire() as conn: + await conn.execute(sql, user_id, work_msg, json.dumps(work_list)) + + async def delete_work_info(self, user_id: int): + """删除用户的悬赏令信息""" + await self.ensure_pool() + sql = "DELETE FROM xiuxian_work_info WHERE user_id = $1" + async with self.pool.acquire() as conn: + await conn.execute(sql, user_id) + - def send_back(self, user_id, goods_id, goods_name, goods_type, goods_num, bind_flag=0): + async def send_back(self, user_id: int, goods_id: int, goods_name: str, goods_type: str, goods_num: int, bind_flag: int = 0): """ 插入物品至背包 :param user_id: 用户qq @@ -1266,152 +1638,462 @@ def send_back(self, user_id, goods_id, goods_name, goods_type, goods_num, bind_f :param bind_flag: 是否绑定物品,0-非绑定,1-绑定 :return: None """ + await self.ensure_pool() now_time = datetime.now() + goods_id = int(goods_id) # 检查物品是否存在,存在则update - cur = self.conn.cursor() - back = self.get_item_by_good_id_and_user_id(user_id, goods_id) + back = await self.get_item_by_good_id_and_user_id(user_id, goods_id) if back: # 判断是否存在,存在则update if bind_flag == 1: - bind_num = back['bind_num'] + goods_num + bind_num = back['goods_bind_num'] + goods_num else: - bind_num = back['bind_num'] + bind_num = back['goods_bind_num'] goods_nums = back['goods_num'] + goods_num - sql = f"UPDATE back set goods_num=?,update_time=?,bind_num={bind_num} WHERE user_id=? and goods_id=?" - cur.execute(sql, (goods_nums, now_time, user_id, goods_id)) - self.conn.commit() + sql = "UPDATE xiuxian_back set goods_num = $1,goods_update_time = $2, goods_bind_num = $3 WHERE user_id = $4 and goods_id = $5" + async with self.pool.acquire() as conn: + await conn.execute(sql, goods_nums, now_time, bind_num, user_id, goods_id) + else: # 判断是否存在,不存在则INSERT if bind_flag == 1: bind_num = goods_num else: bind_num = 0 - sql = f""" - INSERT INTO back (user_id, goods_id, goods_name, goods_type, goods_num, create_time, update_time, bind_num) - VALUES (?,?,?,?,?,?,?,?)""" - cur.execute(sql, (user_id, goods_id, goods_name, goods_type, goods_num, now_time, now_time, bind_num)) - self.conn.commit() + sql = """INSERT INTO xiuxian_back (user_id, goods_id, goods_name, goods_type, goods_num, goods_receive_time, goods_update_time, goods_bind_num) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8)""" + async with self.pool.acquire() as conn: + await conn.execute(sql, user_id, goods_id, goods_name, goods_type, goods_num, now_time, now_time, bind_num) + - def get_item_by_good_id_and_user_id(self, user_id, goods_id): + async def get_item_by_good_id_and_user_id(self, user_id: int, goods_id: int): """根据物品id、用户id获取物品信息""" - sql = f"select * from back WHERE user_id=? and goods_id=?" - cur = self.conn.cursor() - cur.execute(sql, (user_id, goods_id)) - result = cur.fetchone() - if not result: - return None - - columns = [column[0] for column in cur.description] - item_dict = dict(zip(columns, result)) - return item_dict + await self.ensure_pool() + # 确保goods_id是整数类型 + goods_id = int(goods_id) + sql = "SELECT * FROM xiuxian_back WHERE user_id = $1 and goods_id = $2" + async with self.pool.acquire() as conn: + result = await conn.fetchrow(sql, user_id, goods_id) + if not result: + return None + else: + return dict(result) - def update_back_equipment(self, sql_str): + async def update_back_equipment(self, sql_str: str): """更新背包,传入sql""" - logger.opt(colors=True).info(f"执行的sql:{sql_str}") - cur = self.conn.cursor() - cur.execute(sql_str) - self.conn.commit() + await self.ensure_pool() + async with self.pool.acquire() as conn: + await conn.execute(sql_str) + - def reset_user_drug_resistance(self, user_id): + async def reset_user_drug_resistance(self, user_id: int): """重置用户耐药性""" - sql = f"UPDATE back SET all_num=0 where goods_type='丹药' and user_id={user_id}" - cur = self.conn.cursor() - cur.execute(sql, ) - self.conn.commit() + await self.ensure_pool() + sql = "UPDATE xiuxian_back SET goods_all_limit = 0 WHERE goods_type = '丹药' and user_id = $1" + async with self.pool.acquire() as conn: + await conn.execute(sql, int(user_id)) + - def update_back_j(self, user_id, goods_id, num=1, use_key=0): + async def update_back_j(self, user_id: int, goods_id: int, num: int = 1, use_key: int = 0): """ 使用物品 :num 减少数量 默认1 :use_key 是否使用,丹药使用才传 默认0 """ - back = self.get_item_by_good_id_and_user_id(user_id, goods_id) + await self.ensure_pool() + back = await self.get_item_by_good_id_and_user_id(user_id, goods_id) if back['goods_type'] == "丹药" and use_key == 1: # 丹药要判断耐药性、日使用上限 - if back['bind_num'] >= 1: - bind_num = back['bind_num'] - num # 优先使用绑定物品 + if back['goods_bind_num'] >= 1: + bind_num = back['goods_bind_num'] - num # 优先使用绑定物品 else: - bind_num = back['bind_num'] - day_num = back['day_num'] + num - all_num = back['all_num'] + num + bind_num = back['goods_bind_num'] + day_num = back['goods_day_limit'] + num + all_num = back['goods_all_limit'] + num else: - bind_num = back['bind_num'] - day_num = back['day_num'] - all_num = back['all_num'] + bind_num = back['goods_bind_num'] + day_num = back['goods_day_limit'] + all_num = back['goods_all_limit'] goods_num = back['goods_num'] - num now_time = datetime.now() - sql_str = f"UPDATE back set update_time='{now_time}',action_time='{now_time}',goods_num={goods_num},day_num={day_num},all_num={all_num},bind_num={bind_num} WHERE user_id={user_id} and goods_id={goods_id}" - cur = self.conn.cursor() - cur.execute(sql_str) - self.conn.commit() - + sql = "UPDATE xiuxian_back set goods_update_time = $1, goods_action_time = $2, goods_num = $3, goods_day_limit = $4, goods_all_limit = $5, goods_bind_num = $6 WHERE user_id = $7 and goods_id = $8" + async with self.pool.acquire() as conn: + await conn.execute(sql, now_time, now_time, goods_num, day_num, all_num, bind_num, user_id, goods_id) + + -class XiuxianJsonDate: - def __init__(self): - self.root_jsonpath = DATABASE / "灵根.json" - self.level_jsonpath = DATABASE / "突破概率.json" + # 从这里开始是虚神界部分 + async def create_impart_user(self, user_id: str) -> None: + """在数据库中创建用户并初始化""" + await self.ensure_pool() + sql = "INSERT INTO xiuxian_impart (user_id, impart_hp_addition, impart_atk_addition, impart_mp_addition, impart_exp_addition ,impart_boss_atk_addition,impart_crit_addition,impart_crit_dmg_addition,impart_mix_addition,impart_reap_addition,impart_two_exp_quantity,impart_stone_quantity,impart_exp_day_quantity,impart_wish_quantity) VALUES($1, 0, 0, 0, 0 ,0, 0, 0, 0, 0 ,0 ,0 ,0, 0)" + async with self.pool.acquire() as conn: + await conn.execute(sql, int(user_id)) + + - def beifen_linggen_get(self): - with open(self.root_jsonpath, 'r', encoding='utf-8') as e: - a = e.read() - data = json.loads(a) - lg = random.choice(data) - return lg['name'], lg['type'] + async def get_user_impart_info_with_id(self, user_id: int): + """根据USER_ID获取用户impart_buff信息""" + await self.ensure_pool() + sql = "SELECT * from xiuxian_impart WHERE user_id = $1" + async with self.pool.acquire() as conn: + result = await conn.fetchrow(sql, int(user_id)) + if result: + return dict(result) + else: + return None + - def level_rate(self, level): - with open(self.level_jsonpath, 'r', encoding='utf-8') as e: - a = e.read() - data = json.loads(a) - return data[0][level] + async def update_impart_hp_per(self, impart_num: int, user_id: int): + """更新impart_hp_per""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_hp_addition = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True - def linggen_get(self): - """获取灵根信息""" - data = jsondata.root_data() - rate_dict = {} - for i, v in data.items(): - rate_dict[i] = v["type_rate"] - lgen = OtherSet().calculated(rate_dict) - if data[lgen]["type_flag"]: - flag = random.choice(data[lgen]["type_flag"]) - root = random.sample(data[lgen]["type_list"], flag) - msg = "" - for j in root: - if j == root[-1]: - msg += j - break - msg += (j + "、") + async def add_impart_hp_per(self, impart_num: int, user_id: int): + """add impart_hp_addition""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_hp_addition = impart_hp_addition + $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True - return msg + '属性灵根', lgen - else: - root = random.choice(data[lgen]["type_list"]) - return root, lgen + async def update_impart_atk_per(self, impart_num: int, user_id: int): + """更新impart_atk_per""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_atk_addition = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + async def add_impart_atk_per(self, impart_num: int, user_id: int): + """增加impart_atk_per""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_atk_addition=impart_atk_addition + $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + async def update_impart_mp_per(self, impart_num: int, user_id: int): + """更新impart_mp_per""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_mp_addition = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True -class OtherSet(XiuConfig): + async def add_impart_mp_per(self, impart_num: int, user_id: int): + """增加impart_mp_per""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_mp_addition=impart_mp_addition + $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def update_impart_exp_up(self, impart_num: int, user_id: int): + """更新impart_exp_up""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_exp_addition = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def add_impart_exp_up(self, impart_num: int, user_id: int): + """增加impart_exp_up""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_exp_addition=impart_exp_addition + $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def update_boss_atk(self, impart_num: int, user_id: int): + """更新boss_atk""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_boss_atk_addition = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def add_boss_atk(self, impart_num: int, user_id: int): + """增加boss_atk""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_boss_atk_addition=impart_boss_atk_addition + $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def update_impart_know_per(self, impart_num: int, user_id: int): + """更新impart_know_per""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_crit_addition = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def add_impart_know_per(self, impart_num: int, user_id: int): + """增加impart_know_per""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_crit_addition = impart_crit_addition + $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def update_impart_burst_per(self, impart_num: int, user_id: int): + """更新impart_burst_per""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_crit_dmg_addition = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def add_impart_burst_per(self, impart_num: int, user_id: int): + """增加impart_burst_per""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_crit_dmg_addition = impart_crit_dmg_addition + $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def update_impart_mix_per(self, impart_num: int, user_id: int): + """更新impart_mix_per""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_mix_addition = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def add_impart_mix_per(self, impart_num: int, user_id: int): + """增加impart_mix_per""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_mix_addition = impart_mix_addition + $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def update_impart_reap_per(self, impart_num: int, user_id: int): + """更新impart_reap_per""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_reap_addition = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def add_impart_reap_per(self, impart_num: int, user_id: int): + """增加impart_reap_per""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_reap_addition = impart_reap_addition + $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def update_impart_two_exp(self, impart_num: int, user_id: int): + """更新双修经验""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_two_exp_quantity = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def add_impart_two_exp(self, impart_num: int, user_id: int): + """增加双修经验""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_two_exp_quantity = impart_two_exp_quantity + $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def update_impart_wish(self, impart_num: int, user_id: int): + """更新抽卡次数""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_wish_quantity = $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def add_impart_wish(self, impart_num: int, user_id: int): + """增加抽卡次数""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_wish_quantity = impart_wish_quantity + $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def update_stone_num(self, impart_num: int, user_id: int, type_: int): + """更新结晶数量, 0为增加, 1为减少""" + await self.ensure_pool() + if type_ == 0: + sql = "UPDATE xiuxian_impart SET impart_stone_quantity = impart_stone_quantity + $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + if type_ == 1: + sql = "UPDATE xiuxian_impart SET impart_stone_quantity = impart_stone_quantity - $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_num, user_id) + + return True + + async def update_impart_stone_all(self, impart_stone: int): + """所有用户增加结晶""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_stone_quantity = impart_stone_quantity + $1" + async with self.pool.acquire() as conn: + await conn.execute(sql, impart_stone) + + return True + + async def add_impart_exp_day(self, impart_num: int, user_id: int): + """增加虚神界经验""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_exp_day_quantity = impart_exp_day_quantity + $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, int(impart_num), int(user_id)) + + return True + + async def use_impart_exp_day(self, impart_num: int, user_id: int): + """使用虚神界经验""" + await self.ensure_pool() + sql = "UPDATE xiuxian_impart SET impart_exp_day_quantity = impart_exp_day_quantity - $1 WHERE user_id = $2" + async with self.pool.acquire() as conn: + await conn.execute(sql, int(impart_num), int(user_id)) + + return True + + @classmethod + async def perform_maintenance(cls): + """ + 执行定期数据库维护任务,优化性能和空间占用 + + 包括: + 1. 刷新物化视图 + 2. 执行垃圾回收 + 3. 优化索引 + + Returns: + 任务执行结果 + """ + results = { + "views_refreshed": False, + "vacuum_performed": False, + "indexes_rebuilt": False + } + + try: + # 刷新物化视图 + results["views_refreshed"] = await cls.refresh_views() + logger.opt(colors=True).info(f"物化视图刷新{'成功' if results['views_refreshed'] else '失败'}") + + # 执行垃圾回收 + results["vacuum_performed"] = await cls.vacuum_tables(full=False) + logger.opt(colors=True).info(f"VACUUM操作{'成功' if results['vacuum_performed'] else '失败'}") + + # 尝试重建索引 + try: + from .vacuum_optimization import reindex_all_tables + results["indexes_rebuilt"] = await reindex_all_tables() + logger.opt(colors=True).info(f"索引重建{'成功' if results['indexes_rebuilt'] else '失败'}") + except ImportError: + logger.opt(colors=True).warning("索引优化模块未加载,跳过索引重建") + + return results + + except Exception as e: + logger.opt(colors=True).error(f"数据库维护任务执行失败: {e}") + return results + + +class XiuxianJsonData: + def __init__(self): + self.root_jsonpath = DATABASE / "灵根.json" + self.level_jsonpath = DATABASE / "突破概率.json" + + def beifen_linggen_get(self): + with open(self.root_jsonpath, 'r', encoding='utf-8') as e: + a = e.read() + data = json.loads(a) + lg = random.choice(data) + return lg['name'], lg['type'] + + def level_rate(self, level): + with open(self.level_jsonpath, 'r', encoding='utf-8') as e: + a = e.read() + data = json.loads(a) + return data[0][level] + + def linggen_get(self): + """获取灵根信息""" + data = jsondata.root_data() + rate_dict = {} + for i, v in data.items(): + rate_dict[i] = v["type_rate"] + lgen = OtherSet().calculated(rate_dict) + if data[lgen]["type_flag"]: + flag = random.choice(data[lgen]["type_flag"]) + root = random.sample(data[lgen]["type_list"], flag) + msg = "" + for j in root: + if j == root[-1]: + msg += j + break + msg += (j + "、") + + return msg + '属性灵根', lgen + else: + root = random.choice(data[lgen]["type_list"]) + return root, lgen + + + +class OtherSet(XiuConfig): def __init__(self): super().__init__() - def set_closing_type(self, user_level): + async def set_closing_type(self, user_level): list_all = len(self.level) - 1 now_index = self.level.index(user_level) if list_all == now_index: need_exp = 0.001 else: is_updata_level = self.level[now_index + 1] - need_exp = XiuxianDateManage().get_level_power(is_updata_level) + need_exp = await XiuxianDataManager().get_level_power(is_updata_level) return need_exp - def get_type(self, user_exp, rate, user_level): + async def get_type(self, user_exp, rate, user_level): list_all = len(self.level) - 1 now_index = self.level.index(user_level) if list_all == now_index: return "道友已是最高境界,无法突破!" is_updata_level = self.level[now_index + 1] - need_exp = XiuxianDateManage().get_level_power(is_updata_level) + need_exp = await XiuxianDataManager().get_level_power(is_updata_level) # 判断修为是否足够突破 if user_exp >= need_exp: @@ -1458,12 +2140,12 @@ def date_diff(self, new_time, old_time): if isinstance(new_time, datetime): pass else: - new_time = datetime.strptime(new_time, '%Y-%m-%d %H:%M:%S.%f') + new_time = datetime.strptime(new_time, '%Y-%m-%d %H:%M:%S.%') if isinstance(old_time, datetime): pass else: - old_time = datetime.strptime(old_time, '%Y-%m-%d %H:%M:%S.%f') + old_time = datetime.strptime(old_time, '%Y-%m-%d %H:%M:%S.%') day = (new_time - old_time).days sec = (new_time - old_time).seconds @@ -1471,6 +2153,7 @@ def date_diff(self, new_time, old_time): return (day * 24 * 60 * 60) + sec def get_power_rate(self, mind, other): + """获取修为差距""" power_rate = mind / (other + mind) if power_rate >= 0.8: return "道友偷窃小辈实属天道所不齿!" @@ -1479,7 +2162,7 @@ def get_power_rate(self, mind, other): else: return int(power_rate * 100) - def player_fight(self, player1: dict, player2: dict): + async def player_fight(self, player1: dict, player2: dict): """ 回合制战斗 type_in : 1 为完整返回战斗过程(未加) @@ -1487,8 +2170,9 @@ def player_fight(self, player1: dict, player2: dict): 数据示例: {"道号": None, "气血": None, "攻击": None, "真元": None, '会心':None} """ - msg1 = "{}发起攻击,造成了{}伤害\n" - msg2 = "{}发起攻击,造成了{}伤害\n" + from .utils import number_to + msg1 = "{}发起攻击,造成了{}点伤害\n" + msg2 = "{}发起攻击,造成了{}点伤害\n" play_list = [] suc = None @@ -1497,39 +2181,39 @@ def player_fight(self, player1: dict, player2: dict): if player2['气血'] <= 0: player2['气血'] = 1 while True: - player1_gj = int(round(random.uniform(0.95, 1.05), 2) * player1['攻击']) + player1_gj = int(round(random.uniform(0.95, 1.05), 2) * float(player1['攻击'])) if random.randint(0, 100) <= player1['会心']: player1_gj = int(player1_gj * player1['爆伤']) - msg1 = "{}发起会心一击,造成了{}伤害\n" + msg1 = "{}发起会心一击,造成了{}点伤害\n" - player2_gj = int(round(random.uniform(0.95, 1.05), 2) * player2['攻击']) + player2_gj = int(round(random.uniform(0.95, 1.05), 2) * float(player2['攻击'])) if random.randint(0, 100) <= player2['会心']: player2_gj = int(player2_gj * player2['爆伤']) - msg2 = "{}发起会心一击,造成了{}伤害\n" + msg2 = "{}发起会心一击,造成了{}点伤害\n" play1_sh: int = int(player1_gj * (1 - player2['防御'])) play2_sh: int = int(player2_gj * (1 - player1['防御'])) - play_list.append(msg1.format(player1['道号'], play1_sh)) + play_list.append(msg1.format(player1['道号'], number_to(play1_sh))) player2['气血'] = player2['气血'] - play1_sh - play_list.append(f"{player2['道号']}剩余血量{player2['气血']}") - XiuxianDateManage().update_user_hp_mp(player2['user_id'], player2['气血'], player2['真元']) + play_list.append(f"{player2['道号']}剩余血量{number_to(player2['气血'])}") + await XiuxianDataManager().update_user_hp_mp(player2['user_id'], player2['气血'], player2['真元']) if player2['气血'] <= 0: play_list.append(f"{player1['道号']}胜利") suc = f"{player1['道号']}" - XiuxianDateManage().update_user_hp_mp(player2['user_id'], 1, player2['真元']) + await XiuxianDataManager().update_user_hp_mp(player2['user_id'], 1, player2['真元']) break - play_list.append(msg2.format(player2['道号'], play2_sh)) + play_list.append(msg2.format(player2['道号'], number_to(play2_sh))) player1['气血'] = player1['气血'] - play2_sh - play_list.append(f"{player1['道号']}剩余血量{player1['气血']}\n") - XiuxianDateManage().update_user_hp_mp(player1['user_id'], player1['气血'], player1['真元']) + play_list.append(f"{player1['道号']}剩余血量{number_to(player1['气血'])}\n") + await XiuxianDataManager().update_user_hp_mp(player1['user_id'], player1['气血'], player1['真元']) if player1['气血'] <= 0: play_list.append(f"{player2['道号']}胜利") suc = f"{player2['道号']}" - XiuxianDateManage().update_user_hp_mp(player1['user_id'], 1, player1['真元']) + await XiuxianDataManager().update_user_hp_mp(player1['user_id'], 1, player1['真元']) break if player1['气血'] <= 0 or player2['气血'] <= 0: play_list.append("逻辑错误!!!") @@ -1537,8 +2221,8 @@ def player_fight(self, player1: dict, player2: dict): return play_list, suc - def send_hp_mp(self, user_id, hp, mp): - user_msg = XiuxianDateManage().get_user_info_with_id(user_id) + async def send_hp_mp(self, user_id, hp, mp): + user_msg = await XiuxianDataManager().get_user_infos_by_ids(user_id) max_hp = int(user_msg['exp'] / 2) max_mp = int(user_msg['exp']) @@ -1573,427 +2257,8 @@ def send_hp_mp(self, user_id, hp, mp): return msg, hp_mp - - -sql_message = XiuxianDateManage() # sql类 -items = Items() - - -def final_user_data(user_data, columns): - """传入用户当前信息、buff信息,返回最终信息""" - user_dict = dict(zip((col[0] for col in columns), user_data)) - - # 通过字段名称获取相应的值 - impart_data = xiuxian_impart.get_user_impart_info_with_id(user_dict['user_id']) - if impart_data is None: - xiuxian_impart._create_user(user_dict['user_id']) - - impart_data = xiuxian_impart.get_user_impart_info_with_id(user_dict['user_id']) - impart_hp_per = impart_data['impart_hp_per'] if impart_data is not None else 0 - impart_mp_per = impart_data['impart_mp_per'] if impart_data is not None else 0 - impart_atk_per = impart_data['impart_atk_per'] if impart_data is not None else 0 - - user_buff_data = UserBuffDate(user_dict['user_id']).BuffInfo - - armor_atk_buff = 0 - if int(user_buff_data['armor_buff']) != 0: - armor_info = items.get_data_by_item_id(user_buff_data['armor_buff']) - armor_atk_buff = armor_info['atk_buff'] - - weapon_atk_buff = 0 - if int(user_buff_data['faqi_buff']) != 0: - weapon_info = items.get_data_by_item_id(user_buff_data['faqi_buff']) - weapon_atk_buff = weapon_info['atk_buff'] - - main_buff_data = UserBuffDate(user_dict['user_id']).get_user_main_buff_data() - main_hp_buff = main_buff_data['hpbuff'] if main_buff_data is not None else 0 - main_mp_buff = main_buff_data['mpbuff'] if main_buff_data is not None else 0 - main_atk_buff = main_buff_data['atkbuff'] if main_buff_data is not None else 0 - - # 改成字段名称来获取相应的值 - user_dict['hp'] = int(user_dict['hp'] * (1 + main_hp_buff + impart_hp_per)) - user_dict['mp'] = int(user_dict['mp'] * (1 + main_mp_buff + impart_mp_per)) - user_dict['atk'] = int((user_dict['atk'] * (user_dict['atkpractice'] * 0.04 + 1) * (1 + main_atk_buff) * ( - 1 + weapon_atk_buff) * (1 + armor_atk_buff)) * (1 + impart_atk_per)) + int(user_buff_data['atk_buff']) - - return user_dict - -@DRIVER.on_shutdown -async def close_db(): - XiuxianDateManage().close() - - -# 这里是虚神界部分 -class XIUXIAN_IMPART_BUFF: - global impart_num - _instance = {} - _has_init = {} - - def __new__(cls): - if cls._instance.get(impart_num) is None: - cls._instance[impart_num] = super(XIUXIAN_IMPART_BUFF, cls).__new__(cls) - return cls._instance[impart_num] - - def __init__(self): - if not self._has_init.get(impart_num): - self._has_init[impart_num] = True - self.database_path = DATABASE_IMPARTBUFF - if not self.database_path.exists(): - self.database_path.mkdir(parents=True) - self.database_path /= "xiuxian_impart.db" - self.conn = sqlite3.connect(self.database_path) - # self._create_file() - else: - self.database_path /= "xiuxian_impart.db" - self.conn = sqlite3.connect(self.database_path) - logger.opt(colors=True).info(f"xiuxian_impart数据库已连接!") - self._check_data() - - def close(self): - self.conn.close() - logger.opt(colors=True).info(f"xiuxian_impart数据库关闭!") - - def _create_file(self) -> None: - """创建数据库文件""" - c = self.conn.cursor() - c.execute('''CREATE TABLE xiuxian_impart - (NO INTEGER PRIMARY KEY UNIQUE, - USERID TEXT , - level INTEGER , - root INTEGER - );''') - c.execute('''''') - c.execute('''''') - self.conn.commit() - - def _check_data(self): - """检查数据完整性""" - c = self.conn.cursor() - - for i in config_impart.sql_table: - if i == "xiuxian_impart": - try: - c.execute(f"select count(1) from {i}") - except sqlite3.OperationalError: - c.execute(f"""CREATE TABLE "xiuxian_impart" ( - "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, - "user_id" integer DEFAULT 0, - "impart_hp_per" integer DEFAULT 0, - "impart_atk_per" integer DEFAULT 0, - "impart_mp_per" integer DEFAULT 0, - "impart_exp_up" integer DEFAULT 0, - "boss_atk" integer DEFAULT 0, - "impart_know_per" integer DEFAULT 0, - "impart_burst_per" integer DEFAULT 0, - "impart_mix_per" integer DEFAULT 0, - "impart_reap_per" integer DEFAULT 0, - "impart_two_exp" integer DEFAULT 0, - "stone_num" integer DEFAULT 0, - "exp_day" integer DEFAULT 0, - "wish" integer DEFAULT 0 - );""") - - for s in config_impart.sql_table_impart_buff: - try: - c.execute(f"select {s} from xiuxian_impart") - except sqlite3.OperationalError: - sql = f"ALTER TABLE xiuxian_impart ADD COLUMN {s} integer DEFAULT 0;" - logger.opt(colors=True).info(f"{sql}") - logger.opt(colors=True).info(f"xiuxian_impart数据库核对成功!") - c.execute(sql) - - self.conn.commit() - - @classmethod - def close_dbs(cls): - XIUXIAN_IMPART_BUFF().close() - - def create_user(self, user_id): - """校验用户是否存在""" - cur = self.conn.cursor() - sql = f"select * from xiuxian_impart WHERE user_id=?" - cur.execute(sql, (user_id,)) - result = cur.fetchone() - if not result: - return False - else: - return True - - def _create_user(self, user_id: str) -> None: - """在数据库中创建用户并初始化""" - if self.create_user(user_id): - pass - else: - c = self.conn.cursor() - sql = f"INSERT INTO xiuxian_impart (user_id, impart_hp_per, impart_atk_per, impart_mp_per, impart_exp_up ,boss_atk,impart_know_per,impart_burst_per,impart_mix_per,impart_reap_per,impart_two_exp,stone_num,exp_day,wish) VALUES(?, 0, 0, 0, 0 ,0, 0, 0, 0, 0 ,0 ,0 ,0, 0)" - c.execute(sql, (user_id,)) - self.conn.commit() - - def get_user_impart_info_with_id(self, user_id): - """根据USER_ID获取用户impart_buff信息""" - cur = self.conn.cursor() - sql = f"select * from xiuxian_impart WHERE user_id=?" - cur.execute(sql, (user_id,)) - result = cur.fetchone() - if result: - columns = [column[0] for column in cur.description] - user_dict = dict(zip(columns, result)) - return user_dict - else: - return None - - - def update_impart_hp_per(self, impart_num, user_id): - """更新impart_hp_per""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_hp_per=? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def add_impart_hp_per(self, impart_num, user_id): - """add impart_hp_per""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_hp_per=impart_hp_per+? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def update_impart_atk_per(self, impart_num, user_id): - """更新impart_atk_per""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_atk_per=? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def add_impart_atk_per(self, impart_num, user_id): - """add impart_atk_per""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_atk_per=impart_atk_per+? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def update_impart_mp_per(self, impart_num, user_id): - """impart_mp_per""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_mp_per=? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def add_impart_mp_per(self, impart_num, user_id): - """add impart_mp_per""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_mp_per=impart_mp_per+? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def update_impart_exp_up(self, impart_num, user_id): - """impart_exp_up""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_exp_up=? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def add_impart_exp_up(self, impart_num, user_id): - """add impart_exp_up""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_exp_up=impart_exp_up+? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def update_boss_atk(self, impart_num, user_id): - """boss_atk""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET boss_atk=? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def add_boss_atk(self, impart_num, user_id): - """add boss_atk""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET boss_atk=boss_atk+? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def update_impart_know_per(self, impart_num, user_id): - """impart_know_per""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_know_per=? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def add_impart_know_per(self, impart_num, user_id): - """add impart_know_per""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_know_per=impart_know_per+? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def update_impart_burst_per(self, impart_num, user_id): - """impart_burst_per""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_burst_per=? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def add_impart_burst_per(self, impart_num, user_id): - """add impart_burst_per""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_burst_per=impart_burst_per+? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def update_impart_mix_per(self, impart_num, user_id): - """impart_mix_per""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_mix_per=? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def add_impart_mix_per(self, impart_num, user_id): - """add impart_mix_per""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_mix_per=impart_mix_per+? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def update_impart_reap_per(self, impart_num, user_id): - """impart_reap_per""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_reap_per=? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def add_impart_reap_per(self, impart_num, user_id): - """add impart_reap_per""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_reap_per=impart_reap_per+? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def update_impart_two_exp(self, impart_num, user_id): - """更新双修""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_two_exp=? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def add_impart_two_exp(self, impart_num, user_id): - """add impart_two_exp""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET impart_two_exp=impart_two_exp+? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def update_impart_wish(self, impart_num, user_id): - """更新抽卡次数""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET wish=? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def add_impart_wish(self, impart_num, user_id): - """增加抽卡次数""" - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET wish=wish+? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def update_stone_num(self, impart_num, user_id, type_): - """更新结晶数量""" - if type_ == 1: - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET stone_num=stone_num+? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - if type_ == 2: - cur = self.conn.cursor() - sql = f"UPDATE xiuxian_impart SET stone_num=stone_num-? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def update_impart_stone_all(self, impart_stone): - """所有用户增加结晶""" - cur = self.conn.cursor() - sql = "UPDATE xiuxian_impart SET stone_num=stone_num+?" - cur.execute(sql, (impart_stone,)) - self.conn.commit() - - def add_impart_exp_day(self, impart_num, user_id): - """add impart_exp_day""" - cur = self.conn.cursor() - sql = "UPDATE xiuxian_impart SET exp_day=exp_day+? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - def use_impart_exp_day(self, impart_num, user_id): - """use impart_exp_day""" - cur = self.conn.cursor() - sql = "UPDATE xiuxian_impart SET exp_day=exp_day-? WHERE user_id=?" - cur.execute(sql, (impart_num, user_id)) - self.conn.commit() - return True - - -def leave_harm_time(user_id): - """重伤恢复时间""" - hp_speed = 25 - user_mes = sql_message.get_user_info_with_id(user_id) - level = user_mes['level'] - level_rate = sql_message.get_root_rate(user_mes['root_type']) # 灵根倍率 - realm_rate = jsondata.level_data()[level]["spend"] # 境界倍率 - main_buff_data = UserBuffDate(user_id).get_user_main_buff_data() # 主功法数据 - main_buff_rate_buff = main_buff_data['ratebuff'] if main_buff_data else 0 # 主功法修炼倍率 - - try: - time = int(((user_mes['exp'] / 1.5) - user_mes['hp']) / ((XiuConfig().closing_exp * level_rate * realm_rate * ( - 1 + main_buff_rate_buff)) * hp_speed)) - except ZeroDivisionError: - time = "无穷大" - except OverflowError: - time = "溢出" - return time - - -async def impart_check(user_id): - if XIUXIAN_IMPART_BUFF().get_user_impart_info_with_id(user_id) is None: - XIUXIAN_IMPART_BUFF()._create_user(user_id) - return XIUXIAN_IMPART_BUFF().get_user_impart_info_with_id(user_id) - else: - return XIUXIAN_IMPART_BUFF().get_user_impart_info_with_id(user_id) - -xiuxian_impart = XIUXIAN_IMPART_BUFF() - -@DRIVER.on_shutdown -async def close_db(): - XIUXIAN_IMPART_BUFF().close() - - # 这里是buff部分 -class BuffJsonDate: +class BuffJsonData: def __init__(self): """json文件路径""" @@ -2025,60 +2290,1111 @@ def get_armor_info(self, id): return readf(self.armor_jsonpath)[str(id)] -class UserBuffDate: +class UserBuffData: def __init__(self, user_id): """用户Buff数据""" self.user_id = user_id + self._buff_info = None + self._main_buff_data = None + self._sub_buff_data = None + self._sec_buff_data = None + self._weapon_data = None + self._armor_buff_data = None @property - def BuffInfo(self): + async def BuffInfo(self): """获取最新的 Buff 信息""" - return get_user_buff(self.user_id) + if self._buff_info is None: + self._buff_info = await get_user_buff(self.user_id) + return self._buff_info - def get_user_main_buff_data(self): + async def get_user_main_buff_data(self): """获取用户主功法数据""" - main_buff_data = None - buff_info = self.BuffInfo - main_buff_id = buff_info.get('main_buff', 0) - if main_buff_id != 0: - main_buff_data = items.get_data_by_item_id(main_buff_id) - return main_buff_data + if self._main_buff_data is None: + buff_info = await self.BuffInfo + main_buff_id = buff_info.get('main_skill', 0) + if main_buff_id != 0: + self._main_buff_data = items.get_data_by_item_id(main_buff_id) + return self._main_buff_data - def get_user_sub_buff_data(self): + async def get_user_sub_buff_data(self): """获取用户辅修功法数据""" - sub_buff_data = None - buff_info = self.BuffInfo - sub_buff_id = buff_info.get('sub_buff', 0) - if sub_buff_id != 0: - sub_buff_data = items.get_data_by_item_id(sub_buff_id) - return sub_buff_data - - def get_user_sec_buff_data(self): + if self._sub_buff_data is None: + buff_info = await self.BuffInfo + sub_buff_id = buff_info.get('support_skill', 0) + if sub_buff_id != 0: + self._sub_buff_data = items.get_data_by_item_id(sub_buff_id) + return self._sub_buff_data + + async def get_user_sec_buff_data(self): """获取用户神通数据""" - sec_buff_data = None - buff_info = self.BuffInfo - sec_buff_id = buff_info.get('sec_buff', 0) - if sec_buff_id != 0: - sec_buff_data = items.get_data_by_item_id(sec_buff_id) - return sec_buff_data - - def get_user_weapon_data(self): + if self._sec_buff_data is None: + buff_info = await self.BuffInfo + sec_buff_id = buff_info.get('ultimate_skill', 0) + if sec_buff_id != 0: + self._sec_buff_data = items.get_data_by_item_id(sec_buff_id) + return self._sec_buff_data + + async def get_user_weapon_data(self): """获取用户法器数据""" - weapon_data = None - buff_info = self.BuffInfo - weapon_id = buff_info.get('faqi_buff', 0) - if weapon_id != 0: - weapon_data = items.get_data_by_item_id(weapon_id) - return weapon_data - - def get_user_armor_buff_data(self): + if self._weapon_data is None: + buff_info = await self.BuffInfo + weapon_id = buff_info.get('weapon', 0) + if weapon_id != 0: + self._weapon_data = items.get_data_by_item_id(weapon_id) + return self._weapon_data + + async def get_user_armor_buff_data(self): """获取用户防具数据""" - armor_buff_data = None - buff_info = self.BuffInfo - armor_buff_id = buff_info.get('armor_buff', 0) - if armor_buff_id != 0: - armor_buff_data = items.get_data_by_item_id(armor_buff_id) - return armor_buff_data + if self._armor_buff_data is None: + buff_info = await self.BuffInfo + armor_buff_id = buff_info.get('armor', 0) + if armor_buff_id != 0: + self._armor_buff_data = items.get_data_by_item_id(armor_buff_id) + return self._armor_buff_data + + +class XiuXianNameGenerator: + def __init__(self, data_dir: str = ""): + """初始化修仙名称生成器 + + Args: + data_dir: 数据文件目录路径 + """ + self.data_dir = data_dir + self.data = self._load_data() + self._validate_data() + + def _load_data(self) -> Dict[str, Any]: + """加载所有JSON数据文件""" + data = {} + + # 加载共享数据 + data["common"] = self._load_json_file("shared/common.json") + data["strange"] = self._load_json_file("shared/strange.json") + data["color"] = self._load_json_file("shared/color.json") + data["spirit"] = self._load_json_file("shared/spirit.json") + + # 加载人名数据 + data["family"] = self._load_json_file("name/family.json") + data["female"] = self._load_json_file("name/female.json") + data["male"] = self._load_json_file("name/male.json") + data["middle"] = self._load_json_file("name/middle.json") + + # 加载道号数据 + data["dao"] = self._load_json_file("dao/dao.json") + data["dao_title_male"] = self._load_json_file("dao/title_male.json") + data["dao_title_female"] = self._load_json_file("dao/title_female.json") + + # 加载技能数据 + data["skill"] = self._load_json_file("skill/skill.json") + data["skill_prefix"] = self._load_json_file("skill/prefix.json") + data["skill_numfix"] = self._load_json_file("skill/numfix.json") + + # 加载书籍数据 + data["book"] = self._load_json_file("book/book.json") + data["book_prefix"] = self._load_json_file("book/prefix.json") + data["book_postfix"] = self._load_json_file("book/postfix.json") + + # 加载符箓数据 + data["talisman"] = self._load_json_file("talisman/talisman.json") + data["talisman_material"] = self._load_json_file("talisman/material.json") + data["talisman_postfix"] = self._load_json_file("talisman/postfix.json") + + # 加载组织数据 + data["clan"] = self._load_json_file("organization/clan.json") + data["nation"] = self._load_json_file("organization/nation.json") + + # 加载地点数据 + data["place"] = self._load_json_file("place/place.json") + data["place_prefix"] = self._load_json_file("place/prefix.json") + data["place_postfix"] = self._load_json_file("place/postfix.json") + data["location"] = self._load_json_file("place/location.json") + data["zone"] = self._load_json_file("place/zone.json") + + # 加载材料数据 + data["material"] = self._load_json_file("material/material.json") + data["material_postfix"] = self._load_json_file("material/postfix.json") + + # 加载生物数据 + data["creature"] = self._load_json_file("creature/creature.json") + data["creature_prefix"] = self._load_json_file("creature/prefix.json") + data["strange_creature"] = self._load_json_file("creature/strange.json") + + # 加载丹药数据 + data["alchemy"] = self._load_json_file("alchemy/alchemy.json") + + return data + + def _load_json_file(self, file_path: str) -> Any: + """加载单个JSON文件 + + Args: + file_path: 相对于data_dir的文件路径 + + Returns: + 加载的JSON数据 + """ + full_path = os.path.join(self.data_dir, file_path) + try: + with open(full_path, 'r', encoding='utf-8') as f: + return json.load(f) + except Exception as e: + print(f"无法加载 {full_path}: {e}") + return {} if file_path.endswith(".json") else [] + + def _validate_data(self): + """验证加载的数据是否完整有效""" + required_data = [ + "common", "strange", "color", "spirit", + "family", "female", "male", "middle", + "dao", "dao_title_male", "dao_title_female", + "skill", "skill_prefix", "skill_numfix", + "book", "book_prefix", "book_postfix", + "talisman", "talisman_material", "talisman_postfix", + "clan", "nation", + "place", "place_prefix", "place_postfix", "location", "zone", + "material", "material_postfix", + "creature", "creature_prefix", "strange_creature", + "alchemy" + ] + missing = [] + for item in required_data: + if not self.data.get(item): + missing.append(item) + + if missing: + print(f"警告: 以下数据不完整或缺失: {', '.join(missing)}") + + @property + def dao_titles(self) -> List[str]: + """获取所有道号称号列表""" + titles = [] + for gender in ["dao_title_male", "dao_title_female"]: + for rarity in RARITY_LEVELS: + if gender in self.data and rarity in self.data[gender]: + titles.extend(self.data[gender][rarity]) + return list(set(titles)) # 去重 + + @property + def book_prefixes(self) -> List[str]: + """获取所有书籍前缀列表""" + prefixes = [] + for rarity in ["epic", "legendary", "mythic", "exotic"]: + if "book_prefix" in self.data and rarity in self.data["book_prefix"]: + prefixes.extend(self.data["book_prefix"][rarity]) + return prefixes + + @property + def talisman_kind(self) -> List[str]: + """获取所有符箓类型列表""" + kinds = [] + for rarity in RARITY_LEVELS: + if "talisman" in self.data and rarity in self.data["talisman"]: + kinds.extend(self.data["talisman"][rarity]) + return kinds + + @property + def material_kind(self) -> List[str]: + """获取所有材料类型列表""" + kinds = [] + for rarity in RARITY_LEVELS: + if "material" in self.data and rarity in self.data["material"]: + kinds.extend(self.data["material"][rarity]) + return kinds + + @property + def material_postfixes(self) -> List[str]: + """获取所有材料后缀列表""" + postfixes = [] + for kind in ["broken", "handmade"]: + if "material_postfix" in self.data and kind in self.data["material_postfix"]: + postfixes.extend(self.data["material_postfix"][kind]) + return postfixes + + @property + def talisman_postfixes(self) -> List[str]: + """获取所有符箓后缀列表""" + postfixes = [] + for kind in ["broken", "handmade"]: + if "talisman_postfix" in self.data and kind in self.data["talisman_postfix"]: + postfixes.extend(self.data["talisman_postfix"][kind]) + return postfixes + + @property + def zone_kind(self) -> List[str]: + """获取所有区域类型列表""" + kinds = [] + for category in ZONE_CATEGORIES: + if "zone" in self.data and category in self.data["zone"]: + kinds.extend(self.data["zone"][category]) + return kinds + + @property + def book_postfixes(self) -> List[str]: + """获取所有书籍后缀列表""" + postfixes = [] + for rarity in ["uncommon", "rare"]: + if "book_postfix" in self.data and rarity in self.data["book_postfix"]: + postfixes.extend(self.data["book_postfix"][rarity]) + return postfixes + + def _get_rarity(self, max_value: float = 1.0) -> Dict[str, str]: + """获取随机稀有度 + + Args: + max_value: 随机值上限 + + Returns: + 包含稀有度和随机值的字典 + """ + value = random.random() * (max_value or 1.0) + if value < RARITY_VALUES["exotic"]: + rarity = "exotic" + elif value < RARITY_VALUES["mythic"]: + rarity = "mythic" + elif value < RARITY_VALUES["legendary"]: + rarity = "legendary" + elif value < RARITY_VALUES["epic"]: + rarity = "epic" + elif value < RARITY_VALUES["rare"]: + rarity = "rare" + elif value < RARITY_VALUES["uncommon"]: + rarity = "uncommon" + else: + rarity = "common" + return {"rarity": rarity, "value": value} + + def get_name(self, number: int = 1, options: Dict = None) -> List[str]: + """生成人名 + + Args: + number: 生成名字的数量 + options: 选项参数,可包含: + familyName: 指定姓氏 + isFemale: 是否女性 + style: 命名风格('single', 'double', 'combine') + middleCharacter: 中间字符 + + Returns: + 生成的名字列表 + """ + options = options or {} + names = [] + + for _ in range(number): + if options.get("familyName"): + the_family_name = options["familyName"] + else: + family_index = random.randint(0, len(self.data["family"]) - 1) + the_family_name = self.data["family"][family_index] + + is_female = options.get("isFemale", random.randint(0, 1) == 0) + names_of_a_sex = self.data["female"] if is_female else self.data["male"] + + r = random.random() + style = options.get("style") + if not style: + if r < 0.33333333: + style = "single" + elif r < 0.66666666: + style = "double" + else: + style = "combine" + + name = "" + if style == "single": + if options.get("middleCharacter"): + name = options["middleCharacter"] + else: + name_index = random.randint(0, len(names_of_a_sex) - 1) + name = names_of_a_sex[name_index] + elif style == "double": + if options.get("middleCharacter"): + the_middle_character = options["middleCharacter"] + else: + name_index = random.randint(0, len(names_of_a_sex) - 1) + the_middle_character = names_of_a_sex[name_index] + + name_index = random.randint(0, len(names_of_a_sex) - 1) + the_last_character = names_of_a_sex[name_index] + name = the_middle_character + the_last_character + else: + if options.get("middleCharacter"): + the_middle_character = options["middleCharacter"] + else: + name_index = random.randint(0, len(self.data["middle"]) - 1) + the_middle_character = self.data["middle"][name_index] + + name_index = random.randint(0, len(names_of_a_sex) - 1) + the_last_character = names_of_a_sex[name_index] + name = the_middle_character + the_last_character + + names.append(the_family_name + name) + + return names + + def get_dao(self, number: int = 1, options: Dict = None) -> List[Dict]: + """生成道号 + + Args: + number: 生成道号的数量 + options: 选项参数,可包含: + firstCharacter: 第一个字符 + isFemale: 是否女性 + title: 称号 + + Returns: + 生成的道号列表,每个元素包含name和rarity + """ + options = options or {} + names = [] + + for _ in range(number): + if options.get("firstCharacter"): + the_first_character = options["firstCharacter"] + else: + name_index1 = random.randint(0, len(self.data["dao"]) - 1) + the_first_character = self.data["dao"][name_index1] + + name_index2 = random.randint(0, len(self.data["dao"]) - 1) + name = the_first_character + self.data["dao"][name_index2] + + is_female = options.get("isFemale", random.randint(0, 1) == 0) + title_group = self.data["dao_title_female"] if is_female else self.data["dao_title_male"] + + t = options.get("title", "") + rarity = "common" + + if not t: + rarity_info = self._get_rarity() + rarity = rarity_info["rarity"] + + if rarity == "exotic" and title_group.get("exotic"): + t = random.choice(title_group["exotic"]) + elif rarity == "mythic" and title_group.get("mythic"): + t = random.choice(title_group["mythic"]) + elif rarity == "legendary" and title_group.get("legendary"): + t = random.choice(title_group["legendary"]) + elif rarity == "epic" and title_group.get("epic"): + t = random.choice(title_group["epic"]) + elif rarity == "rare" and title_group.get("rare"): + t = random.choice(title_group["rare"]) + elif rarity == "uncommon" and title_group.get("uncommon"): + t = random.choice(title_group["uncommon"]) + else: + if t in (title_group.get("exotic", []) + self.data["dao_title_male"].get("exotic", [])): + rarity = "exotic" + elif t in (title_group.get("mythic", []) + self.data["dao_title_male"].get("mythic", [])): + rarity = "mythic" + elif t in (title_group.get("legendary", []) + self.data["dao_title_male"].get("legendary", [])): + rarity = "legendary" + elif t in (title_group.get("epic", []) + self.data["dao_title_male"].get("epic", [])): + rarity = "epic" + elif t in (title_group.get("rare", []) + self.data["dao_title_male"].get("rare", [])): + rarity = "rare" + elif t in (title_group.get("uncommon", []) + self.data["dao_title_male"].get("uncommon", [])): + rarity = "uncommon" + + names.append({"name": name + t, "rarity": rarity}) + + return names + + def _get_skill_name(self, length: Optional[int] = None, kind: Optional[str] = None, + prefix: Optional[str] = None, numfix: Optional[str] = None) -> Dict: + """生成单个技能名称 + + Args: + length: 名称长度 + kind: 技能类型 + prefix: 前缀 + numfix: 数字后缀 + + Returns: + 包含name和rarity的字典 + """ + len = length or 1 + rarity = "common" + + if not length: + r = self._get_rarity() + if r["value"] < RARITY_VALUES["rare"]: + len = 3 + elif r["value"] < RARITY_VALUES["uncommon"]: + len = 2 + rarity = r["rarity"] + else: + if length > 2: + rarity = "rare" + elif length > 1: + rarity = "uncommon" + + common = [] + for category in ["dao", "element", "creature", "thing", "color", "place", + "adj", "number", "gesture", "action"]: + if category in self.data.get("common", {}): + common.extend(self.data["common"][category]) + + name = "" + for _ in range(len): + name += random.choice(common) + + pre = prefix or "" + if not pre and random.random() < RARITY_VALUES["epic"]: + pre = random.choice(self.data["skill_prefix"]) + + n = numfix or "" + if not n and random.random() < RARITY_VALUES["epic"]: + n = random.choice(self.data["skill_numfix"]) + + k = kind or random.choice(self.data["skill"]) + + if random.random() < 0.5: + name = (n + _NUMBER_BEGIN_SUPPLEMENT if n else "") + pre + name + k + else: + if len(k) > 1: + name = pre + name + k + (n + _NUMBER_END_SUPPLEMENT if n else "") + else: + name = pre + name + n + k + + return {"name": name, "rarity": rarity} + + def get_skill(self, number: int = 1, options: Dict = None) -> List[Dict]: + """生成功法名称 + + Args: + number: 生成名称的数量 + options: 选项参数,可包含: + length: 技能名称长度 + kind: 技能类型 + prefix: 前缀 + numfix: 数字后缀 + + Returns: + 生成的功法名称列表,每个元素包含name和rarity + """ + options = options or {} + names = [] + + for _ in range(number): + name = self._get_skill_name( + options.get("length"), + options.get("kind"), + options.get("prefix"), + options.get("numfix") + ) + names.append(name) + + return names + + def get_book(self, number: int = 1, options: Dict = None) -> List[Dict]: + """生成秘籍名称 + + Args: + number: 生成名称的数量 + options: 选项参数,可包含: + length: 书名长度 + mainkind: 主要类型 + prefix: 前缀 + postkind: 后缀类型 + postfix: 后缀 + + Returns: + 生成的秘籍名称列表,每个元素包含name和rarity + """ + options = options or {} + names = [] + + for _ in range(number): + skillname = self._get_skill_name(options.get("length"), options.get("mainkind")) + rarity = skillname["rarity"] + + pre = options.get("prefix", "") + if not pre: + if rarity == "exotic" and "exotic" in self.data["book_prefix"]: + pre = random.choice(self.data["book_prefix"]["exotic"]) + elif rarity == "mythic" and "mythic" in self.data["book_prefix"]: + pre = random.choice(self.data["book_prefix"]["mythic"]) + elif rarity == "legendary" and "legendary" in self.data["book_prefix"]: + pre = random.choice(self.data["book_prefix"]["legendary"]) + elif rarity == "epic" and "epic" in self.data["book_prefix"]: + pre = random.choice(self.data["book_prefix"]["epic"]) + + pk = options.get("postkind", "") + if pre and not pk: + pk = random.choice(self.data["book"]) + + post = options.get("postfix", "") + if not post: + r1 = random.random() + r2 = random.random() + if r1 < RARITY_VALUES["rare"] and r2 < RARITY_VALUES["rare"] and "rare" in self.data["book_postfix"]: + post = _PARENTHESIS_LEFT + random.choice(self.data["book_postfix"]["rare"]) + _PARENTHESIS_RIGHT + elif r1 < RARITY_VALUES["uncommon"] and r2 < RARITY_VALUES["uncommon"] and "uncommon" in self.data["book_postfix"]: + post = _PARENTHESIS_LEFT + random.choice(self.data["book_postfix"]["uncommon"]) + _PARENTHESIS_RIGHT + else: + post = _PARENTHESIS_LEFT + post + _PARENTHESIS_RIGHT + + names.append({ + "name": _BOOK_LEFT + skillname["name"] + pre + pk + post + _BOOK_RIGHT, + "rarity": rarity + }) + + return names + + def get_creature(self, number: int = 1, options: Dict = None) -> List[Dict]: + """生成生灵名称 + + Args: + number: 生成名称的数量 + options: 选项参数,可包含: + category: 生物种类 + rarity: 稀有度 + + Returns: + 生成的生灵名称列表,每个元素包含name,rarity和category + """ + options = options or {} + names = [] + common_creature_names = [] + for category in ["dao", "element", "thing", "color", "number", "action"]: + if category in self.data.get("common", {}): + common_creature_names.extend(self.data["common"][category]) + + for _ in range(number): + name = "" + pre = random.choice(common_creature_names) + c = random.choice(self.data["color"]) + s = random.choice(self.data["creature_prefix"]) + + cat = options.get("category") + if not cat: + cat = random.choice(CREATURE_CATEGORY) + + k = random.choice(self.data["creature"][cat]) + r = options.get("rarity") or self._get_rarity(RARITY_VALUES["uncommon"])["rarity"] + + if r == "exotic": + name = random.choice(self.data["strange_creature"]) + elif r == "mythic": + name = pre + c + s + k + elif r == "legendary": + name = pre + s + k + elif r == "epic": + name = pre + c + k + elif r == "rare": + name = pre + k + elif r == "uncommon": + name = c + s + k + elif r == "common": + name = c + k + + names.append({"name": name, "rarity": r, "category": cat}) + + return names + + def get_material(self, number: int = 1, options: Dict = None) -> List[Dict]: + """生成材料名称 + + Args: + number: 生成名称的数量 + options: 选项参数,可包含: + kind: 材料类型 + rarity: 稀有度 + postfix: 后缀 + + Returns: + 生成的材料名称列表,每个元素包含name和rarity + """ + options = options or {} + names = [] + common = [] + for category in self.data.get("common", {}): + common.extend(self.data["common"][category]) + + for _ in range(number): + name = "" + age = "" + pre = random.choice(common) + c = random.choice(self.data["color"]) + s = random.choice(self.data["spirit"]) + + k = options.get("kind") + r = options.get("rarity") or self._get_rarity(RARITY_VALUES["uncommon"])["rarity"] + + if r == "exotic": + all_materials = [] + for rarity_level in RARITY_LEVELS: + if rarity_level in self.data["material"]: + all_materials.extend(self.data["material"][rarity_level]) + k = k or random.choice(all_materials) + age = _AGE100 + name = age + pre + c + s + k + elif r == "mythic": + materials = [] + for rarity_level in RARITY_LEVELS: + if rarity_level in ["mythic", "legendary", "epic", "rare", "uncommon", "common"]: + if rarity_level in self.data["material"]: + materials.extend(self.data["material"][rarity_level]) + k = k or random.choice(materials) + age = _AGE10 + name = age + pre + c + s + k + elif r == "legendary": + materials = [] + for rarity_level in RARITY_LEVELS: + if rarity_level in ["legendary", "epic", "rare", "uncommon", "common"]: + if rarity_level in self.data["material"]: + materials.extend(self.data["material"][rarity_level]) + k = k or random.choice(materials) + age = _AGE1 + name = age + pre + c + s + k + elif r == "epic": + materials = [] + for rarity_level in RARITY_LEVELS: + if rarity_level in ["epic", "rare", "uncommon", "common"]: + if rarity_level in self.data["material"]: + materials.extend(self.data["material"][rarity_level]) + k = k or random.choice(materials) + name = pre + c + s + k + elif r == "rare": + materials = [] + for rarity_level in RARITY_LEVELS: + if rarity_level in ["rare", "uncommon", "common"]: + if rarity_level in self.data["material"]: + materials.extend(self.data["material"][rarity_level]) + k = k or random.choice(materials) + name = pre + s + k + elif r == "uncommon": + materials = [] + for rarity_level in RARITY_LEVELS: + if rarity_level in ["uncommon", "common"]: + if rarity_level in self.data["material"]: + materials.extend(self.data["material"][rarity_level]) + k = k or random.choice(materials) + name = c + s + k + elif r == "common": + if "common" in self.data["material"]: + k = k or random.choice(self.data["material"]["common"]) + name = c + k + + post = options.get("postfix", "") + if not post: + r1 = random.random() + r2 = random.random() + if (r1 < RARITY_VALUES["rare"] and r2 < RARITY_VALUES["rare"] and + "broken" in self.data["material_postfix"]): + post = (_PARENTHESIS_LEFT + + random.choice(self.data["material_postfix"]["broken"]) + + _PARENTHESIS_RIGHT) + elif (r1 < RARITY_VALUES["uncommon"] and r2 < RARITY_VALUES["uncommon"] and + "handmade" in self.data["material_postfix"]): + post = (_PARENTHESIS_LEFT + + random.choice(self.data["material_postfix"]["handmade"]) + + _PARENTHESIS_RIGHT) + else: + post = _PARENTHESIS_LEFT + post + _PARENTHESIS_RIGHT + + names.append({"name": name + post, "rarity": r}) + + return names + + def get_talisman(self, number: int = 1, options: Dict = None) -> List[Dict]: + """生成法宝名称 + + Args: + number: 生成名称的数量 + options: 选项参数,可包含: + kind: 符箓类型 + rarity: 稀有度 + postfix: 后缀 + + Returns: + 生成的法宝名称列表,每个元素包含name和rarity + """ + options = options or {} + names = [] + common = [] + for category in self.data.get("common", {}): + common.extend(self.data["common"][category]) + + for _ in range(number): + name = "" + prefix = random.choice(common) + c = random.choice(self.data["color"]) + m = random.choice(self.data["talisman_material"]) + s = random.choice(self.data["spirit"]) + + k = options.get("kind") + r = options.get("rarity") or self._get_rarity(RARITY_VALUES["uncommon"])["rarity"] + + if r == "exotic": + all_talismans = [] + for rarity_level in RARITY_LEVELS: + if rarity_level in self.data["talisman"]: + all_talismans.extend(self.data["talisman"][rarity_level]) + k = k or random.choice(all_talismans) + name = prefix + s + k + elif r == "mythic": + talismans = [] + for rarity_level in RARITY_LEVELS: + if rarity_level in ["mythic", "legendary", "epic", "rare", "uncommon", "common"]: + if rarity_level in self.data["talisman"]: + talismans.extend(self.data["talisman"][rarity_level]) + k = k or random.choice(talismans) + name = prefix + s + k + elif r == "legendary": + talismans = [] + for rarity_level in RARITY_LEVELS: + if rarity_level in ["legendary", "epic", "rare", "uncommon", "common"]: + if rarity_level in self.data["talisman"]: + talismans.extend(self.data["talisman"][rarity_level]) + k = k or random.choice(talismans) + name = prefix + c + m + k + elif r == "epic": + talismans = [] + for rarity_level in RARITY_LEVELS: + if rarity_level in ["epic", "rare", "uncommon", "common"]: + if rarity_level in self.data["talisman"]: + talismans.extend(self.data["talisman"][rarity_level]) + k = k or random.choice(talismans) + name = prefix + m + k + elif r == "rare": + talismans = [] + for rarity_level in RARITY_LEVELS: + if rarity_level in ["rare", "uncommon", "common"]: + if rarity_level in self.data["talisman"]: + talismans.extend(self.data["talisman"][rarity_level]) + k = k or random.choice(talismans) + name = prefix + k + elif r == "uncommon": + talismans = [] + for rarity_level in RARITY_LEVELS: + if rarity_level in ["uncommon", "common"]: + if rarity_level in self.data["talisman"]: + talismans.extend(self.data["talisman"][rarity_level]) + k = k or random.choice(talismans) + name = c + m + k + elif r == "common": + if "common" in self.data["talisman"]: + k = k or random.choice(self.data["talisman"]["common"]) + name = m + k + + post = options.get("postfix", "") + if not post: + r1 = random.random() + r2 = random.random() + if (r1 < RARITY_VALUES["rare"] and r2 < RARITY_VALUES["rare"] and + "broken" in self.data["talisman_postfix"]): + post = (_PARENTHESIS_LEFT + + random.choice(self.data["talisman_postfix"]["broken"]) + + _PARENTHESIS_RIGHT) + elif (r1 < RARITY_VALUES["uncommon"] and r2 < RARITY_VALUES["uncommon"] and + "handmade" in self.data["talisman_postfix"]): + post = (_PARENTHESIS_LEFT + + random.choice(self.data["talisman_postfix"]["handmade"]) + + _PARENTHESIS_RIGHT) + else: + post = _PARENTHESIS_LEFT + post + _PARENTHESIS_RIGHT + + names.append({"name": name + post, "rarity": r}) + + return names + + def get_alchemy(self, number: int = 1, kind: Optional[str] = None) -> List[Dict]: + """生成丹药名称 + + Args: + number: 生成名称的数量 + kind: 丹药类型 + + Returns: + 生成的丹药名称列表,每个元素包含name和rarity + """ + names = [] + common_alchemy_names = [] + for category in ["dao", "element", "color", "number", "action"]: + if category in self.data.get("common", {}): + common_alchemy_names.extend(self.data["common"][category]) + + for _ in range(number): + rarity = "common" + pre = random.choice(common_alchemy_names) + s = "" + + r = self._get_rarity() + if r["value"] < RARITY_VALUES["rare"]: + s = random.choice(self.data["spirit"]) + + rarity = r["rarity"] + k = kind or "" + if not kind: + k = random.choice(self.data["alchemy"]) + + names.append({"name": pre + s + k, "rarity": rarity}) + + return names + + def get_clan(self, number: int = 1, kind: Optional[str] = None) -> List[str]: + """生成门派名称 + + Args: + number: 生成名称的数量 + kind: 门派类型 + + Returns: + 生成的门派名称列表 + """ + names = [] + common = [] + for category in self.data.get("common", {}): + common.extend(self.data["common"][category]) + + for _ in range(number): + name = random.choice(common) + k = kind + if not k: + k = random.choice(self.data["clan"]) + + names.append(name + k) + + return names + + def get_nation(self, number: int = 1, kind: Optional[str] = None) -> List[Dict]: + """生成国家名称 + + Args: + number: 生成名称的数量 + kind: 国家类型 + + Returns: + 生成的国家名称列表,每个元素包含name和rarity + """ + names = [] + common = [] + for category in self.data.get("common", {}): + common.extend(self.data["common"][category]) + + for _ in range(number): + name = "" + k = kind or "" + rarity = "common" + + r = random.random() + if r < RARITY_VALUES["rare"]: + name = random.choice(self.data["strange"]) + rarity = "rare" + if not kind: + if len(name) == 1: + k = _COUNTRY + else: + k = random.choice(self.data["nation"]) + elif r < RARITY_VALUES["uncommon"]: + name = random.choice(common) + rarity = "uncommon" + if not kind: + if len(name) == 1: + k = _COUNTRY + else: + k = random.choice(self.data["nation"]) + else: + prefix = "" + if random.random() < RARITY_VALUES["rare"]: + prefix = random.choice(self.data["place_prefix"]) + + name = prefix + random.choice(self.data["place"]) + if not kind: + k = _COUNTRY + + names.append({"name": name + k, "rarity": rarity}) + + return names + + def get_location(self, number: int = 1, kind: Optional[str] = None) -> List[Dict]: + """生成据点名称 + + Args: + number: 生成名称的数量 + kind: 地点类型 + + Returns: + 生成的据点名称列表,每个元素包含name和rarity + """ + names = [] + common = [] + for category in self.data.get("common", {}): + common.extend(self.data["common"][category]) + + for _ in range(number): + name = "" + k = kind or "" + rarity = "common" + + r = random.random() + if r < RARITY_VALUES["rare"]: + name = random.choice(self.data["strange"]) + rarity = "rare" + elif r < RARITY_VALUES["uncommon"]: + name = random.choice(common) + rarity = "uncommon" + else: + place_index = random.randint(0, len(self.data["place"]) - 1) + postfix = "" + if random.random() < RARITY_VALUES["uncommon"]: + postfix_index = random.randint(0, len(self.data["place_postfix"]) - 1) + postfix = self.data["place_postfix"][postfix_index] + + name = self.data["place"][place_index] + postfix + + if not kind: + k = random.choice(self.data["location"]) + + names.append({"name": name + k, "rarity": rarity}) + + return names + + def _get_zone_kind(self, category: Optional[str] = None) -> str: + """获取地域类型 + + Args: + category: 区域类别 + + Returns: + 地域类型字符串 + """ + category = category or random.choice(ZONE_CATEGORIES) + group = self.data["zone"][category] + return random.choice(group) + + def get_zone(self, number: int = 1, options_or_kind=None) -> List[Dict]: + """生成地域名称 + + Args: + number: 生成名称的数量 + options_or_kind: 可以是区域类型字符串或包含以下键的选项字典: + kind: 区域类型 + category: 区域类别 + + Returns: + 生成的地域名称列表,每个元素包含name和rarity + """ + options = {} + if isinstance(options_or_kind, str): + options = {"kind": options_or_kind} + elif isinstance(options_or_kind, dict): + options = options_or_kind + + names = [] + common = [] + for category in self.data.get("common", {}): + common.extend(self.data["common"][category]) + + for _ in range(number): + name = "" + k = options.get("kind") or self._get_zone_kind(options.get("category")) + rarity = "common" + + r = random.random() + if r < RARITY_VALUES["rare"]: + name = random.choice(self.data["strange"]) + rarity = "rare" + elif r < RARITY_VALUES["uncommon"]: + name = random.choice(common) + rarity = "uncommon" + else: + prefix = "" + if random.random() < RARITY_VALUES["rare"]: + prefix = random.choice(self.data["place_prefix"]) + + name = prefix + random.choice(self.data["place"]) + if len(name) == 1: + if len(k) > 1: + name += _LINK_WORD + else: + if random.random() < RARITY_VALUES["rare"]: + name += _LINK_WORD + + names.append({"name": name + k, "rarity": rarity}) + + return names + + + +async def final_user_data(user_data, columns): + """传入用户当前信息、buff信息,返回最终信息""" + user_dict = user_data + + # 通过字段名称获取相应的值 + impart_data = await XiuxianDataManager().get_user_impart_info_with_id(user_dict['user_id']) + if impart_data is None: + await XiuxianDataManager().create_impart_user(user_dict['user_id']) + + impart_data = await XiuxianDataManager().get_user_impart_info_with_id(user_dict['user_id']) + impart_hp_addition = float(impart_data['impart_hp_addition']) if impart_data is not None else 0 + impart_mp_addition = float(impart_data['impart_mp_addition']) if impart_data is not None else 0 + impart_atk_addition = float(impart_data['impart_atk_addition']) if impart_data is not None else 0 + + user_buff_data = await get_user_buff(user_dict['user_id']) + + armor_atk_buff = 0 + if int(user_buff_data['armor']) != 0: + armor_info = items.get_data_by_item_id(user_buff_data['armor']) + armor_atk_buff = float(armor_info['atk_buf']) + + weapon_atk_buff = 0 + if int(user_buff_data['weapon']) != 0: + weapon_info = items.get_data_by_item_id(user_buff_data['weapon']) + weapon_atk_buff = float(weapon_info['atk_buff']) + + main_buff_data = await UserBuffData(user_dict['user_id']).get_user_main_buff_data() + main_hp_buff = float(main_buff_data['hpbuff']) if main_buff_data is not None else 0 + main_mp_buff = float(main_buff_data['mpbuff']) if main_buff_data is not None else 0 + main_atk_buff = float(main_buff_data['atkbuff']) if main_buff_data is not None else 0 + + # 确保所有值都是float类型,然后再进行计算 + user_atk = float(user_dict['atk']) + atk_practice_level = float(user_dict['atk_practice_level']) + + # 改成字段名称来获取相应的值 + user_dict['hp'] = int(float(user_dict['hp']) * (1 + main_hp_buff + impart_hp_addition)) + user_dict['mp'] = int(float(user_dict['mp']) * (1 + main_mp_buff + impart_mp_addition)) + user_dict['atk'] = int((user_atk * (atk_practice_level * 0.04 + 1) * (1 + main_atk_buff) * ( + 1 + weapon_atk_buff) * (1 + armor_atk_buff)) * (1 + impart_atk_addition)) + int(user_buff_data['atk']) + + return user_dict + + +async def leave_harm_time(user_id): + """重伤恢复时间""" + hp_speed = 25 + user_mes = await XiuxianDataManager().get_user_infos_by_ids(user_id) + level = user_mes['level'] + level_rate = await XiuxianDataManager().get_root_rate(user_mes['root_type']) # 灵根倍率 + realm_rate = jsondata.level_data()[level]["spend"] # 境界倍率 + + # 获取buff信息并处理主功法数据 + user_buff_data = await get_user_buff(user_id) + main_buff_data = None + main_buff_id = user_buff_data.get('main_skill', 0) + if main_buff_id != 0: + main_buff_data = items.get_data_by_item_id(main_buff_id) + main_buff_rate_buff = main_buff_data['ratebuf'] if main_buff_data else 0 # 主功法修炼倍率 + + try: + time = int(((float(user_mes['exp']) / 1.5) - float(user_mes['hp'])) / ((XiuConfig().closing_exp * level_rate * realm_rate * ( + 1 + main_buff_rate_buff)) * hp_speed)) + except ZeroDivisionError: + time = "无穷大" + except OverflowError: + time = "溢出" + return time + + +async def impart_check(user_id): + if await XiuxianDataManager().get_user_impart_info_with_id(user_id) is None: + await XiuxianDataManager().create_impart_user(user_id) + return await XiuxianDataManager().get_user_impart_info_with_id(user_id) + else: + return await XiuxianDataManager().get_user_impart_info_with_id(user_id) def get_weapon_info_msg(weapon_id, weapon_info=None): @@ -2091,12 +3407,12 @@ def get_weapon_info_msg(weapon_id, weapon_info=None): msg = '' if weapon_info is None: weapon_info = items.get_data_by_item_id(weapon_id) - atk_buff_msg = f"提升{int(weapon_info['atk_buff'] * 100)}%攻击力!" if weapon_info['atk_buff'] != 0 else '' - crit_buff_msg = f"提升{int(weapon_info['crit_buff'] * 100)}%会心率!" if weapon_info['crit_buff'] != 0 else '' + atk_buff_msg = f"提升{int(weapon_info['atk_buff'] * 100)}%攻击力!" if weapon_info['atk_buf'] != 0 else '' + crit_buff_msg = f"提升{int(weapon_info['crit_buff'] * 100)}%会心率!" if weapon_info['crit_buf'] != 0 else '' crit_atk_msg = f"提升{int(weapon_info['critatk'] * 100)}%会心伤害!" if weapon_info['critatk'] != 0 else '' - def_buff_msg = f"{'提升' if weapon_info['def_buff'] > 0 else '降低'}{int(abs(weapon_info['def_buff']) * 100)}%减伤率!" if weapon_info['def_buff'] != 0 else '' - zw_buff_msg = f"装备专属武器时提升伤害!!" if weapon_info['zw'] != 0 else '' - mp_buff_msg = f"降低真元消耗{int(weapon_info['mp_buff'] * 100)}%!" if weapon_info['mp_buff'] != 0 else '' + def_buff_msg = f"{'提升' if weapon_info['def_buff'] > 0 else '降低'}{int(abs(weapon_info['def_buff']) * 100)}%减伤率!" if weapon_info['def_buf'] != 0 else '' + zw_buff_msg = "装备专属武器时提升伤害!!" if weapon_info['zw'] != 0 else '' + mp_buff_msg = f"降低真元消耗{int(weapon_info['mp_buff'] * 100)}%!" if weapon_info['mp_buf'] != 0 else '' msg += f"名字:{weapon_info['name']}\n" msg += f"品阶:{weapon_info['level']}\n" msg += f"效果:{atk_buff_msg}{crit_buff_msg}{crit_atk_msg}{def_buff_msg}{mp_buff_msg}{zw_buff_msg}" @@ -2114,8 +3430,8 @@ def get_armor_info_msg(armor_id, armor_info=None): if armor_info is None: armor_info = items.get_data_by_item_id(armor_id) def_buff_msg = f"提升{int(armor_info['def_buff'] * 100)}%减伤率!" - atk_buff_msg = f"提升{int(armor_info['atk_buff'] * 100)}%攻击力!" if armor_info['atk_buff'] != 0 else '' - crit_buff_msg = f"提升{int(armor_info['crit_buff'] * 100)}%会心率!" if armor_info['crit_buff'] != 0 else '' + atk_buff_msg = f"提升{int(armor_info['atk'] * 100)}%攻击力!" if armor_info['atk'] != 0 else '' + crit_buff_msg = f"提升{int(armor_info['crit_buff'] * 100)}%会心率!" if armor_info['crit_buf'] != 0 else '' msg += f"名字:{armor_info['name']}\n" msg += f"品阶:{armor_info['level']}\n" msg += f"效果:{def_buff_msg}{atk_buff_msg}{crit_buff_msg}" @@ -2142,8 +3458,8 @@ def get_main_info_msg(id): clo_exp_msg = f",提升{round(mainbuff['clo_exp'] * 100, 0)}%闭关经验" if mainbuff['clo_exp'] != 0 else '' clo_rs_msg = f",提升{round(mainbuff['clo_rs'] * 100, 0)}%闭关生命回复" if mainbuff['clo_rs'] != 0 else '' - random_buff_msg = f",战斗时随机获得一个战斗属性" if mainbuff['random_buff'] != 0 else '' - ew_msg = f",使用专属武器时伤害增加50%!" if mainbuff['ew'] != 0 else '' + random_buff_msg = ",战斗时随机获得一个战斗属性" if mainbuff['random_buff'] != 0 else '' + ew_msg = ",使用专属武器时伤害增加50%!" if mainbuff['ew'] != 0 else '' msg = f"{mainbuff['name']}: {hpmsg}{mpmsg}{atkmsg}{ratemsg}{cri_tmsg}{def_msg}{dan_msg}{dan_exp_msg}{reap_msg}{exp_msg}{critatk_msg}{two_msg}{number_msg}{clo_exp_msg}{clo_rs_msg}{random_buff_msg}{ew_msg}!" return mainbuff, msg @@ -2182,11 +3498,11 @@ def get_sub_info_msg(id): #辅修功法8 msg = f"{subbuff['name']}:{submsg}{stone_msg}{integral_msg}{jin_msg}{drop_msg}{fan_msg}{break_msg}{exp_msg}" return subbuff, msg -def get_user_buff(user_id): - BuffInfo = sql_message.get_user_buff_info(user_id) +async def get_user_buff(user_id): + BuffInfo = await XiuxianDataManager().get_user_buff_info(user_id) if BuffInfo is None: - sql_message.initialize_user_buff_info(user_id) - return sql_message.get_user_buff_info(user_id) + await XiuxianDataManager().initialize_user_buff_info(user_id) + return await XiuxianDataManager().get_user_buff_info(user_id) else: return BuffInfo @@ -2247,7 +3563,7 @@ def get_player_info(user_id, info_name): if key not in list(player_info.keys()): player_info[key] = MIXELIXIRINFOCONFIG[key] save_player_info(user_id, player_info, info_name) - except: + except ValueError: player_info = MIXELIXIRINFOCONFIG save_player_info(user_id, player_info, info_name) return player_info @@ -2265,7 +3581,7 @@ def save_player_info(user_id, data, info_name): user_id = str(user_id) if not os.path.exists(PLAYERSDATA / user_id): - logger.opt(colors=True).info(f"用户目录不存在,创建目录") + logger.opt(colors=True).info("用户目录不存在,创建目录") os.makedirs(PLAYERSDATA / user_id) FILEPATH = PLAYERSDATA / user_id / f"{info_name}.json" @@ -2273,4 +3589,16 @@ def save_player_info(user_id, data, info_name): save_mode = "w" if os.path.exists(FILEPATH) else "x" with open(FILEPATH, mode=save_mode, encoding="UTF-8") as f: f.write(data) - f.close() \ No newline at end of file + f.close() + + +@DRIVER.on_shutdown +async def close_db(): + await XiuxianDataManager().close() + +@DRIVER.on_startup +async def init_db(): + """初始化数据库连接和表结构""" + data_manager = XiuxianDataManager() + await data_manager._init_db_and_pool() + logger.opt(colors=True).info("修仙数据库初始化完成!") \ No newline at end of file diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/xn_xiuxian_impart_config.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/xn_xiuxian_impart_config.py deleted file mode 100755 index 8630c444..00000000 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_utils/xn_xiuxian_impart_config.py +++ /dev/null @@ -1,17 +0,0 @@ -from pathlib import Path - -DATABASE = Path() / "data" / "xiuxian" - - -class IMPART_BUFF_CONFIG: - def __init__(self): - self.sql_table = ["xiuxian_impart"] - # 数据库字段 - self.sql_table_impart_buff = ["id", "user_id", "impart_hp_per", - "impart_atk_per", "impart_mp_per", - "impart_exp_up", "boss_atk", - "impart_know_per", "impart_burst_per", - "impart_mix_per", "impart_reap_per", - "impart_two_exp", "stone_num"] - -config_impart = IMPART_BUFF_CONFIG() diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_work/__init__.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_work/__init__.py index edf62221..ddc1a966 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_work/__init__.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_work/__init__.py @@ -1,4 +1,5 @@ import os +import json from typing import Any, Tuple, Dict from nonebot import on_regex, require, on_command from nonebot.params import RegexGroup @@ -9,11 +10,11 @@ GroupMessageEvent, MessageSegment, ) -from ..xiuxian_utils.xiuxian2_handle import XiuxianDateManage, OtherSet +from ..xiuxian_utils.xiuxian2_handle import XiuxianDataManager, OtherSet from .work_handle import workhandle from datetime import datetime from ..xiuxian_utils.xiuxian_opertion import do_is_work -from ..xiuxian_utils.utils import check_user, check_user_type, get_msg_pic +from ..xiuxian_utils.utils import check_user, check_user_type, get_msg_pic, handle_send from nonebot.log import logger from .reward_data_source import PLAYERSDATA from ..xiuxian_utils.item_json import Items @@ -21,9 +22,7 @@ # 定时任务 resetrefreshnum = require("nonebot_plugin_apscheduler").scheduler -work = {} # 悬赏令信息记录 -refreshnum: Dict[str, int] = {} # 用户悬赏令刷新次数记录 -sql_message = XiuxianDateManage() # sql类 + # sql类 items = Items() lscost = 1000000000 # 刷新灵石消耗 count = 3 # 免费次数 @@ -32,8 +31,8 @@ # 重置悬赏令刷新次数 @resetrefreshnum.scheduled_job("cron", hour=0, minute=0) async def resetrefreshnum_(): - sql_message.reset_work_num() - logger.opt(colors=True).info(f"用户悬赏令刷新次数重置成功") + await XiuxianDataManager().reset_work_num() + logger.opt(colors=True).info("用户悬赏令刷新次数重置成功") last_work = on_command("最后的悬赏令", priority=15, block=True) @@ -43,12 +42,12 @@ async def resetrefreshnum_(): permission=GROUP, block=True ) -__work_help__ = f""" +__work_help__ = """ 悬赏令帮助信息: 指令: -1、悬赏令:获取对应实力的悬赏令 +1、悬赏令:获取对应实力的悬赏令(每次随机生成3-5个任务) 2、悬赏令刷新:刷新当前悬赏令,每日免费{count}次 -实力支持:江湖好手|搬血境|洞天境|化灵境|铭纹境|列阵境|尊者境|神火境|真一境|圣祭境|天神境|虚道境|斩我境|遁一境|至尊境|真仙境 +实力支持:江湖好手至真仙境 3、悬赏令终止:终止当前悬赏令任务 4、悬赏令结算:结算悬赏奖励 5、悬赏令接取+编号:接取对应的悬赏令 @@ -59,44 +58,38 @@ async def resetrefreshnum_(): @last_work.handle(parameterless=[Cooldown(stamina_cost = 1, at_sender=False)]) async def last_work_(bot: Bot, event: GroupMessageEvent): bot, send_group_id = await assign_bot(bot=bot, event=event) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await last_work.finish() user_id = user_info['user_id'] user_level = user_info['level'] user_rank = convert_rank(user_level)[0] - is_type, msg = check_user_type(user_id, 2) # 需要在悬赏令中的用户 + is_type, msg = await check_user_type(user_id, 2) # 需要在悬赏令中的用户 if (is_type and user_rank <= 11) or ( - is_type and user_info['exp'] >= sql_message.get_level_power('真仙境圆满')) or ( - is_type and int(user_info['exp']) >= int(OtherSet().set_closing_type(user_level)) * XiuConfig().closing_exp_upper_limit + is_type and user_info['exp'] >= await XiuxianDataManager().get_level_power('真仙境圆满')) or ( + is_type and int(user_info['exp']) >= int(await OtherSet().set_closing_type(user_level)) * XiuConfig().closing_exp_upper_limit ): - user_cd_message = sql_message.get_user_cd(user_id) - work_time = datetime.strptime( - user_cd_message['create_time'], "%Y-%m-%d %H:%M:%S.%f" - ) + user_cd_message = await XiuxianDataManager().get_user_time(user_id) + # 判断create_time是str还是datetime对象 + create_time = user_cd_message['schedule_create_time'] + if isinstance(create_time, str): + work_time = datetime.strptime(create_time, "%Y-%m-%d %H:%M:%S.%") + else: + work_time = create_time exp_time = (datetime.now() - work_time).seconds // 60 # 时长计算 - time2 = workhandle().do_work( - # key=1, name=user_cd_message.scheduled_time 修改点 - key=1, name=user_cd_message['scheduled_time'], level=user_level, exp=user_info['exp'], + time2 = await workhandle().do_work( + key=1, name=user_cd_message['schedule'], level=user_level, exp=user_info['exp'], user_id=user_info['user_id'] ) if exp_time < time2: - msg = f"进行中的悬赏令【{user_cd_message['scheduled_time']}】,预计{time2 - exp_time}分钟后可结束" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = f"进行中的悬赏令【{user_cd_message['schedule']}】,预计{time2 - exp_time}分钟后可结束" + await handle_send(bot, event, send_group_id, msg) await last_work.finish() else: - msg, give_stone, s_o_f, item_id, big_suc = workhandle().do_work( + msg, give_stone, s_o_f, item_id, big_suc = await workhandle().do_work( 2, - work_list=user_cd_message['scheduled_time'], + work_list=user_cd_message['schedule'], level=user_level, exp=user_info['exp'], user_id=user_info['user_id'] @@ -109,34 +102,34 @@ async def last_work_(bot: Bot, event: GroupMessageEvent): item_info = items.get_data_by_item_id(item_id) item_msg = f"{item_info['level']}:{item_info['name']}" if big_suc: # 大成功 - sql_message.update_ls(user_id, give_stone * 2, 1) - sql_message.do_work(user_id, 0) + await XiuxianDataManager().update_ls(user_id, give_stone * 2, 0) + await XiuxianDataManager().do_work(user_id, 0) msg = f"悬赏令结算,{msg}获得报酬{give_stone * 2}枚灵石" # todo 战利品结算sql if item_flag: - sql_message.send_back(user_id, item_id, item_info['name'], item_info['type'], 1) + await XiuxianDataManager().send_back(user_id, item_id, item_info['name'], item_info['type'], 1) msg += f",额外获得奖励:{item_msg}!" else: msg += "!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await last_work.finish() else: - sql_message.update_ls(user_id, give_stone, 1) - sql_message.do_work(user_id, 0) + await XiuxianDataManager().update_ls(user_id, give_stone, 0) + await XiuxianDataManager().do_work(user_id, 0) msg = f"悬赏令结算,{msg}获得报酬{give_stone}枚灵石" if s_o_f: # 普通成功 if item_flag: - sql_message.send_back(user_id, item_id, item_info['name'], item_info['type'], 1) + await XiuxianDataManager().send_back(user_id, item_id, item_info['name'], item_info['type'], 1) msg += f",额外获得奖励:{item_msg}!" else: msg += "!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -145,18 +138,14 @@ async def last_work_(bot: Bot, event: GroupMessageEvent): else: # 失败 msg += "!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await last_work.finish() else: msg = "不满足使用条件!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await last_work.finish() @@ -164,117 +153,89 @@ async def last_work_(bot: Bot, event: GroupMessageEvent): async def do_work_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = RegexGroup()): bot, send_group_id = await assign_bot(bot=bot, event=event) user_level = "仙王境初期" - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await do_work.finish() user_level_sx = user_info['level'] user_id = user_info['user_id'] user_rank = convert_rank(user_info['level'])[0] - sql_message.update_last_check_info_time(user_id) # 更新查看修仙信息时间 - user_cd_message = sql_message.get_user_cd(user_id) - if not os.path.exists(PLAYERSDATA / str(user_id) / "workinfo.json") and user_cd_message['type'] == 2: - sql_message.do_work(user_id, 0) + await XiuxianDataManager().update_last_check_info_time(user_id) # 更新查看修仙信息时间 + user_cd_message = await XiuxianDataManager().get_user_time(user_id) + if not os.path.exists(PLAYERSDATA / str(user_id) / "workinfo.json") and user_cd_message['schedule_type'] == 2: + await XiuxianDataManager().do_work(user_id, 0) msg = "悬赏令已更新,已重置道友的状态!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await do_work.finish() mode = args[0] # 刷新、终止、结算、接取 - if user_rank <= convert_rank('仙王境初期')[0] or user_info['exp'] >= sql_message.get_level_power(user_level): + if user_rank <= convert_rank('仙王境初期')[0] or user_info['exp'] >= await XiuxianDataManager().get_level_power(user_level): msg = "道友的境界已过创业初期,悬赏令已经不能满足道友了!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await do_work.finish() user_level = user_info['level'] - if int(user_info['exp']) >= int(OtherSet().set_closing_type(user_level)) * XiuConfig().closing_exp_upper_limit: + if int(user_info['exp']) >= int(await OtherSet().set_closing_type(user_level)) * XiuConfig().closing_exp_upper_limit: # 获取下个境界需要的修为 * 1.5为闭关上限 msg = "道友的修为已经到达上限,悬赏令已无法再获得经验!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await do_work.finish() - if user_cd_message['type'] == 1: + if user_cd_message['schedule_type'] == 1: msg = "已经在闭关中,请输入【出关】结束后才能获取悬赏令!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await do_work.finish() - if user_cd_message['type'] == 3: + if user_cd_message['schedule_type'] == 3: msg = "道友在秘境中,请等待结束后才能获取悬赏令!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await do_work.finish() if mode is None: # 接取逻辑 - if (user_cd_message['scheduled_time'] is None) or (user_cd_message['type'] == 0): - try: - msg = work[user_id].msg - except KeyError: + if (user_cd_message['schedule'] is None) or (user_cd_message['schedule_type'] == 0): + # 从数据库获取 + work_info = await XiuxianDataManager().get_work_info(user_id) + if work_info: + msg = work_info['work_msg'] + else: msg = "没有查到你的悬赏令信息呢,请刷新!" - elif user_cd_message['type'] == 2: - work_time = datetime.strptime( - user_cd_message['create_time'], "%Y-%m-%d %H:%M:%S.%f" - ) + elif user_cd_message['schedule_type'] == 2: + # 判断create_time是str还是datetime对象 + create_time = user_cd_message['schedule_create_time'] + if isinstance(create_time, str): + work_time = datetime.strptime(create_time, "%Y-%m-%d %H:%M:%S.%") + else: + work_time = create_time exp_time = (datetime.now() - work_time).seconds // 60 # 时长计算 - time2 = workhandle().do_work(key=1, name=user_cd_message['scheduled_time'], user_id=user_info['user_id']) + time2 = await workhandle().do_work(key=1, name=user_cd_message['schedule'], user_id=user_info['user_id']) if exp_time < time2: - msg = f"进行中的悬赏令【{user_cd_message['scheduled_time']}】,预计{time2 - exp_time}分钟后可结束" + msg = f"进行中的悬赏令【{user_cd_message['schedule']}】,预计{time2 - exp_time}分钟后可结束" else: - msg = f"进行中的悬赏令【{user_cd_message['scheduled_time']}】,已结束,请输入【悬赏令结算】结算任务信息!" + msg = f"进行中的悬赏令【{user_cd_message['schedule']}】,已结束,请输入【悬赏令结算】结算任务信息!" else: msg = "状态未知错误!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await do_work.finish() if mode == "刷新": # 刷新逻辑 stone_use = 0 #悬赏令刷新提示是否扣灵石 - if user_cd_message['type'] == 2: - work_time = datetime.strptime( - user_cd_message['create_time'], "%Y-%m-%d %H:%M:%S.%f" - ) + if user_cd_message['schedule_type'] == 2: + # 判断create_time是str还是datetime对象 + create_time = user_cd_message['schedule_create_time'] + if isinstance(create_time, str): + work_time = datetime.strptime(create_time, "%Y-%m-%d %H:%M:%S.%") + else: + work_time = create_time exp_time = (datetime.now() - work_time).seconds // 60 - time2 = workhandle().do_work(key=1, name=user_cd_message['scheduled_time'], user_id=user_info['user_id']) + time2 = await workhandle().do_work(key=1, name=user_cd_message['schedule'], user_id=user_info['user_id']) if exp_time < time2: - msg = f"进行中的悬赏令【{user_cd_message['scheduled_time']}】,预计{time2 - exp_time}分钟后可结束" + msg = f"进行中的悬赏令【{user_cd_message['schedule']}】,预计{time2 - exp_time}分钟后可结束" else: - msg = f"进行中的悬赏令【{user_cd_message['scheduled_time']}】,已结束,请输入【悬赏令结算】结算任务信息!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + msg = f"进行中的悬赏令【{user_cd_message['schedule']}】,已结束,请输入【悬赏令结算】结算任务信息!" + await handle_send(bot, event, send_group_id, msg) await do_work.finish() - usernums = sql_message.get_work_num(user_id) + usernums = await XiuxianDataManager().get_work_num(user_id) - isUser, user_info, msg = check_user(event) + isUser, user_info, msg = await check_user(event) if not isUser: - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await do_work.finish() + await handle_send(bot, event, send_group_id, msg) + await do_work.finish() freenum = count - usernums - 1 if freenum < 0: @@ -282,19 +243,19 @@ async def do_work_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = R if int(user_info['stone']) < int(lscost / convert_rank(user_level_sx)[0]): msg = f"道友的灵石不足以刷新,下次刷新消耗灵石:{int(lscost / convert_rank(user_level_sx)[0])}枚" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await do_work.finish() else: - sql_message.update_ls(user_id, int(lscost / convert_rank(user_level_sx)[0]) , 2) + await XiuxianDataManager().update_ls(user_id, int(lscost / convert_rank(user_level_sx)[0]) , 1) stone_use = 1 - work_msg = workhandle().do_work(0, level=user_level, exp=user_info['exp'], user_id=user_id) + work_msg = await workhandle().do_work(0, level=user_level, exp=user_info['exp'], user_id=user_id) n = 1 work_list = [] - work_msg_f = f"☆------道友的个人悬赏令------☆\n" + work_msg_f = "☆------道友的个人悬赏令------☆\n" for i in work_msg: work_list.append([i[0], i[3]]) work_msg_f += f"{n}、{get_work_msg(i)}" @@ -302,63 +263,54 @@ async def do_work_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = R work_msg_f += f"(悬赏令每日免费刷新次数:{count},超过{count}次后,下次刷新消耗灵石{int(lscost / convert_rank(user_level_sx)[0])},今日可免费刷新次数:{freenum}次)" if int(stone_use) == 1: work_msg_f += f"\n道友消耗灵石{int(lscost / convert_rank(user_level_sx)[0])}枚,成功刷新悬赏令" - work[user_id] = do_is_work(user_id) - work[user_id].msg = work_msg_f - work[user_id].world = work_list - sql_message.update_work_num(user_id, usernums + 1) - msg = work[user_id].msg - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + + # 保存到数据库 + await XiuxianDataManager().save_work_info(user_id, work_msg_f, work_list) + await XiuxianDataManager().update_work_num(user_id, usernums + 1) + msg = work_msg_f + await handle_send(bot, event, send_group_id, msg) await do_work.finish() elif mode == "终止": - is_type, msg = check_user_type(user_id, 2) # 需要在悬赏令中的用户 + is_type, msg = await check_user_type(user_id, 2) # 需要在悬赏令中的用户 if is_type: stone = 4000000 - sql_message.update_ls(user_id, stone, 2) - sql_message.do_work(user_id, 0) + await XiuxianDataManager().update_ls(user_id, stone, 1) + await XiuxianDataManager().do_work(user_id, 0) msg = f"道友不讲诚信,被打了一顿灵石减少{stone},悬赏令已终止!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await do_work.finish() else: msg = "没有查到你的悬赏令信息呢,请刷新!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await do_work.finish() elif mode == "结算": - is_type, msg = check_user_type(user_id, 2) # 需要在悬赏令中的用户 + is_type, msg = await check_user_type(user_id, 2) # 需要在悬赏令中的用户 if is_type: - user_cd_message = sql_message.get_user_cd(user_id) - work_time = datetime.strptime( - user_cd_message['create_time'], "%Y-%m-%d %H:%M:%S.%f" - ) + user_cd_message = await XiuxianDataManager().get_user_time(user_id) + # 判断create_time是str还是datetime对象 + create_time = user_cd_message['schedule_create_time'] + if isinstance(create_time, str): + work_time = datetime.strptime(create_time, "%Y-%m-%d %H:%M:%S.%") + else: + work_time = create_time exp_time = (datetime.now() - work_time).seconds // 60 # 时长计算 - time2 = workhandle().do_work( - key=1, name=user_cd_message['scheduled_time'], level=user_level, exp=user_info['exp'], + time2 = await workhandle().do_work( + key=1, name=user_cd_message['schedule'], level=user_level, exp=user_info['exp'], user_id=user_info['user_id'] ) if exp_time < time2: - msg = f"进行中的悬赏令【{user_cd_message['scheduled_time']}】,预计{time2 - exp_time}分钟后可结束" + msg = f"进行中的悬赏令【{user_cd_message['schedule']}】,预计{time2 - exp_time}分钟后可结束" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await do_work.finish() else: - msg, give_exp, s_o_f, item_id, big_suc = workhandle().do_work(2, - work_list=user_cd_message['scheduled_time'], + msg, give_exp, s_o_f, item_id, big_suc = await workhandle().do_work(2, + work_list=user_cd_message['schedule'], level=user_level, exp=user_info['exp'], user_id=user_info['user_id']) @@ -370,34 +322,34 @@ async def do_work_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = R item_info = items.get_data_by_item_id(item_id) item_msg = f"{item_info['level']}:{item_info['name']}" if big_suc: # 大成功 - sql_message.update_exp(user_id, give_exp * 2) - sql_message.do_work(user_id, 0) + await XiuxianDataManager().update_exp(user_id, give_exp * 2, 0) + await XiuxianDataManager().do_work(user_id, 0) msg = f"悬赏令结算,{msg}增加修为{give_exp * 2}" # todo 战利品结算sql if item_flag: - sql_message.send_back(user_id, item_id, item_info['name'], item_info['type'], 1) + await XiuxianDataManager().send_back(user_id, item_id, item_info['name'], item_info['type'], 1) msg += f",额外获得奖励:{item_msg}!" else: msg += "!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await do_work.finish() else: - sql_message.update_exp(user_id, give_exp) - sql_message.do_work(user_id, 0) + await XiuxianDataManager().update_exp(user_id, give_exp, 0) + await XiuxianDataManager().do_work(user_id, 0) msg = f"悬赏令结算,{msg}增加修为{give_exp}" if s_o_f: # 普通成功 if item_flag: - sql_message.send_back(user_id, item_id, item_info['name'], item_info['type'], 1) + await XiuxianDataManager().send_back(user_id, item_id, item_info['name'], item_info['type'], 1) msg += f",额外获得奖励:{item_msg}!" else: msg += "!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) @@ -406,72 +358,92 @@ async def do_work_(bot: Bot, event: GroupMessageEvent, args: Tuple[Any, ...] = R else: # 失败 msg += "!" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await do_work.finish() else: msg = "没有查到你的悬赏令信息呢,请刷新!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await do_work.finish() elif mode == "接取": num = args[1] - is_type, msg = check_user_type(user_id, 0) # 需要无状态的用户 + is_type, msg = await check_user_type(user_id, 0) # 需要无状态的用户 if is_type: # 接取逻辑 if num is None or str(num) not in ['1', '2', '3']: msg = '请输入正确的任务序号' if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await do_work.finish() - work_num = 1 - try: - if work[user_id]: - work_num = int(num) # 任务序号 + + # 从数据库获取悬赏令信息 + work_info = await XiuxianDataManager().get_work_info(user_id) + + if work_info is not None: + # 数据库中有记录 + work_list = json.loads(work_info['work_list']) + work_num = int(num) # 任务序号 + try: - get_work = work[user_id].world[work_num - 1] - sql_message.do_work(user_id, 2, get_work[0]) - del work[user_id] + get_work = work_list[work_num - 1] + await XiuxianDataManager().do_work(user_id, 2, get_work[0]) + # 删除数据库中的悬赏令信息 + await XiuxianDataManager().delete_work_info(user_id) + msg = f"接取任务【{get_work[0]}】成功" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await do_work.finish() - except IndexError: msg = "没有这样的任务" if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) + await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) + else: + await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await do_work.finish() + else: + try: + if user_id in work_list: + work_num = int(num) # 任务序号 + try: + get_work = work_list[work_num - 1] + await XiuxianDataManager().do_work(user_id, 2, get_work[0]) + await XiuxianDataManager().delete_work_info(user_id) + msg = f"接取任务【{get_work[0]}】成功" + if XiuConfig().img: + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) + await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) + else: + await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await do_work.finish() + except IndexError: + msg = "没有这样的任务" + if XiuConfig().img: + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) + await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) + else: + await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await do_work.finish() + except KeyError: + msg = "没有查到你的悬赏令信息呢,请刷新!" + if XiuConfig().img: + pic = await get_msg_pic(f"@{user_info['user_name'] or event.sender.nickname}\n" + msg) await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) else: await bot.send_group_msg(group_id=int(send_group_id), message=msg) await do_work.finish() - - except KeyError: - msg = "没有查到你的悬赏令信息呢,请刷新!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) - await do_work.finish() else: msg = "没有查到你的悬赏令信息呢,请刷新!" - if XiuConfig().img: - pic = await get_msg_pic(f"@{event.sender.nickname}\n" + msg) - await bot.send_group_msg(group_id=int(send_group_id), message=MessageSegment.image(pic)) - else: - await bot.send_group_msg(group_id=int(send_group_id), message=msg) + await handle_send(bot, event, send_group_id, msg) await do_work.finish() elif mode == "帮助": diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_work/reward_data_source.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_work/reward_data_source.py index 3d626ba3..3d5a01c4 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_work/reward_data_source.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_work/reward_data_source.py @@ -1,12 +1,14 @@ import os +import json +from pathlib import Path from nonebot.log import logger -from ..xiuxian_utils.data_source import * +from ..xiuxian_utils.data_source import JsonData WORKDATA = Path() / "data" / "xiuxian" / "work" -class reward(JsonDate): +class reward(JsonData): def __init__(self): super().__init__() @@ -60,7 +62,7 @@ def savef(user_id, data): user_id = str(user_id) if not os.path.exists(PLAYERSDATA / user_id): - logger.opt(colors=True).info(f"用户目录不存在,创建目录") + logger.opt(colors=True).info("用户目录不存在,创建目录") os.makedirs(PLAYERSDATA / user_id) FILEPATH = PLAYERSDATA / user_id / "workinfo.json" diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_work/work_handle.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_work/work_handle.py index 0edf6c07..c823022e 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_work/work_handle.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_work/work_handle.py @@ -1,16 +1,17 @@ -from ..xiuxian_utils.xiuxian2_handle import * -from .workmake import * -from ..xiuxian_utils.xiuxian2_handle import XiuxianDateManage +import json +import random +from ..xiuxian_utils.xiuxian2_handle import XiuxianJsonData +from .workmake import workmake +from ..xiuxian_utils.xiuxian2_handle import XiuxianDataManager from ..xiuxian_utils.item_json import Items +from .reward_data_source import savef, readf -sql_message = XiuxianDateManage() # sql类 +class workhandle(XiuxianJsonData): -class workhandle(XiuxianJsonDate): - - def do_work(self, key, work_list=None, name=None, level="江湖好手", exp=None, user_id=None): + async def do_work(self, key, work_list=None, name=None, level="江湖好手", exp=None, user_id=None): """悬赏令获取""" if key == 0: # 如果没有获取过,则返回悬赏令 - data = workmake(level, exp, sql_message.get_user_info_with_id(user_id)['level']) + data = workmake(level, exp, (await XiuxianDataManager().get_user_infos_by_ids(user_id))['level']) get_work_list = [] for k, v in data.items(): if v[3] == 0: @@ -26,7 +27,7 @@ def do_work(self, key, work_list=None, name=None, level="江湖好手", exp=None try: data = readf(user_id) return data[name][2] - except: + except ValueError: pass elif key == 2: # 如果是结算,则获取结果 @@ -44,4 +45,4 @@ def do_work(self, key, work_list=None, name=None, level="江湖好手", exp=None if random.randint(1, 100) <= data[work_list][0]: return success_msg, data[work_list][1], True, item_id, bigsuc else: - return fail_msg, int(data[work_list][1] / 2), False, 0, bigsuc + return fail_msg, int(data[work_list][1] / 2), False, 0, bigsuc \ No newline at end of file diff --git a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_work/workmake.py b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_work/workmake.py index 5a57e8d4..4432e7b1 100755 --- a/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_work/workmake.py +++ b/nonebot_plugin_xiuxian_2/xiuxian/xiuxian_work/workmake.py @@ -1,4 +1,4 @@ -from .reward_data_source import * +from .reward_data_source import reward import random from ..xiuxian_utils.item_json import Items from ..xiuxian_config import convert_rank @@ -58,7 +58,7 @@ def get_random_item_type(): for i, v in type_rate.items(): try: temp_dict[i] = v["type_rate"] - except: + except ValueError: continue key = [OtherSet().calculated(temp_dict)] return key @@ -74,7 +74,7 @@ def countrate(exp, needexp): r = exp / needexp * 100 if r > 100: tp += 1 - exp /= 1.5 + exp = float(exp) / 1.5 else: flag = False @@ -82,4 +82,4 @@ def countrate(exp, needexp): isOut = float(1 - tp * 0.05) if isOut < 0.5: isOut = 0.5 - return rate, round(isOut, 2) + return rate, round(isOut, 2) \ No newline at end of file