refactor code

This commit is contained in:
hibiki
2021-07-30 21:21:51 +08:00
parent 2ad891aa1e
commit cc24822dca
165 changed files with 7815 additions and 8174 deletions
+55 -60
View File
@@ -2,7 +2,7 @@ from nonebot import on_command
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent, MessageEvent
from nonebot.typing import T_State
from configs.path_config import IMAGE_PATH
from utils.init_result import image
from utils.message_builder import image
from .data_source import create_shop_help, add_goods, del_goods, update_goods
from nonebot.permission import SUPERUSER
from utils.utils import get_message_text, is_number
@@ -11,73 +11,72 @@ import os
import time
__plugin_name__ = '商店'
__plugin_name__ = "商店"
shop_help = on_command("商店", priority=5, block=True)
shop_add_goods = on_command('添加商品', priority=5, permission=SUPERUSER, block=True)
shop_add_goods = on_command("添加商品", priority=5, permission=SUPERUSER, block=True)
shop_del_goods = on_command('删除商品', priority=5, permission=SUPERUSER, block=True)
shop_del_goods = on_command("删除商品", priority=5, permission=SUPERUSER, block=True)
shop_update_goods = on_command('修改商品', priority=5, permission=SUPERUSER, block=True)
shop_update_goods = on_command("修改商品", priority=5, permission=SUPERUSER, block=True)
@shop_help.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if not os.path.exists(f'{IMAGE_PATH}/shop_help.png'):
if not os.path.exists(f"{IMAGE_PATH}/shop_help.png"):
await create_shop_help()
await shop_help.send(image('shop_help.png'))
await shop_help.send(image("shop_help.png"))
@shop_add_goods.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json())
if msg:
msg = msg.split('-')
msg = msg.split("-")
if len(msg) < 3:
await shop_add_goods.finish('商品参数不完全...', at_sender=True)
await shop_add_goods.finish("商品参数不完全...", at_sender=True)
if not is_number(msg[1]):
await shop_add_goods.finish('商品的价格必须是合法数字!', at_sender=True)
await shop_add_goods.finish("商品的价格必须是合法数字!", at_sender=True)
msg[1] = int(msg[1])
if len(msg) > 3:
if not is_number(msg[3]):
await shop_add_goods.finish('商品的折扣要小数啊!', at_sender=True)
await shop_add_goods.finish("商品的折扣要小数啊!", at_sender=True)
msg[3] = float(msg[3])
if len(msg) > 4:
if not is_number(msg[4]):
await shop_add_goods.finish('商品的限时时间是要写多少分钟噢!', at_sender=True)
await shop_add_goods.finish("商品的限时时间是要写多少分钟噢!", at_sender=True)
msg[4] = time.time() + int(msg[4]) * 60
if await add_goods(msg):
await shop_add_goods.send(f'添加商品 {msg[0]} 成功...', at_sender=True)
if os.path.exists(f'{IMAGE_PATH}/shop_help.png'):
os.remove(f'{IMAGE_PATH}/shop_help.png')
logger.info(f'USER {event.user_id} 上传商品 {msg} 成功')
await shop_add_goods.send(f"添加商品 {msg[0]} 成功...", at_sender=True)
if os.path.exists(f"{IMAGE_PATH}/shop_help.png"):
os.remove(f"{IMAGE_PATH}/shop_help.png")
logger.info(f"USER {event.user_id} 上传商品 {msg} 成功")
else:
await shop_add_goods.send(f'添加商品 {msg[0]} 失败了...', at_sender=True)
logger.warning(f'USER {event.user_id} 上传商品 {msg} 失败')
await shop_add_goods.send(f"添加商品 {msg[0]} 失败了...", at_sender=True)
logger.warning(f"USER {event.user_id} 上传商品 {msg} 失败")
@shop_del_goods.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json())
if msg:
name = ''
name = ""
id_ = 0
if is_number(msg):
id_ = int(msg)
else:
name = msg
rst, goods_name, code = await del_goods(name, id_)
await shop_del_goods.send(rst, at_sender=True)
if code == 200:
await shop_del_goods.send(f'删除商品 {goods_name} 成功了...', at_sender=True)
if os.path.exists(f'{IMAGE_PATH}/shop_help.png'):
os.remove(f'{IMAGE_PATH}/shop_help.png')
logger.info(f'USER {event.user_id} 删除商品 {goods_name} 成功')
await shop_del_goods.send(f"删除商品 {goods_name} 成功了...", at_sender=True)
if os.path.exists(f"{IMAGE_PATH}/shop_help.png"):
os.remove(f"{IMAGE_PATH}/shop_help.png")
logger.info(f"USER {event.user_id} 删除商品 {goods_name} 成功")
else:
await shop_del_goods.send(f'删除商品 {goods_name} 失败了...', at_sender=True)
logger.info(f'USER {event.user_id} 删除商品 {goods_name} 失败')
await shop_del_goods.send(f"删除商品 {goods_name} 失败了...", at_sender=True)
logger.info(f"USER {event.user_id} 删除商品 {goods_name} 失败")
@shop_update_goods.handle()
@@ -85,41 +84,37 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json())
if msg:
tmp = {}
msg = msg.split('-')
msg = msg.split("-")
for x in msg:
if x.find('name') != -1:
tmp['name'] = x.split(' ')[1].strip()
elif x.find('price') != -1:
tmp['price'] = x.split(' ')[1].strip()
if not is_number(tmp['price']):
await shop_update_goods.finish('价格必须是数字啊!', at_sender=True)
tmp['price'] = int(tmp['price'])
elif x.find('des') != -1:
tmp['des'] = x.split(' ')[1].strip()
elif x.find('discount') != -1:
tmp['discount'] = x.split(' ')[1].strip()
if not is_number(tmp['discount']):
await shop_update_goods.finish('折扣必须是数字啊!', at_sender=True)
tmp['discount'] = float(tmp['discount'])
elif x.find('time') != -1:
tmp['time'] = x.split(' ')[1].strip()
if not is_number(tmp['time']):
await shop_update_goods.finish('限时时间必须是数字啊!', at_sender=True)
tmp['time'] = time.time() + tmp['time'] * 60
if not tmp.get('name'):
await shop_update_goods.finish('未指定商品名称(序号也可)!', at_sender=True)
if is_number(tmp['name']):
tmp['name'] = int(tmp['name'])
if x.find("name") != -1:
tmp["name"] = x.split(" ")[1].strip()
elif x.find("price") != -1:
tmp["price"] = x.split(" ")[1].strip()
if not is_number(tmp["price"]):
await shop_update_goods.finish("价格必须是数字啊!", at_sender=True)
tmp["price"] = int(tmp["price"])
elif x.find("des") != -1:
tmp["des"] = x.split(" ")[1].strip()
elif x.find("discount") != -1:
tmp["discount"] = x.split(" ")[1].strip()
if not is_number(tmp["discount"]):
await shop_update_goods.finish("折扣必须是数字啊!", at_sender=True)
tmp["discount"] = float(tmp["discount"])
elif x.find("time") != -1:
tmp["time"] = x.split(" ")[1].strip()
if not is_number(tmp["time"]):
await shop_update_goods.finish("限时时间必须是数字啊!", at_sender=True)
tmp["time"] = time.time() + tmp["time"] * 60
if not tmp.get("name"):
await shop_update_goods.finish("未指定商品名称(序号也可)!", at_sender=True)
if is_number(tmp["name"]):
tmp["name"] = int(tmp["name"])
flag, name, text = await update_goods(tmp)
if flag:
await shop_update_goods.send(f'修改商品 {name} 成功了...\n{text}', at_sender=True)
if os.path.exists(f'{IMAGE_PATH}/shop_help.png'):
os.remove(f'{IMAGE_PATH}/shop_help.png')
logger.info(f'USER {event.user_id} 修改商品 {name} 数据 {tmp} 成功')
await shop_update_goods.send(f"修改商品 {name} 成功了...\n{text}", at_sender=True)
if os.path.exists(f"{IMAGE_PATH}/shop_help.png"):
os.remove(f"{IMAGE_PATH}/shop_help.png")
logger.info(f"USER {event.user_id} 修改商品 {name} 数据 {tmp} 成功")
else:
await shop_update_goods.send(f'修改商品 {name} 失败了...', at_sender=True)
logger.info(f'USER {event.user_id} 修改商品 {name} 数据 {tmp} 失败')
await shop_update_goods.send(f"修改商品 {name} 失败了...", at_sender=True)
logger.info(f"USER {event.user_id} 修改商品 {name} 数据 {tmp} 失败")
+70 -46
View File
@@ -1,99 +1,123 @@
from models.goods_info import GoodsInfo
from utils.img_utils import CreateImg
from utils.image_utils import CreateImg
from utils.utils import is_number
from configs.path_config import IMAGE_PATH
from configs.config import IMPORT_DEFAULT_SHOP_GOODS
from nonebot import Driver
import nonebot
import time
driver: Driver = nonebot.get_driver()
# 导入内置商品
@driver.on_startup
async def init_default_shop_goods():
if IMPORT_DEFAULT_SHOP_GOODS:
await add_goods(["好感度双倍加持卡Ⅰ", 30, "下次签到双倍好感度概率 + 10%(谁才是真命天子?)(同类商品将覆盖)"])
await add_goods(["好感度双倍加持卡Ⅱ", 150, "下次签到双倍好感度概率 + 20%(平平庸庸)(同类商品将覆盖)"])
await add_goods(["好感度双倍加持卡Ⅲ", 250, "下次签到双倍好感度概率 + 30%(金币才是真命天子!)(同类商品将覆盖)"])
# 创建商店界面
async def create_shop_help():
goods_lst = await GoodsInfo.get_all_goods()
tmp = ''
tmp = ""
idx = 1
for goods in goods_lst:
tmp += f'{idx}.{goods.goods_name}\t\t售价:{goods.goods_price}金币\n' \
f'\t\t{goods.goods_description}\n'
tmp += (
f"{idx}.{goods.goods_name}\t\t售价:{goods.goods_price}金币\n"
f"\t\t{goods.goods_description}\n"
)
idx += 1
w = 1000
h = 400 + len(goods_lst) * 40
h = 1000 if h < 1000 else h
shop_logo = CreateImg(100, 100, background=f'{IMAGE_PATH}/other/shop_text.png')
shop_logo = CreateImg(100, 100, background=f"{IMAGE_PATH}/other/shop_text.png")
shop = CreateImg(w, h, font_size=20)
zhenxun_img = CreateImg(525, 581, background=f'{IMAGE_PATH}/zhenxun/toukan_2.png')
zhenxun_img = CreateImg(525, 581, background=f"{IMAGE_PATH}/zhenxun/toukan_2.png")
shop.paste(zhenxun_img, (780, 100))
shop.paste(shop_logo, (450, 30), True)
shop.text((int((1000 - shop.getsize('注【通过 序号 或者 商品名称 购买】')[0]) / 2), 170), '注【通过 序号 或者 商品名称 购买】')
shop.text(
(int((1000 - shop.getsize("注【通过 序号 或者 商品名称 购买】")[0]) / 2), 170),
"注【通过 序号 或者 商品名称 购买】",
)
shop.text((20, 230), tmp[:-1])
shop.text((20, h - 100), '神秘药水\t\t售价:9999999金币\n\t\t鬼知道会有什么效果~')
shop.save(f'{IMAGE_PATH}/shop_help.png')
shop.text((20, h - 100), "神秘药水\t\t售价:9999999金币\n\t\t鬼知道会有什么效果~")
shop.save(f"{IMAGE_PATH}/shop_help.png")
# 添加商品
async def add_goods(msg: list):
data = {
'名称': None,
'价格': None,
'描述': None,
'折扣': 1,
'限时': 0,
"名称": None,
"价格": None,
"描述": None,
"折扣": 1,
"限时": 0,
}
keys = list(data.keys())
idx = 0
for x in msg:
data[keys[idx]] = x
idx += 1
return await GoodsInfo.add_goods(data['名称'], data['价格'], data['描述'], data['折扣'], data['限时'])
return await GoodsInfo.add_goods(
data["名称"], data["价格"], data["描述"], data["折扣"], data["限时"]
)
# 删除商品
async def del_goods(name: str, id_: int):
goods_lst = await GoodsInfo.get_all_goods()
if id_:
if id_ < 1 or id_ > len(goods_lst):
return '序号错误,没有该序号商品...', '', 999
return "序号错误,没有该序号商品...", "", 999
goods_name = goods_lst[id_ - 1].goods_name
if await GoodsInfo.del_goods(goods_name):
return f'删除商品 {goods_name} 成功!', goods_name, 200
if await GoodsInfo.delete_goods(goods_name):
return f"删除商品 {goods_name} 成功!", goods_name, 200
else:
return f'删除商品 {goods_name} 失败!', goods_name, 999
return f"删除商品 {goods_name} 失败!", goods_name, 999
if name:
if await GoodsInfo.del_goods(name):
return f'删除商品 {name} 成功!', name, 200
if await GoodsInfo.delete_goods(name):
return f"删除商品 {name} 成功!", name, 200
else:
return f'删除商品 {name} 失败!', name, 999
return f"删除商品 {name} 失败!", name, 999
# 更新商品信息
async def update_goods(data: dict):
goods_lst = await GoodsInfo.get_all_goods()
if is_number(data['name']):
if data['name'] < 1 or data['name'] > len(goods_lst):
return '序号错误,没有该序号的商品...', '', 999
goods = goods_lst[data['name'] - 1]
if is_number(data["name"]):
if data["name"] < 1 or data["name"] > len(goods_lst):
return "序号错误,没有该序号的商品...", "", 999
goods = goods_lst[data["name"] - 1]
else:
goods = await GoodsInfo.get_goods_info(data['name'])
goods = await GoodsInfo.get_goods_info(data["name"])
if not goods:
return '名称错误,没有该名称的商品...', '', 999
return "名称错误,没有该名称的商品...", "", 999
name = goods.goods_name
price = goods.goods_price
des = goods.goods_description
discount = goods.goods_discount
limit_time = goods.goods_limit_time
tmp = ''
if data.get('price'):
tmp = ""
if data.get("price"):
tmp += f'价格:{price} --> {data["price"]}\n'
price = data['price']
if data.get('des'):
price = data["price"]
if data.get("des"):
tmp += f'描述:{des} --> {data["des"]}\n'
des = data['des']
if data.get('discount'):
des = data["des"]
if data.get("discount"):
tmp += f'折扣:{discount} --> {data["discount"]}\n'
discount = data['discount']
if data.get('time'):
discount = data["discount"]
if data.get("time"):
old_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(limit_time))
new_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(data['time']))
tmp += f'折扣:{old_time} --> {new_time}\n'
limit_time = data['time']
return await GoodsInfo.update_goods(name, price, des, discount, limit_time), name, tmp[:-1]
new_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(data["time"]))
tmp += f"折扣:{old_time} --> {new_time}\n"
limit_time = data["time"]
return (
await GoodsInfo.update_goods(name, price, des, discount, limit_time),
name,
tmp[:-1],
)