update 0.0.6.0

This commit is contained in:
HibiKier
2021-11-04 16:11:50 +08:00
parent 21c1950898
commit 19d650c35d
217 changed files with 8213 additions and 5697 deletions
+15
View File
@@ -8,6 +8,7 @@ from nonebot.adapters.cqhttp import Bot, GroupMessageEvent, MessageEvent
from nonebot.permission import SUPERUSER
import random
from nonebot.plugin import MatcherGroup
from configs.path_config import IMAGE_PATH
import re
from .open_cases_c import (
open_case,
@@ -68,6 +69,20 @@ __plugin_settings__ = {
}
__plugin_task__ = {"open_case_reset_remind": "每日开箱重置提醒"}
__plugin_cd_limit__ = {"rst": "着什么急啊,慢慢来!"}
__plugin_resources__ = {f"cases": IMAGE_PATH}
__plugin_configs__ = {
"INITIAL_OPEN_CASE_COUNT": {"value": 20, "help": "初始每日开箱次数", "default_value": 20},
"EACH_IMPRESSION_ADD_COUNT": {
"value": 3,
"help": "每 * 点好感度额外增加开箱次数",
"default_value": 3,
},
"COOKIE": {
"value": None,
"help": "BUFF的cookie",
},
"BUFF_PROXY": {"value": None, "help": "使用代理访问BUFF"},
}
cases_name = ["狂牙大行动", "突围大行动", "命悬一线", "裂空", "光谱"]
+2
View File
@@ -0,0 +1,2 @@
from .open_cases_user import *
from .buff_prices import *
+35
View File
@@ -0,0 +1,35 @@
from datetime import datetime
from services.db_context import db
# 1.狂牙武器箱
class BuffPrice(db.Model):
__tablename__ = 'buff_prices'
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer(), primary_key=True)
case_id = db.Column(db.Integer(), nullable=False)
skin_name = db.Column(db.Unicode(), nullable=False)
skin_price = db.Column(db.Float(), nullable=False)
update_date = db.Column(db.DateTime(), nullable=False)
_idx1 = db.Index('buff_price_idx1', 'skin_name', unique=True)
@classmethod
async def ensure(cls, skin_name: str, for_update: bool = False) -> 'BuffPrice':
query = cls.query.where(
(cls.skin_name == skin_name)
)
if for_update:
query = query.with_for_update()
user = await query.gino.first()
return user or await cls.create(
case_id=1,
skin_name=skin_name,
skin_price=0,
update_date=datetime.min,
)
@@ -0,0 +1,60 @@
from datetime import datetime
from services.db_context import db
class OpenCasesUser(db.Model):
__tablename__ = 'open_cases_users'
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer(), primary_key=True)
user_qq = db.Column(db.BigInteger(), nullable=False)
belonging_group = db.Column(db.BigInteger(), nullable=False)
total_count = db.Column(db.Integer(), nullable=False, default=0)
blue_count = db.Column(db.Integer(), nullable=False, default=0)
blue_st_count = db.Column(db.Integer(), nullable=False, default=0)
purple_count = db.Column(db.Integer(), nullable=False, default=0)
purple_st_count = db.Column(db.Integer(), nullable=False, default=0)
pink_count = db.Column(db.Integer(), nullable=False, default=0)
pink_st_count = db.Column(db.Integer(), nullable=False, default=0)
red_count = db.Column(db.Integer(), nullable=False, default=0)
red_st_count = db.Column(db.Integer(), nullable=False, default=0)
knife_count = db.Column(db.Integer(), nullable=False, default=0)
knife_st_count = db.Column(db.Integer(), nullable=False, default=0)
spend_money = db.Column(db.Integer(), nullable=False, default=0)
make_money = db.Column(db.Float(), nullable=False, default=0)
today_open_total = db.Column(db.Integer(), nullable=False, default=0)
open_cases_time_last = db.Column(db.DateTime(timezone=True), nullable=False, default=datetime.now())
knifes_name = db.Column(db.Unicode(), nullable=False, default="")
_idx1 = db.Index('open_cases_group_users_idx1', 'user_qq', 'belonging_group', unique=True)
@classmethod
async def ensure(cls, user_qq: int, belonging_group: int, for_update: bool = False) -> 'OpenCasesUser':
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.belonging_group == belonging_group)
)
if for_update:
query = query.with_for_update()
user = await query.gino.first()
return user or await cls.create(
user_qq=user_qq,
belonging_group=belonging_group,
)
@classmethod
async def get_user_all(cls, group_id: int = None) -> 'list':
user_list = []
if not group_id:
query = await cls.query.gino.all()
else:
query = await cls.query.where(
(cls.belonging_group == group_id)
).gino.all()
for user in query:
user_list.append(user)
return user_list
+165 -115
View File
@@ -2,39 +2,40 @@ from datetime import datetime, timedelta
from .config import *
from services.log import logger
from services.db_context import db
from models.open_cases_user import OpenCasesUser
from .models.open_cases_user import OpenCasesUser
from models.sign_group_user import SignGroupUser
from utils.message_builder import image
import pypinyin
import random
from .utils import get_price
from models.buff_price import BuffPrice
from .models.buff_prices import BuffPrice
from PIL import Image
from utils.image_utils import alpha2white_pil, CreateImg
from configs.path_config import IMAGE_PATH
import asyncio
from utils.utils import cn2py
from configs.config import INITIAL_OPEN_CASE_COUNT
MAX_COUNT = INITIAL_OPEN_CASE_COUNT
from configs.config import Config
async def open_case(user_qq: int, group: int, case_name: str = "狂牙大行动") -> str:
if case_name not in ["狂牙大行动", "突围大行动", "命悬一线", '裂空', '光谱']:
if case_name not in ["狂牙大行动", "突围大行动", "命悬一线", "裂空", "光谱"]:
return "武器箱未收录"
knifes_flag = False
# lan zi fen hong jin price
uplist = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0]
case = ""
for i in pypinyin.pinyin(case_name, style=pypinyin.NORMAL):
case += ''.join(i)
case += "".join(i)
impression = (await SignGroupUser.ensure(user_qq, group)).impression
rand = random.random()
async with db.transaction():
user = await OpenCasesUser.ensure(user_qq, group, for_update=True)
# 一天次数上限
if user.today_open_total == int(MAX_COUNT + int(impression) / 3):
if user.today_open_total == int(
Config.get_config("open_cases", "INITIAL_OPEN_CASE_COUNT")
+ int(impression)
/ Config.get_config("open_cases", "EACH_IMPRESSION_ADD_COUNT")
):
return _handle_is_MAX_COUNT()
skin, mosun = get_color_quality(rand, case_name)
# 调侃
@@ -43,51 +44,49 @@ async def open_case(user_qq: int, group: int, case_name: str = "狂牙大行动"
uplist[0] = 1
else:
uplist[1] = 1
ridicule_result = random.choice(['这样看着才舒服',
'是自己人,大伙把刀收好',
'非常舒适~'])
ridicule_result = random.choice(["这样看着才舒服", "是自己人,大伙把刀收好", "非常舒适~"])
if skin[:2] == "受限":
if skin.find("StatTrak") == -1:
uplist[2] = 1
else:
uplist[3] = 1
ridicule_result = random.choice(['还行吧,勉强接受一下下',
'居然不是蓝色,太假了',
'运气-1-1-1-1-1...'])
ridicule_result = random.choice(
["还行吧,勉强接受一下下", "居然不是蓝色,太假了", "运气-1-1-1-1-1..."]
)
if skin[:2] == "保密":
if skin.find("StatTrak") == -1:
uplist[4] = 1
else:
uplist[5] = 1
ridicule_result = random.choice(['开始不适....',
'你妈妈买菜必涨价!涨三倍!',
'你最近不适合出门,真的'])
ridicule_result = random.choice(
["开始不适....", "你妈妈买菜必涨价!涨三倍!", "你最近不适合出门,真的"]
)
if skin[:2] == "隐秘":
if skin.find("StatTrak") == -1:
uplist[6] = 1
else:
uplist[7] = 1
ridicule_result = random.choice(['已经非常不适',
'好兄弟你开的什么箱子啊,一般箱子不是只有蓝色的吗',
'开始拿阳寿开箱子了?'])
ridicule_result = random.choice(
["已经非常不适", "好兄弟你开的什么箱子啊,一般箱子不是只有蓝色的吗", "开始拿阳寿开箱子了?"]
)
if skin[:2] == "罕见":
knifes_flag = True
if skin.find("StatTrak") == -1:
uplist[8] = 1
else:
uplist[9] = 1
ridicule_result = random.choice(['你的好运我收到了,你可以去喂鲨鱼了',
'最近该吃啥就迟点啥吧,哎,好好的一个人怎么就....哎',
'众所周知,欧皇寿命极短.'])
ridicule_result = random.choice(
["你的好运我收到了,你可以去喂鲨鱼了", "最近该吃啥就迟点啥吧,哎,好好的一个人怎么就....哎", "众所周知,欧皇寿命极短."]
)
if skin.find("(") != -1:
cskin = skin.split("(")
skin = cskin[0].strip() + "(" + cskin[1].strip()
skin = skin.split("|")[0].strip() + " | " + skin.split("|")[1].strip()
# 价格
if skin.find('无涂装') == -1:
if skin.find("无涂装") == -1:
dbprice = await BuffPrice.ensure(skin[9:])
else:
dbprice = await BuffPrice.ensure(skin[9: skin.rfind('(')].strip())
dbprice = await BuffPrice.ensure(skin[9 : skin.rfind("(")].strip())
if dbprice.skin_price != 0:
price_result = dbprice.skin_price
print("数据库查询到价格: ", dbprice.skin_price)
@@ -114,38 +113,55 @@ async def open_case(user_qq: int, group: int, case_name: str = "狂牙大行动"
# cskin_word = sp[1][:sp[1].find("(") - 1].strip()
if knifes_flag:
await user.update(
knifes_name=user.knifes_name + f"{case}||{skin.split(':')[1].strip()} 磨损:{str(mosun)[:11]}, 价格:{uplist[10]},"
knifes_name=user.knifes_name
+ f"{case}||{skin.split(':')[1].strip()} 磨损:{str(mosun)[:11]}, 价格:{uplist[10]},"
).apply()
cskin_word = skin.split(':')[1].replace('|', '-').replace('(StatTrak™)', '')
cskin_word = cskin_word[: cskin_word.rfind('(')].strip()
skin_name = cn2py(cskin_word.replace('|', '-').replace('(StatTrak™)', '').strip())
img = image(f'{skin_name}.png', "cases/" + case)
cskin_word = skin.split(":")[1].replace("|", "-").replace("(StatTrak™)", "")
cskin_word = cskin_word[: cskin_word.rfind("(")].strip()
skin_name = cn2py(
cskin_word.replace("|", "-").replace("(StatTrak™)", "").strip()
)
img = image(f"{skin_name}.png", "cases/" + case)
# if knifes_flag:
# await user.update(
# knifes_name=user.knifes_name + f"{skin} 磨损:{mosun}, 价格:{uplist[10]}"
# ).apply()
if await update_user_total(user, uplist):
logger.info(f"qq:{user_qq} 群:{group} 开启{case_name}武器箱 获得 {skin} 磨损:{mosun}, 价格:{uplist[10]}, 数据更新成功")
logger.info(
f"qq:{user_qq} 群:{group} 开启{case_name}武器箱 获得 {skin} 磨损:{mosun}, 价格:{uplist[10]}, 数据更新成功"
)
else:
logger.warning(f"qq:{user_qq} 群:{group} 开启{case_name}武器箱 获得 {skin} 磨损:{mosun}, 价格:{uplist[10]}, 数据更新失败")
logger.warning(
f"qq:{user_qq} 群:{group} 开启{case_name}武器箱 获得 {skin} 磨损:{mosun}, 价格:{uplist[10]}, 数据更新失败"
)
user = await OpenCasesUser.ensure(user_qq, group, for_update=True)
over_count = int(MAX_COUNT + int(impression) / 3) - user.today_open_total
return f"开启{case_name}武器箱.\n剩余开箱次数:{over_count}.\n" \
+ img + "\n" + \
f"皮肤:{skin}\n" \
f"磨损:{mosun:.9f}\n" \
f"价格:{price_result}\n" \
f"{ridicule_result}"
over_count = int(
Config.get_config("open_cases", "INITIAL_OPEN_CASE_COUNT")
+ int(impression)
/ Config.get_config("open_cases", "EACH_IMPRESSION_ADD_COUNT")
) - user.today_open_total
return (
f"开启{case_name}武器箱.\n剩余开箱次数:{over_count}.\n" + img + "\n" + f"皮肤:{skin}\n"
f"磨损:{mosun:.9f}\n"
f"价格:{price_result}\n"
f"{ridicule_result}"
)
async def open_shilian_case(user_qq: int, group: int, case_name: str, num: int = 10):
user = await OpenCasesUser.ensure(user_qq, group, for_update=True)
impression = (await SignGroupUser.ensure(user_qq, group)).impression
if user.today_open_total == int(MAX_COUNT + int(impression) / 3):
max_count = int(
Config.get_config("open_cases", "INITIAL_OPEN_CASE_COUNT")
+ int(impression) / Config.get_config("open_cases", "EACH_IMPRESSION_ADD_COUNT")
)
if user.today_open_total == max_count:
return _handle_is_MAX_COUNT()
if int(MAX_COUNT + int(impression) / 3) - user.today_open_total < num:
return f"今天开箱次数不足{num}次噢,请单抽试试看(也许单抽运气更好?)" \
f"\n剩余开箱次数:{int(MAX_COUNT + int(impression) / 3) - user.today_open_total}"
if max_count - user.today_open_total < num:
return (
f"今天开箱次数不足{num}次噢,请单抽试试看(也许单抽运气更好?)"
f"\n剩余开箱次数:{max_count - user.today_open_total}"
)
await user.update(
total_count=user.total_count + num,
spend_money=user.spend_money + 17 * num,
@@ -163,7 +179,7 @@ async def open_shilian_case(user_qq: int, group: int, case_name: str, num: int =
# lan zi fen hong jin price
uplist = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0]
img_list = []
name_list = ['蓝', '蓝(暗金)', '紫', '紫(暗金)', '粉', '粉(暗金)', '红', '红(暗金)', '金', '金(暗金)']
name_list = ["蓝", "蓝(暗金)", "紫", "紫(暗金)", "粉", "粉(暗金)", "红", "红(暗金)", "金", "金(暗金)"]
async with db.transaction():
for _ in range(num):
knifes_flag = False
@@ -200,49 +216,71 @@ async def open_shilian_case(user_qq: int, group: int, case_name: str, num: int =
skin = cskin[0].strip() + "(" + cskin[1].strip()
skin = skin.split("|")[0].strip() + " | " + skin.split("|")[1].strip()
# 价格
if skin.find('无涂装') == -1:
if skin.find("无涂装") == -1:
dbprice = await BuffPrice.ensure(skin[9:])
else:
dbprice = await BuffPrice.ensure(skin[9: skin.rfind('(')].strip())
dbprice = await BuffPrice.ensure(skin[9 : skin.rfind("(")].strip())
if dbprice.skin_price != 0:
price_result = dbprice.skin_price
uplist[10] += price_result
else:
price_result = '未查询到'
price_result = "未查询到"
if knifes_flag:
await user.update(
knifes_name=user.knifes_name + f"{case}||{skin.split(':')[1].strip()} 磨损:{str(mosun)[:11]}, 价格:{dbprice.skin_price},"
knifes_name=user.knifes_name
+ f"{case}||{skin.split(':')[1].strip()} 磨损:{str(mosun)[:11]}, 价格:{dbprice.skin_price},"
).apply()
cskin_word = skin.split(':')[1].replace('|', '-').replace('(StatTrak™)', '')
cskin_word = cskin_word[: cskin_word.rfind('(')].strip()
cskin_word = skin.split(":")[1].replace("|", "-").replace("(StatTrak™)", "")
cskin_word = cskin_word[: cskin_word.rfind("(")].strip()
skin_name = ""
for i in pypinyin.pinyin(cskin_word.replace('|', '-').replace('(StatTrak™)', '').strip(),
style=pypinyin.NORMAL):
skin_name += ''.join(i)
for i in pypinyin.pinyin(
cskin_word.replace("|", "-").replace("(StatTrak™)", "").strip(),
style=pypinyin.NORMAL,
):
skin_name += "".join(i)
# img = image(skin_name, "cases/" + case, "png")
wImg = CreateImg(200, 270, 200, 200)
wImg.paste(alpha2white_pil(Image.open(IMAGE_PATH + f'cases/{case}/{skin_name}.png').resize((200, 200), Image.ANTIALIAS)), (0, 0))
wImg.paste(
alpha2white_pil(
Image.open(IMAGE_PATH + f"cases/{case}/{skin_name}.png").resize(
(200, 200), Image.ANTIALIAS
)
),
(0, 0),
)
wImg.text((5, 200), skin)
wImg.text((5, 220), f'磨损:{str(mosun)[:9]}')
wImg.text((5, 240), f'价格:{price_result}')
wImg.text((5, 220), f"磨损:{str(mosun)[:9]}")
wImg.text((5, 240), f"价格:{price_result}")
img_list.append(wImg)
logger.info(f"USER {user_qq} GROUP {group} 开启{case_name}武器箱 获得 {skin} 磨损:{mosun}, 价格:{uplist[10]}")
logger.info(
f"USER {user_qq} GROUP {group} 开启{case_name}武器箱 获得 {skin} 磨损:{mosun}, 价格:{uplist[10]}"
)
if await update_user_total(user, uplist, 0):
logger.info(f"USER {user_qq} GROUP {group} 开启{case_name}武器箱 {num} 次, 数据更新成功")
logger.info(
f"USER {user_qq} GROUP {group} 开启{case_name}武器箱 {num} 次, 数据更新成功"
)
else:
logger.warning(f"USER {user_qq} GROUP {group} 开启{case_name}武器箱 {num} 次, 价格:{uplist[10]}, 数据更新失败")
logger.warning(
f"USER {user_qq} GROUP {group} 开启{case_name}武器箱 {num} 次, 价格:{uplist[10]}, 数据更新失败"
)
# markImg = CreateImg(1000, h, 200, 270)
# for img in img_list:
# markImg.paste(img)
markImg = await asyncio.get_event_loop().run_in_executor(None, paste_markImg, h, img_list)
over_count = int(MAX_COUNT + int(impression) / 3) - user.today_open_total
result = ''
markImg = await asyncio.get_event_loop().run_in_executor(
None, paste_markImg, h, img_list
)
over_count = max_count - user.today_open_total
result = ""
for i in range(len(name_list)):
if uplist[i]:
result += f'[{name_list[i]}:{uplist[i]}] '
return f"开启{case_name}武器箱\n剩余开箱次数:{over_count}\n" \
+ image(b64=markImg.pic2bs4()) + \
'\n' + result[:-1] + f'\n总获取金额:{uplist[-1]:.2f}\n总花费:{17 * num}'
result += f"[{name_list[i]}:{uplist[i]}] "
return (
f"开启{case_name}武器箱\n剩余开箱次数:{over_count}\n"
+ image(b64=markImg.pic2bs4())
+ "\n"
+ result[:-1]
+ f"\n总获取金额:{uplist[-1]:.2f}\n总花费:{17 * num}"
)
def paste_markImg(h: int, img_list: list):
@@ -273,7 +311,7 @@ async def update_user_total(user: OpenCasesUser, up_list: list, num: int = 1) ->
spend_money=user.spend_money + 17 * num,
make_money=user.make_money + up_list[10],
today_open_total=user.today_open_total + num,
open_cases_time_last=datetime.now()
open_cases_time_last=datetime.now(),
).apply()
return True
except:
@@ -283,21 +321,23 @@ async def update_user_total(user: OpenCasesUser, up_list: list, num: int = 1) ->
async def total_open_statistics(user_qq: int, group: int) -> str:
async with db.transaction():
user = await OpenCasesUser.ensure(user_qq, group, for_update=True)
return f"开箱总数:{user.total_count}\n" \
f"今日开箱:{user.today_open_total}\n" \
f"蓝色军规:{user.blue_count}\n" \
f"蓝色暗金:{user.blue_st_count}\n" \
f"紫色受限:{user.purple_count}\n" \
f"紫色暗金:{user.purple_st_count}\n" \
f"粉色保密:{user.pink_count}\n" \
f"粉色暗金:{user.pink_st_count}\n" \
f"红色隐秘:{user.red_count}\n" \
f"红色暗金:{user.red_st_count}\n" \
f"金色罕见:{user.knife_count}\n" \
f"金色暗金:{user.knife_st_count}\n" \
f"花费金额:{user.spend_money}\n" \
f"获取金额:{user.make_money:.2f}\n" \
f"最后开箱日期:{(user.open_cases_time_last + timedelta(hours=8)).date()}"
return (
f"开箱总数:{user.total_count}\n"
f"今日开箱:{user.today_open_total}\n"
f"蓝色军规:{user.blue_count}\n"
f"蓝色暗金:{user.blue_st_count}\n"
f"紫色受限:{user.purple_count}\n"
f"紫色暗金:{user.purple_st_count}\n"
f"粉色保密:{user.pink_count}\n"
f"粉色暗金:{user.pink_st_count}\n"
f"红色隐秘:{user.red_count}\n"
f"红色暗金:{user.red_st_count}\n"
f"金色罕见:{user.knife_count}\n"
f"金色暗金:{user.knife_st_count}\n"
f"花费金额:{user.spend_money}\n"
f"获取金额:{user.make_money:.2f}\n"
f"最后开箱日期:{(user.open_cases_time_last + timedelta(hours=8)).date()}"
)
async def group_statistics(group: int):
@@ -318,20 +358,22 @@ async def group_statistics(group: int):
uplist[10] += user.make_money
uplist[11] += user.total_count
uplist[12] += user.today_open_total
return f"群开箱总数:{uplist[11]}\n" \
f"群今日开箱:{uplist[12]}\n" \
f"蓝色军规:{uplist[0]}\n" \
f"蓝色暗金:{uplist[1]}\n" \
f"紫色受限:{uplist[2]}\n" \
f"紫色暗金:{uplist[3]}\n" \
f"粉色保密:{uplist[4]}\n" \
f"粉色暗金:{uplist[5]}\n" \
f"红色隐秘:{uplist[6]}\n" \
f"红色暗金:{uplist[7]}\n" \
f"金色罕见:{uplist[8]}\n" \
f"金色暗金:{uplist[9]}\n" \
f"花费金额:{uplist[11] * 17}\n" \
f"获取金额:{uplist[10]:.2f}"
return (
f"群开箱总数:{uplist[11]}\n"
f"群今日开箱:{uplist[12]}\n"
f"蓝色军规:{uplist[0]}\n"
f"蓝色暗金:{uplist[1]}\n"
f"紫色受限:{uplist[2]}\n"
f"紫色暗金:{uplist[3]}\n"
f"粉色保密:{uplist[4]}\n"
f"粉色暗金:{uplist[5]}\n"
f"红色隐秘:{uplist[6]}\n"
f"红色暗金:{uplist[7]}\n"
f"金色罕见:{uplist[8]}\n"
f"金色暗金:{uplist[9]}\n"
f"花费金额:{uplist[11] * 17}\n"
f"获取金额:{uplist[10]:.2f}"
)
async def my_knifes_name(user_id: int, group: int):
@@ -348,7 +390,9 @@ async def my_knifes_name(user_id: int, group: int):
else:
h = 600 * int(length / 5) + 600
w = 540 * 5
A = await asyncio.get_event_loop().run_in_executor(None, _pst_my_knife, w, h, knifes_list)
A = await asyncio.get_event_loop().run_in_executor(
None, _pst_my_knife, w, h, knifes_list
)
return image(b64=A.pic2bs4())
else:
return "您木有开出金色级别的皮肤喔"
@@ -357,30 +401,36 @@ async def my_knifes_name(user_id: int, group: int):
def _pst_my_knife(w, h, knifes_list):
A = CreateImg(w, h, 540, 600)
for knife in knifes_list:
case = knife.split('||')[0]
knife = knife.split('||')[1]
name = knife[:knife.find('(')].strip()
itype = knife[knife.find('(')+1: knife.find(')')].strip()
mosun = knife[knife.find('磨损:')+3: knife.rfind('价格:')].strip()
if mosun[-1] == ',' or mosun[-1] == ',':
case = knife.split("||")[0]
knife = knife.split("||")[1]
name = knife[: knife.find("(")].strip()
itype = knife[knife.find("(") + 1 : knife.find(")")].strip()
mosun = knife[knife.find("磨损:") + 3 : knife.rfind("价格:")].strip()
if mosun[-1] == "," or mosun[-1] == ",":
mosun = mosun[:-1]
price = knife[knife.find('价格:')+3:]
price = knife[knife.find("价格:") + 3 :]
skin_name = ""
for i in pypinyin.pinyin(name.replace('|', '-').replace('(StatTrak™)', '').strip(),
style=pypinyin.NORMAL):
skin_name += ''.join(i)
for i in pypinyin.pinyin(
name.replace("|", "-").replace("(StatTrak™)", "").strip(),
style=pypinyin.NORMAL,
):
skin_name += "".join(i)
knife_img = CreateImg(470, 600, 470, 470, font_size=20)
knife_img.paste(alpha2white_pil(
Image.open(IMAGE_PATH + f'cases/{case}/{skin_name}.png').resize((470, 470), Image.ANTIALIAS)), (0, 0))
knife_img.text((5, 500), f'\t{name}({itype})')
knife_img.text((5, 530), f'\t磨损:{mosun}')
knife_img.text((5, 560), f'\t价格:{price}')
knife_img.paste(
alpha2white_pil(
Image.open(IMAGE_PATH + f"cases/{case}/{skin_name}.png").resize(
(470, 470), Image.ANTIALIAS
)
),
(0, 0),
)
knife_img.text((5, 500), f"\t{name}({itype})")
knife_img.text((5, 530), f"\t磨损:{mosun}")
knife_img.text((5, 560), f"\t价格:{price}")
A.paste(knife_img)
return A
# G3SG1(StatTrak™) | 血腥迷彩 (战痕累累)
# G3SG1(StatTrak™) | 血腥迷彩 (战痕累累)
# G3SG1(StatTrak™) | 血腥迷彩 (战痕累累)
+135 -93
View File
@@ -1,19 +1,18 @@
from models.buff_price import BuffPrice
from .models.buff_prices import BuffPrice
from services.db_context import db
from datetime import datetime, timedelta
from utils.user_agent import get_user_agent
from configs.path_config import IMAGE_PATH
import aiohttp
import aiofiles
from models.open_cases_user import OpenCasesUser
from .models.open_cases_user import OpenCasesUser
import os
from services.log import logger
from utils.utils import get_bot
from utils.utils import get_cookie_text
from asyncio.exceptions import TimeoutError
import pypinyin
from nonebot.adapters.cqhttp.exception import ActionFailed
from configs.config import BUFF_PROXY
from configs.config import Config
from utils.manager import group_manager
url = "https://buff.163.com/api/market/goods"
@@ -21,20 +20,20 @@ url = "https://buff.163.com/api/market/goods"
async def util_get_buff_price(case_name: str = "狂牙大行动") -> str:
cookie = {'session': get_cookie_text('buff')}
cookie = {"session": Config.get_config("open_cases", "COOKIE")}
failed_list = []
case = ""
for i in pypinyin.pinyin(case_name, style=pypinyin.NORMAL):
case += ''.join(i)
case += "".join(i)
if case_name == "狂牙大行动":
case_id = 1
elif case_name == "突围大行动":
case_id = 2
elif case_name == "命悬一线":
case_id = 3
elif case_name == '裂空':
elif case_name == "裂空":
case_id = 4
elif case_name == '光谱':
elif case_name == "光谱":
case_id = 5
else:
return "未查询到武器箱"
@@ -44,47 +43,63 @@ async def util_get_buff_price(case_name: str = "狂牙大行动") -> str:
CASE_PINK = eval(case + "_CASE_PINK")
CASE_PURPLE = eval(case + "_CASE_PURPLE")
CASE_BLUE = eval(case + "_CASE_BLUE")
async with aiohttp.ClientSession(cookies=cookie, headers=get_user_agent()) as session:
async with aiohttp.ClientSession(
cookies=cookie, headers=get_user_agent()
) as session:
for total_list in [CASE_KNIFE, CASE_RED, CASE_PINK, CASE_PURPLE, CASE_BLUE]:
print("----------------------------------")
for skin in total_list:
print(skin)
if skin in ["蝴蝶刀 | 无涂装", '求生匕首 | 无涂装', '流浪者匕首 | 无涂装', '系绳匕首 | 无涂装', '骷髅匕首 | 无涂装']:
skin = skin.split('|')[0].strip()
if skin in [
"蝴蝶刀 | 无涂装",
"求生匕首 | 无涂装",
"流浪者匕首 | 无涂装",
"系绳匕首 | 无涂装",
"骷髅匕首 | 无涂装",
]:
skin = skin.split("|")[0].strip()
async with db.transaction():
name_list = []
price_list = []
parameter = {
"game": "csgo",
"page_num": "1",
"search": skin
}
parameter = {"game": "csgo", "page_num": "1", "search": skin}
try:
async with session.get(url, proxy=BUFF_PROXY, params=parameter, timeout=20) as response:
async with session.get(
url,
proxy=Config.get_config("open_cases", "BUFF_PROXY"),
params=parameter,
timeout=20,
) as response:
if response.status == 200:
data = (await response.json())["data"]
total_page = data["total_page"]
data = data["items"]
flag = False
if skin.find('|') == -1: # in ['蝴蝶刀', '求生匕首', '流浪者匕首', '系绳匕首', '骷髅匕首']:
if (
skin.find("|") == -1
): # in ['蝴蝶刀', '求生匕首', '流浪者匕首', '系绳匕首', '骷髅匕首']:
for i in range(1, total_page + 1):
name_list = []
price_list = []
parameter = {
"game": "csgo",
"page_num": f"{i}",
"search": skin
"search": skin,
}
async with session.get(url, params=parameter, timeout=20) as res:
data = (await response.json())["data"]["items"]
async with session.get(
url, params=parameter, timeout=20
) as res:
data = (await response.json())["data"][
"items"
]
for j in range(len(data)):
if data[j]['name'] in [f'{skin}(★)']:
if data[j]["name"] in [f"{skin}(★)"]:
name = data[j]["name"]
price = data[j]["sell_reference_price"]
name_list.append(name.split('(')[0].strip() + ' | 无涂装')
price = data[j][
"sell_reference_price"
]
name_list.append(
name.split("(")[0].strip()
+ " | 无涂装"
)
price_list.append(price)
print(name_list[-1])
print(price_list[-1])
flag = True
break
if flag:
@@ -99,38 +114,56 @@ async def util_get_buff_price(case_name: str = "狂牙大行动") -> str:
price_list.append(price)
except Exception as e:
failed_list.append(skin)
print(f"{skin}更新失败")
logger.warning(f"{skin}更新失败")
else:
failed_list.append(skin)
print(f"{skin}更新失败")
logger.warning(f"{skin}更新失败")
except Exception:
failed_list.append(skin)
print(f"{skin}更新失败")
logger.warning(f"{skin}更新失败")
continue
for i in range(len(name_list)):
name = name_list[i].strip()
price = float(price_list[i])
if name.find("(★)") != -1:
name = name[: name.find("(")] + name[name.find(")") + 1:]
name = name[: name.find("(")] + name[name.find(")") + 1 :]
if name.find("消音") != -1 and name.find("(S") != -1:
name = name.split("(")[0][:-4] + "(" + name.split("(")[1]
name = name.split("|")[0].strip() + " | " + name.split("|")[1].strip()
name = (
name.split("|")[0].strip()
+ " | "
+ name.split("|")[1].strip()
)
elif name.find("消音") != -1:
name = name.split("|")[0][:-5].strip() + " | " + name.split("|")[1].strip()
name = (
name.split("|")[0][:-5].strip()
+ " | "
+ name.split("|")[1].strip()
)
if name.find(" 18 ") != -1 and name.find("(S") != -1:
name = name.split("(")[0][:-5] + "(" + name.split("(")[1]
name = name.split("|")[0].strip() + " | " + name.split("|")[1].strip()
name = (
name.split("|")[0].strip()
+ " | "
+ name.split("|")[1].strip()
)
elif name.find(" 18 ") != -1:
name = name.split("|")[0][:-6].strip() + " | " + name.split("|")[1].strip()
name = (
name.split("|")[0][:-6].strip()
+ " | "
+ name.split("|")[1].strip()
)
dbskin = await BuffPrice.ensure(name, True)
if (dbskin.update_date + timedelta(8)).date() == datetime.now().date():
if (
dbskin.update_date + timedelta(8)
).date() == datetime.now().date():
continue
await dbskin.update(
case_id=case_id,
skin_price=price,
update_date=datetime.now(),
).apply()
print(f"{name_list[i]}---------->成功更新")
logger.info(f"{name_list[i]}---------->成功更新")
result = None
if failed_list:
result = ""
@@ -140,11 +173,11 @@ async def util_get_buff_price(case_name: str = "狂牙大行动") -> str:
async def util_get_buff_img(case_name: str = "狂牙大行动") -> str:
cookie = {'session': get_cookie_text('buff')}
cookie = {"session": Config.get_config("open_cases", "COOKIE")}
error_list = []
case = ""
for i in pypinyin.pinyin(case_name, style=pypinyin.NORMAL):
case += ''.join(i)
case += "".join(i)
path = "cases/" + case + "/"
if not os.path.exists(IMAGE_PATH + path):
os.mkdir(IMAGE_PATH + path)
@@ -154,63 +187,75 @@ async def util_get_buff_img(case_name: str = "狂牙大行动") -> str:
CASE_PINK = eval(case + "_CASE_PINK")
CASE_PURPLE = eval(case + "_CASE_PURPLE")
CASE_BLUE = eval(case + "_CASE_BLUE")
async with aiohttp.ClientSession(cookies=cookie, headers=get_user_agent()) as session:
async with aiohttp.ClientSession(
cookies=cookie, headers=get_user_agent()
) as session:
for total_list in [CASE_KNIFE, CASE_RED, CASE_PINK, CASE_PURPLE, CASE_BLUE]:
for skin in total_list:
parameter = {
"game": "csgo",
"page_num": "1",
"search": skin
}
if skin in ["蝴蝶刀 | 无涂装", '求生匕首 | 无涂装', '流浪者匕首 | 无涂装', '系绳匕首 | 无涂装', '骷髅匕首 | 无涂装']:
skin = skin.split('|')[0].strip()
print("开始更新----->", skin)
print(skin)
skin_name = ''
parameter = {"game": "csgo", "page_num": "1", "search": skin}
if skin in [
"蝴蝶刀 | 无涂装",
"求生匕首 | 无涂装",
"流浪者匕首 | 无涂装",
"系绳匕首 | 无涂装",
"骷髅匕首 | 无涂装",
]:
skin = skin.split("|")[0].strip()
logger.info(f"开始更新----->{skin}")
skin_name = ""
# try:
async with session.get(url, proxy=BUFF_PROXY, params=parameter, timeout=20) as response:
async with session.get(
url,
proxy=Config.get_config("open_cases", "BUFF_PROXY"),
params=parameter,
timeout=20,
) as response:
if response.status == 200:
data = (await response.json())["data"]
total_page = data["total_page"]
flag = False
if skin.find('|') == -1: # in ['蝴蝶刀', '求生匕首', '流浪者匕首', '系绳匕首', '骷髅匕首']:
if (
skin.find("|") == -1
): # in ['蝴蝶刀', '求生匕首', '流浪者匕首', '系绳匕首', '骷髅匕首']:
for i in range(1, total_page + 1):
async with session.get(url, params=parameter, timeout=20) as res:
async with session.get(
url, params=parameter, timeout=20
) as res:
data = (await response.json())["data"]["items"]
for j in range(len(data)):
if data[j]['name'] in [f'{skin}(★)']:
img_url = data[j]['goods_info']['icon_url']
for k in pypinyin.pinyin(skin + '无涂装', style=pypinyin.NORMAL):
skin_name += ''.join(k)
async with aiofiles.open(IMAGE_PATH + path + skin_name + ".png", 'wb') as f:
print("------->开始写入 ", skin)
async with session.get(img_url, timeout=7) as res:
if data[j]["name"] in [f"{skin}(★)"]:
img_url = data[j]["goods_info"]["icon_url"]
for k in pypinyin.pinyin(
skin + "无涂装", style=pypinyin.NORMAL
):
skin_name += "".join(k)
async with aiofiles.open(
IMAGE_PATH + path + skin_name + ".png",
"wb",
) as f:
logger.info(f"------->开始写入{skin}")
async with session.get(
img_url, timeout=7
) as res:
await f.write(await res.read())
flag = True
break
if flag:
break
else:
img_url = (await response.json())["data"]['items'][0]['goods_info']['icon_url']
for i in pypinyin.pinyin(skin.replace('|', '-').strip(), style=pypinyin.NORMAL):
skin_name += ''.join(i)
async with aiofiles.open(IMAGE_PATH + path + skin_name + ".png", 'wb') as f:
print("------->开始写入 ", skin)
img_url = (await response.json())["data"]["items"][0][
"goods_info"
]["icon_url"]
for i in pypinyin.pinyin(
skin.replace("|", "-").strip(), style=pypinyin.NORMAL
):
skin_name += "".join(i)
async with aiofiles.open(
IMAGE_PATH + path + skin_name + ".png", "wb"
) as f:
logger.info(f"------->开始写入 {skin}")
async with session.get(img_url, timeout=7) as res:
await f.write(await res.read())
# async with session.get(url, params=parameter, timeout=7) as response:
# if response.status == 200:
# img_url = (await response.json())["data"]['items'][0]['goods_info']['icon_url']
# skin_name = ''
# for i in pypinyin.pinyin(skin.split("|")[1].strip(), style=pypinyin.NORMAL):
# skin_name += ''.join(i)
# async with aiofiles.open(IMAGE_PATH + path + skin_name + ".png", 'wb') as f:
# print("------->开始写入 ", skin)
# async with session.get(img_url, timeout=7) as res:
# await f.write(await res.read())
# except Exception:
# print("图片更新失败 ---->", skin)
# error_list.append(skin)
result = None
if error_list:
result = ""
@@ -220,16 +265,14 @@ async def util_get_buff_img(case_name: str = "狂牙大行动") -> str:
async def get_price(dname):
cookie = {'session': get_cookie_text('buff')}
cookie = {"session": Config.get_config("open_cases", "COOKIE")}
name_list = []
price_list = []
parameter = {
"game": "csgo",
"page_num": "1",
"search": dname
}
parameter = {"game": "csgo", "page_num": "1", "search": dname}
try:
async with aiohttp.ClientSession(cookies=cookie, headers=get_user_agent()) as session:
async with aiohttp.ClientSession(
cookies=cookie, headers=get_user_agent()
) as session:
async with session.get(url, params=parameter, timeout=7) as response:
if response.status == 200:
try:
@@ -262,22 +305,21 @@ async def update_count_daily():
for user in users:
await user.update(
today_open_total=0,
).apply()
).apply()
bot = get_bot()
gl = await bot.get_group_list()
gl = [g['group_id'] for g in gl]
gl = [g["group_id"] for g in gl]
for g in gl:
if await group_manager.check_group_task_status(g, 'open_case_reset_remind'):
if await group_manager.check_group_task_status(g, "open_case_reset_remind"):
try:
await bot.send_group_msg(group_id=g, message="今日开箱次数重置成功")
except ActionFailed:
logger.warning(f'{g} 群被禁言,无法发送 开箱重置提醒')
logger.warning(f"{g} 群被禁言,无法发送 开箱重置提醒")
logger.info("今日开箱次数重置成功")
except Exception as e:
logger.error(f'开箱重置错误 e:{e}')
logger.error(f"开箱重置错误 e:{e}")
# 蝴蝶刀(★) | 噩梦之夜 (久经沙场)
if __name__ == '__main__':
if __name__ == "__main__":
print(util_get_buff_img("xxxx/"))