From 43111d5bc739e02e861c02c6ec25ab470da8fc74 Mon Sep 17 00:00:00 2001 From: Ewait Date: Thu, 12 Jan 2023 22:32:54 +0800 Subject: [PATCH 01/18] refactor(main): using img-url for vip-shop-img cache,fix keyerr in notify task --- code/main.py | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/code/main.py b/code/main.py index cf9b559..eab49c1 100644 --- a/code/main.py +++ b/code/main.py @@ -1403,7 +1403,8 @@ def is_CacheLatest(kook_user_id:str): is_Status = VipShopBgDict[kook_user_id]['status'] # 如果有切换登录用户/背景图,此为false # 判断图片是不是今天的(可能出现早八提醒的时候出错,导致缓存没有更新,是昨天的图) is_Today = (VipShopBgDict[kook_user_id]['cache_time']-GetTimeStampOf8AM())>=0 - return is_Today and is_Status # 有一个为false,结果就是false + is_Key = ('cache_img' in VipShopBgDict[kook_user_id]) # 键值是否存在 + return is_Today and is_Status and is_Key# 有一个为false,结果就是false return False # 获取每日商店的命令 @@ -1466,14 +1467,13 @@ async def get_daily_shop(msg: Message, *arg): # 开始画图 draw_time = time.time() #计算画图需要的时间 is_vip = await vip_ck(msg.author_id) #判断用户是否为VIP - img_ret = {'status':True,'value':None} + img_ret = {'status':True,'value':None,'upload_flag':True} # 每天8点bot遍历完之后会把vip的商店结果图存起来 shop_path = f"./log/img_temp_vip/shop/{msg.author_id}.png" # 如果是vip而且path存在,背景图/登录用户没有更改过,图片缓存时间正确 if is_vip and (os.path.exists(shop_path)) and is_CacheLatest(msg.author_id): - bg_vip_shop = Image.open(shop_path) #直接使用本地已经画好的图片 - bg = copy.deepcopy(bg_vip_shop) - img_ret['value'] = bg # 放入返回值 + img_ret['upload_flag'] = False #有缓存图,直接使用本地已有链接 + dailyshop_img_src = VipShopBgDict[msg.author_id]['cache_img'] elif is_vip and (msg.author_id in VipShopBgDict): #本地缓存路径不存在,或者缓存过期 play_currency = await fetch_valorant_point(userdict)#获取用户的vp和rp vp = play_currency["Balances"]["85ad13f7-3d1b-5128-9eb2-7cd8ee0b5741"] #vp @@ -1493,15 +1493,16 @@ async def get_daily_shop(msg: Message, *arg): # 获取图片成功,打印画图耗时 log_time += f"- [Drawing] {format(time.time() - draw_time,'.4f')} - [Au] {msg.author_id}" print(log_time) - # bg.save(f"test.png") #保存到本地 - imgByteArr = io.BytesIO() - bg.save(imgByteArr, format='PNG') - imgByte = imgByteArr.getvalue() - dailyshop_img_src = await bot_upimg.client.create_asset(imgByte) # 上传图片 - # 结束shop的总计时 - end = time.perf_counter() - # 结果为浮点数,保留两位小数 - shop_using_time = format(end - start, '.2f') + if img_ret['upload_flag']: + imgByteArr = io.BytesIO() + bg.save(imgByteArr, format='PNG') + imgByte = imgByteArr.getvalue() + dailyshop_img_src = await bot_upimg.client.create_asset(imgByte) # 上传图片 + if is_vip: #vip缓存图片 + VipShopBgDict[msg.author_id]['cache_img'] = dailyshop_img_src #设置图片url + VipShopBgDict[msg.author_id]['cache_time'] = time.time() #设置图片缓存的时间 + # 结束shop的总计时,结果为浮点数,保留两位小数 + shop_using_time = format(time.perf_counter() - start, '.2f') # 商店的图片 cm = CardMessage() @@ -2196,7 +2197,7 @@ async def auto_skin_notify(): if img_ret['status']: bg_shop = img_ret['value'] bg_shop.save(img_shop_path, format='PNG') - VipShopBgDict['cache_time'] = time.time() #设置图片缓存的时间 + VipShopBgDict[vip]['cache_time'] = time.time() #设置图片缓存的时间 else: #如果图片没有正常返回,那就发送文字版本 shop_text = "" for skinuuid in list_shop: @@ -2210,6 +2211,7 @@ async def auto_skin_notify(): log_time += f"- [Drawing] {format(time.time() - draw_time,'.4f')} - [Au] {vip}" print(log_time) dailyshop_img_src = await bot_upimg.client.create_asset(img_shop_path) # 上传图片 + VipShopBgDict[vip]['cache_img'] = dailyshop_img_src # 缓存图片url # 结束shop的总计时 结果为浮点数,保留两位小数 using_time = format(time.perf_counter() - start, '.2f') #卡片消息发送图片或者text From f8fe73080efa405ff859824e5f316c9d4fee27da Mon Sep 17 00:00:00 2001 From: Ewait Date: Thu, 12 Jan 2023 23:35:02 +0800 Subject: [PATCH 02/18] fix(EzAuth): fix keyerr of 'start_time' in 2faWait --- code/endpoints/EzAuth.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/code/endpoints/EzAuth.py b/code/endpoints/EzAuth.py index 3ef79a5..5101499 100644 --- a/code/endpoints/EzAuth.py +++ b/code/endpoints/EzAuth.py @@ -68,13 +68,13 @@ def authorize(self,username, password,key): tokens = [token,token_id] elif "auth_failure" in r.text: - print(F"[EzAuth] k:{key} auth_failure, NOT EXIST") - User2faCode[key]= {'status':False,'err':"auth_failure, NOT EXIST"} + print(F"[EzAuth] k:{key} auth_failure, USER NOT EXIST") + User2faCode[key]= {'status':False,'err':"auth_failure, NOT EXIST",'start_time':time.time()} raise Exception("auth_failure") elif 'rate_limited' in r.text: print(F"[EzAuth] k:{key} auth rate limited") - User2faCode[key]= {'status':False,'err':"auth rate_limited"} + User2faCode[key]= {'status':False,'err':"auth rate_limited",'start_time':time.time()} raise Exception("auth rate_limited") else:# 到此处一般是需要邮箱验证的用户 @@ -248,16 +248,17 @@ async def auth2faWait(key,msg=None): # 开始循环检测status状态 while(not User2faCode[key]['status']): - # 这里 -3s 是为了让该线程更晚获取到信息,要在auth线程break之后才删除键值 - if (time.time()-User2faCode[key]['start_time']-3)>TFA_TIME_LIMIT: - del User2faCode[key] - break # 超过10分钟,以无效处理 # 不为none,出现错误 if User2faCode[key]['err'] != None: if 'rate_limited' in User2faCode[key]['err']: raise auth_exceptions.RiotRatelimitError else: raise Exception(User2faCode[key]['err']) + # 这里 -3s 是为了让该线程更晚获取到信息,要在auth线程break之后才删除键值 + if (time.time()-User2faCode[key]['start_time']-3)>TFA_TIME_LIMIT: + del User2faCode[key] + break # 超过10分钟,以无效处理 + # 睡一会再检测 await asyncio.sleep(0.3) From 4e72af2b2b9e7f0e7d3e6f8641af5fdd5992fccb Mon Sep 17 00:00:00 2001 From: Ewait Date: Thu, 12 Jan 2023 23:35:51 +0800 Subject: [PATCH 03/18] fiox(api): fix wrong file save path in apitoken,add traceback in apihandler --- code/endpoints/ApiHandler.py | 4 ++-- code/endpoints/ApiToken.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/code/endpoints/ApiHandler.py b/code/endpoints/ApiHandler.py index eba3e80..30122a9 100644 --- a/code/endpoints/ApiHandler.py +++ b/code/endpoints/ApiHandler.py @@ -1,7 +1,7 @@ import json import time import threading -import aiofiles +import traceback from endpoints.EzAuth import auth_exceptions,auth2fa,auth2faWait,Get2faWait_Key,User2faCode from endpoints.ApiToken import token_ck,ApiTokenDict,save_token_files from endpoints.Gtime import GetTime @@ -78,7 +78,7 @@ async def base_img_request(request): print(f"ERR! [{GetTime()}] login - riot_auth.riot_auth.auth_exceptions.RiotRatelimitError") return {'code': 200, 'message': "riot_auth.auth_exceptions.RiotRatelimitError",'info':'riot登录api超速,请稍后重试'} except Exception as result: - print(f"ERR! [{GetTime()}] login - {result}") + print(f"ERR! [{GetTime()}] login\n{traceback.format_exc()}") return {'code': 200, 'message': f"{result}",'info':'riot登录错误,详见message'} print(f'[{GetTime()}] [Api] k:{key} - user auth success') diff --git a/code/endpoints/ApiToken.py b/code/endpoints/ApiToken.py index f3f101d..7cd82fe 100644 --- a/code/endpoints/ApiToken.py +++ b/code/endpoints/ApiToken.py @@ -14,7 +14,7 @@ def get_uuid(): def save_token_files(text=''): global ApiTokenDict - with open("./log/UserToken.json", 'w', encoding='utf-8') as fw2: + with open("./log/ApiToken.json", 'w', encoding='utf-8') as fw2: json.dump(ApiTokenDict, fw2, indent=2, sort_keys=True, ensure_ascii=False) print(f"[token] files saved! {text}") From 6385cd53a98cf4781a9e81bcd11f1c255c271320 Mon Sep 17 00:00:00 2001 From: Ewait Date: Thu, 12 Jan 2023 23:36:19 +0800 Subject: [PATCH 04/18] fix(main): fix keyerr of upload_flag --- code/main.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/code/main.py b/code/main.py index eab49c1..ea949ed 100644 --- a/code/main.py +++ b/code/main.py @@ -1467,12 +1467,13 @@ async def get_daily_shop(msg: Message, *arg): # 开始画图 draw_time = time.time() #计算画图需要的时间 is_vip = await vip_ck(msg.author_id) #判断用户是否为VIP - img_ret = {'status':True,'value':None,'upload_flag':True} + img_ret = {'status':True,'value':None} + upload_flag=True # 每天8点bot遍历完之后会把vip的商店结果图存起来 shop_path = f"./log/img_temp_vip/shop/{msg.author_id}.png" # 如果是vip而且path存在,背景图/登录用户没有更改过,图片缓存时间正确 if is_vip and (os.path.exists(shop_path)) and is_CacheLatest(msg.author_id): - img_ret['upload_flag'] = False #有缓存图,直接使用本地已有链接 + upload_flag=False #有缓存图,直接使用本地已有链接 dailyshop_img_src = VipShopBgDict[msg.author_id]['cache_img'] elif is_vip and (msg.author_id in VipShopBgDict): #本地缓存路径不存在,或者缓存过期 play_currency = await fetch_valorant_point(userdict)#获取用户的vp和rp @@ -1493,7 +1494,7 @@ async def get_daily_shop(msg: Message, *arg): # 获取图片成功,打印画图耗时 log_time += f"- [Drawing] {format(time.time() - draw_time,'.4f')} - [Au] {msg.author_id}" print(log_time) - if img_ret['upload_flag']: + if upload_flag: imgByteArr = io.BytesIO() bg.save(imgByteArr, format='PNG') imgByte = imgByteArr.getvalue() From 6200788da1697c00fe3a5778bdecde4c0c7db8aa Mon Sep 17 00:00:00 2001 From: Ewait Date: Thu, 12 Jan 2023 23:40:24 +0800 Subject: [PATCH 05/18] fix(main): nofity.task only create_asset when img ready --- code/main.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/code/main.py b/code/main.py index ea949ed..bf7e3cd 100644 --- a/code/main.py +++ b/code/main.py @@ -2198,6 +2198,11 @@ async def auto_skin_notify(): if img_ret['status']: bg_shop = img_ret['value'] bg_shop.save(img_shop_path, format='PNG') + # 打印画图日志 + log_time += f"- [Drawing] {format(time.time() - draw_time,'.4f')} - [Au] {vip}" + print(log_time) + dailyshop_img_src = await bot_upimg.client.create_asset(img_shop_path) # 上传图片 + VipShopBgDict[vip]['cache_img'] = dailyshop_img_src # 缓存图片url VipShopBgDict[vip]['cache_time'] = time.time() #设置图片缓存的时间 else: #如果图片没有正常返回,那就发送文字版本 shop_text = "" @@ -2208,11 +2213,7 @@ async def auto_skin_notify(): shop_text += f"{res_item['data']['displayName']} - VP {price}\n" print(f"[BOT.TASK.NOTIFY] VAu:{vip} test img err, using text") - # 打印日志 - log_time += f"- [Drawing] {format(time.time() - draw_time,'.4f')} - [Au] {vip}" - print(log_time) - dailyshop_img_src = await bot_upimg.client.create_asset(img_shop_path) # 上传图片 - VipShopBgDict[vip]['cache_img'] = dailyshop_img_src # 缓存图片url + # 结束shop的总计时 结果为浮点数,保留两位小数 using_time = format(time.perf_counter() - start, '.2f') #卡片消息发送图片或者text From e79ee13879696d7f08f7718f95264b2929545a86 Mon Sep 17 00:00:00 2001 From: Ewait Date: Fri, 13 Jan 2023 15:56:36 +0800 Subject: [PATCH 06/18] fix(main): del err login_rate check in login --- code/main.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/code/main.py b/code/main.py index bf7e3cd..8c48b56 100644 --- a/code/main.py +++ b/code/main.py @@ -1052,18 +1052,16 @@ async def login_authtoken(msg: Message, user: str = 'err', passwd: str = 'err',t elif Login_Forbidden: await Login_Forbidden_send(msg) return - - global login_rate_limit, UserTokenDict, UserAuthDict try: + global login_rate_limit, UserTokenDict, UserAuthDict cm0 = CardMessage() c = Card(color='#fb4b57') #卡片侧边栏颜色 - if await check_global_login_rate(msg):# 全局请求超速 - return - if await check_user_login_rate(msg):# 用户请求超速 - print(f"Login - Au:{msg.author_id} - raise user_login_rate_limit") - return - + # if await check_global_login_rate(msg):# 全局请求超速 + # return + # if await check_user_login_rate(msg):# 用户请求超速 + # print(f"Login - Au:{msg.author_id} - raise user_login_rate_limit") + # return text = "正在尝试获取您的riot账户token" c.append(Module.Section(Element.Text(text, Types.Text.KMD), Element.Image(src=icon_cm.val_logo_gif, size='sm'))) c.append(Module.Context(Element.Text("小憩一下,很快就好啦!", Types.Text.KMD))) From c3a687897d547cdd0ea1b441500ff63491d73ab2 Mon Sep 17 00:00:00 2001 From: Ewait Date: Fri, 13 Jan 2023 16:06:11 +0800 Subject: [PATCH 07/18] fix(main): add key 'cache' and 'bg' in VipShopBgDcit --- code/main.py | 94 +++++++++++++++++++++++++++------------------------- 1 file changed, 49 insertions(+), 45 deletions(-) diff --git a/code/main.py b/code/main.py index 8c48b56..1902bd0 100644 --- a/code/main.py +++ b/code/main.py @@ -478,9 +478,9 @@ async def replace_illegal_img(user_id: str, num: int): """ try: global VipShopBgDict - img_str = VipShopBgDict[user_id]["background"][num] - VipShopBgDict[user_id]["background"][num] = illegal_img_169 - VipShopBgDict[user_id]["status"] = False #需要重新加载图片 + img_str = VipShopBgDict['bg'][user_id]["background"][num] + VipShopBgDict['bg'][user_id]["background"][num] = illegal_img_169 + VipShopBgDict['bg'][user_id]["status"] = False #需要重新加载图片 with open("./log/VipUserShopBg.json", 'w', encoding='utf-8') as fw2: json.dump(VipShopBgDict, fw2, indent=2, sort_keys=True, ensure_ascii=False) print(f"[Replace_img] Au:{user_id} [{img_str}]") #写入文件后打印log信息 @@ -501,7 +501,7 @@ async def check_vip_img(): c.append(Module.Context(Element.Text("多次发送违禁图片会导致阿狸被封,请您慎重选择图片!", Types.Text.KMD))) #遍历vip用户的图片 log_str_user = "[BOT.TASK] check_vip_img Au:" - for vip_user, vip_bg in VipShopBgDict.items(): + for vip_user, vip_bg in VipShopBgDict['bg'].items(): user = await bot.client.fetch_user(vip_user) sz = len(vip_bg["background"]) i = 0 @@ -566,8 +566,8 @@ def len_VusBg(user_id: str): - len(VipShopBgDict[user_id]["background"]) - return 0 if user not in dict """ - if user_id in VipShopBgDict: - return len(VipShopBgDict[user_id]["background"]) + if user_id in VipShopBgDict['bg']: + return len(VipShopBgDict['bg'][user_id]["background"]) else: return 0 @@ -575,7 +575,7 @@ def len_VusBg(user_id: str): #因为下面两个函数都要用,所以直接独立出来 async def get_vip_shop_bg_cm(msg: Message): global VipShopBgDict - if msg.author_id not in VipShopBgDict: + if msg.author_id not in VipShopBgDict['bg']: return "您尚未自定义商店背景图!" elif len_VusBg(msg.author_id) == 0: return "您尚未自定义商店背景图!" @@ -583,8 +583,8 @@ async def get_vip_shop_bg_cm(msg: Message): cm = CardMessage() c1 = Card(color='#e17f89') c1.append(Module.Header('您当前设置的商店背景图如下')) - c1.append(Module.Container(Element.Image(src=VipShopBgDict[msg.author_id]["background"][0]))) - sz = len(VipShopBgDict[msg.author_id]["background"]) + c1.append(Module.Container(Element.Image(src=VipShopBgDict['bg'][msg.author_id]["background"][0]))) + sz = len(VipShopBgDict['bg'][msg.author_id]["background"]) if sz > 1: c1.append(Module.Divider()) c1.append(Module.Section(Element.Text('当前未启用的背景图,可用「/vip-shop-s 序号」切换', Types.Text.KMD))) @@ -592,19 +592,19 @@ async def get_vip_shop_bg_cm(msg: Message): while (i < sz): try: # 打开图片进行测试,没有问题就append - bg_test = Image.open(io.BytesIO(await img_requestor(VipShopBgDict[msg.author_id]["background"][i]))) + bg_test = Image.open(io.BytesIO(await img_requestor(VipShopBgDict['bg'][msg.author_id]["background"][i]))) if i == 0: #第一张图片只进行打开测试,没有报错就是没有违规,不进行后续的append操作 i += 1 continue # 插入后续其他图片 c1.append( Module.Section(Element.Text(f' [{i}]', Types.Text.KMD), - Element.Image(src=VipShopBgDict[msg.author_id]["background"][i]))) + Element.Image(src=VipShopBgDict['bg'][msg.author_id]["background"][i]))) i += 1 except UnidentifiedImageError as result: err_str = f"ERR! [{GetTime()}] checking [{msg.author_id}] img\n```\n{result}\n" #把被ban的图片替换成默认的图片,打印url便于日后排错 - err_str += f"[UnidentifiedImageError] url={VipShopBgDict[msg.author_id]['background'][i]}\n```" + err_str += f"[UnidentifiedImageError] url={VipShopBgDict['bg'][msg.author_id]['background'][i]}\n```" await replace_illegal_img(msg.author_id, i) #替换图片 await bot.client.send(debug_ch, err_str) # 发送消息到debug频道 print(err_str) @@ -629,8 +629,8 @@ async def vip_shop_bg_set(msg: Message, icon: str = "err", *arg): x3 = "[None]" if icon != 'err': - user_ind = (msg.author_id in VipShopBgDict) #判断当前用户在不在dict中 - if user_ind and len(VipShopBgDict[msg.author_id]["background"]) >= 4: + user_ind = (msg.author_id in VipShopBgDict['bg']) #判断当前用户在不在dict中 + if user_ind and len(VipShopBgDict['bg'][msg.author_id]["background"]) >= 4: text = f"当前仅支持保存4个自定义图片" c.append( Module.Section(Element.Text(text, Types.Text.KMD), Element.Image(src=icon_cm.that_it, size='sm'))) @@ -666,12 +666,12 @@ async def vip_shop_bg_set(msg: Message, icon: str = "err", *arg): #到插入的时候再创建list,避免出现图片没有通过检查,但是list又被创建了的情况 if not user_ind: - VipShopBgDict[msg.author_id] = {} - VipShopBgDict[msg.author_id]["background"] = list() + VipShopBgDict['bg'][msg.author_id] = {} + VipShopBgDict['bg'][msg.author_id]["background"] = list() #新建用户,但是有可能已经缓存了默认的背景图片,所以状态为false(重画) - VipShopBgDict[msg.author_id]["status"] = False + VipShopBgDict['bg'][msg.author_id]["status"] = False #插入图片 - VipShopBgDict[msg.author_id]["background"].append(x3) + VipShopBgDict['bg'][msg.author_id]["background"].append(x3) cm = await get_vip_shop_bg_cm(msg) #先让测试bot把这个卡片发到频道,如果发出去了说明json没有问题 @@ -688,7 +688,7 @@ async def vip_shop_bg_set(msg: Message, icon: str = "err", *arg): except requester.HTTPRequester.APIRequestFailed as result: await APIRequestFailed_Handler("vip_shop",traceback.format_exc(),msg,bot,None,cm) - VipShopBgDict[msg.author_id]["background"].remove(x3) #删掉里面的图片 + VipShopBgDict['bg'][msg.author_id]["background"].remove(x3) #删掉里面的图片 print(f"[vip_shop] Au:{msg.author_id} remove(err_img)") except Exception as result: await BaseException_Handler("vip_shop",traceback.format_exc(),msg,bot,None,cm,"建议加入帮助频道找我康康到底是啥问题") @@ -704,14 +704,14 @@ async def vip_shop_bg_set_s(msg: Message, num: str = "err", *arg): global VipShopBgDict if not await vip_ck(msg): return - if msg.author_id not in VipShopBgDict: + if msg.author_id not in VipShopBgDict['bg']: await msg.reply("您尚未自定义商店背景图!") return num = int(num) - if num < len(VipShopBgDict[msg.author_id]["background"]): + if num < len(VipShopBgDict['bg'][msg.author_id]["background"]): try: #打开用户需要切换的图片 - bg_vip = Image.open(io.BytesIO(await img_requestor(VipShopBgDict[msg.author_id]["background"][num]))) + bg_vip = Image.open(io.BytesIO(await img_requestor(VipShopBgDict['bg'][msg.author_id]["background"][num]))) except UnidentifiedImageError as result: err_str = f"ERR! [{GetTime()}] vip_shop_s_imgck\n```\n{result}\n```" await msg.reply(f"图片违规!请重新上传\n{err_str}") @@ -719,10 +719,10 @@ async def vip_shop_bg_set_s(msg: Message, num: str = "err", *arg): print(err_str) return # 图片检查通过,交换两个图片的位置 - icon_num = VipShopBgDict[msg.author_id]["background"][num] - VipShopBgDict[msg.author_id]["background"][num] = VipShopBgDict[msg.author_id]["background"][0] - VipShopBgDict[msg.author_id]["background"][0] = icon_num - VipShopBgDict[msg.author_id]['status'] = False #修改图片之后,因为8点bot存储了商店图,所以需要重新获取新的背景 + icon_num = VipShopBgDict['bg'][msg.author_id]["background"][num] + VipShopBgDict['bg'][msg.author_id]["background"][num] = VipShopBgDict['bg'][msg.author_id]["background"][0] + VipShopBgDict['bg'][msg.author_id]["background"][0] = icon_num + VipShopBgDict['bg'][msg.author_id]['status'] = False #修改图片之后,因为8点bot存储了商店图,所以需要重新获取新的背景 # #进行缩放+贴上图后保存 # bg_vip = resize_vip(1280,720,bg_vip) @@ -744,7 +744,7 @@ async def vip_shop_bg_set_s(msg: Message, num: str = "err", *arg): # 修改/新增都需要写入文件 with open("./log/VipUserShopBg.json", 'w', encoding='utf-8') as fw2: json.dump(VipShopBgDict, fw2, indent=2, sort_keys=True, ensure_ascii=False) - print(f"[vip-shop-s] Au:{msg.author_id} switch to [{VipShopBgDict[msg.author_id]['background'][0]}]") + print(f"[vip-shop-s] Au:{msg.author_id} switch to [{VipShopBgDict['bg'][msg.author_id]['background'][0]}]") except requester.HTTPRequester.APIRequestFailed as result: await APIRequestFailed_Handler("vip_shop_s",traceback.format_exc(),msg,bot,None,cm) except Exception as result: @@ -760,15 +760,15 @@ async def vip_shop_bg_set_d(msg: Message, num: str = "err", *arg): try: if not await vip_ck(msg): return - if msg.author_id not in VipShopBgDict: + if msg.author_id not in VipShopBgDict['bg']: await msg.reply("您尚未自定义商店背景图!") return num = int(num) - if num < len(VipShopBgDict[msg.author_id]["background"]) and num > 0: + if num < len(VipShopBgDict['bg'][msg.author_id]["background"]) and num > 0: # 删除图片 - del_img_url = VipShopBgDict[msg.author_id]["background"][num] - del VipShopBgDict[msg.author_id]["background"][num] + del_img_url = VipShopBgDict['bg'][msg.author_id]["background"][num] + del VipShopBgDict['bg'][msg.author_id]["background"][num] elif num == 0: await msg.reply("不支持删除当前正在使用的背景图!") return @@ -1110,8 +1110,8 @@ async def login_authtoken(msg: Message, user: str = 'err', passwd: str = 'err',t # 如果是vip用户,则执行下面的代码 if await vip_ck(msg.author_id): global VipShopBgDict #因为换了用户,所以需要修改状态码重新获取商店 - if msg.author_id in VipShopBgDict: - VipShopBgDict[msg.author_id]['status']=False + if msg.author_id in VipShopBgDict['bg']: + VipShopBgDict['bg'][msg.author_id]['status']=False #为了保险起见,保存一下状态信息到文件 with open("./log/VipUserShopBg.json", 'w', encoding='utf-8') as fw1: json.dump(VipShopBgDict, fw1, indent=2, sort_keys=True, ensure_ascii=False) @@ -1397,12 +1397,16 @@ def isSame_Authuuid(msg: Message): # 判断缓存好的图片是否可用 def is_CacheLatest(kook_user_id:str): # 判断vip用户是否在背景图中,且没有 切换登录用户/切换背景图 - if kook_user_id in VipShopBgDict: - is_Status = VipShopBgDict[kook_user_id]['status'] # 如果有切换登录用户/背景图,此为false + is_Status = False + if kook_user_id in VipShopBgDict['bg']: + is_Status = VipShopBgDict['bg'][kook_user_id]['status'] # 如果有切换登录用户/背景图,此为false # 判断图片是不是今天的(可能出现早八提醒的时候出错,导致缓存没有更新,是昨天的图) - is_Today = (VipShopBgDict[kook_user_id]['cache_time']-GetTimeStampOf8AM())>=0 - is_Key = ('cache_img' in VipShopBgDict[kook_user_id]) # 键值是否存在 + if kook_user_id in VipShopBgDict['cache']: + is_Today = (VipShopBgDict['cache'][kook_user_id]['cache_time']-GetTimeStampOf8AM())>=0 + is_Key = ('cache_img' in VipShopBgDict['cache'][kook_user_id]) # 键值是否存在 return is_Today and is_Status and is_Key# 有一个为false,结果就是false + else: + VipShopBgDict['cache'][kook_user_id] = {'cache_time':0} return False # 获取每日商店的命令 @@ -1472,12 +1476,12 @@ async def get_daily_shop(msg: Message, *arg): # 如果是vip而且path存在,背景图/登录用户没有更改过,图片缓存时间正确 if is_vip and (os.path.exists(shop_path)) and is_CacheLatest(msg.author_id): upload_flag=False #有缓存图,直接使用本地已有链接 - dailyshop_img_src = VipShopBgDict[msg.author_id]['cache_img'] - elif is_vip and (msg.author_id in VipShopBgDict): #本地缓存路径不存在,或者缓存过期 + dailyshop_img_src = VipShopBgDict['cache'][msg.author_id]['cache_img'] + elif is_vip and (msg.author_id in VipShopBgDict['bg']): #本地缓存路径不存在,或者缓存过期 play_currency = await fetch_valorant_point(userdict)#获取用户的vp和rp vp = play_currency["Balances"]["85ad13f7-3d1b-5128-9eb2-7cd8ee0b5741"] #vp rp = play_currency["Balances"]["e59aa87c-4cbf-517a-5983-6e81511be9b7"] #R点 - background_img = ('err' if msg.author_id not in VipShopBgDict else VipShopBgDict[msg.author_id]["background"][0]) + background_img = ('err' if msg.author_id not in VipShopBgDict['bg'] else VipShopBgDict['bg'][msg.author_id]["background"][0]) img_ret = await get_shop_img_169(list_shop,vp=vp,rp=rp,bg_img_src=background_img) else:# 普通用户/没有自定义图片的vip用户 img_ret = await get_shop_img_11(list_shop) @@ -1498,8 +1502,8 @@ async def get_daily_shop(msg: Message, *arg): imgByte = imgByteArr.getvalue() dailyshop_img_src = await bot_upimg.client.create_asset(imgByte) # 上传图片 if is_vip: #vip缓存图片 - VipShopBgDict[msg.author_id]['cache_img'] = dailyshop_img_src #设置图片url - VipShopBgDict[msg.author_id]['cache_time'] = time.time() #设置图片缓存的时间 + VipShopBgDict['cache'][msg.author_id]['cache_img'] = dailyshop_img_src #设置图片url + VipShopBgDict['cache'][msg.author_id]['cache_time'] = time.time() #设置图片缓存的时间 # 结束shop的总计时,结果为浮点数,保留两位小数 shop_using_time = format(time.perf_counter() - start, '.2f') @@ -2191,7 +2195,7 @@ async def auto_skin_notify(): vp = play_currency["Balances"]["85ad13f7-3d1b-5128-9eb2-7cd8ee0b5741"] #vp rp = play_currency["Balances"]["e59aa87c-4cbf-517a-5983-6e81511be9b7"] #R点 # 设置用户背景图,如果在则用,否则返回err - background_img = ('err' if vip not in VipShopBgDict else VipShopBgDict[vip]["background"][0]) + background_img = ('err' if vip not in VipShopBgDict['bg'] else VipShopBgDict['bg'][vip]["background"][0]) img_ret = await get_shop_img_169(list_shop,vp=vp,rp=rp,bg_img_src=background_img) if img_ret['status']: bg_shop = img_ret['value'] @@ -2200,8 +2204,8 @@ async def auto_skin_notify(): log_time += f"- [Drawing] {format(time.time() - draw_time,'.4f')} - [Au] {vip}" print(log_time) dailyshop_img_src = await bot_upimg.client.create_asset(img_shop_path) # 上传图片 - VipShopBgDict[vip]['cache_img'] = dailyshop_img_src # 缓存图片url - VipShopBgDict[vip]['cache_time'] = time.time() #设置图片缓存的时间 + VipShopBgDict['cache'][vip]['cache_img'] = dailyshop_img_src # 缓存图片url + VipShopBgDict['cache'][vip]['cache_time'] = time.time() #设置图片缓存的时间 else: #如果图片没有正常返回,那就发送文字版本 shop_text = "" for skinuuid in list_shop: From 8eb1313c528bcafabef657f00c1f6bf4101b7cd2 Mon Sep 17 00:00:00 2001 From: Ewait Date: Sun, 15 Jan 2023 11:37:06 +0800 Subject: [PATCH 08/18] fix(shopimg):fix bad transparency mask in sm_comp_169 --- code/endpoints/ShopImg.py | 1 + 1 file changed, 1 insertion(+) diff --git a/code/endpoints/ShopImg.py b/code/endpoints/ShopImg.py index ccd292e..22c903f 100644 --- a/code/endpoints/ShopImg.py +++ b/code/endpoints/ShopImg.py @@ -153,6 +153,7 @@ def sm_comp_169(skin_img_url, skin_name, price, skin_level_icon, skinuuid): # 缩放皮肤等级图标 level_icon = level_icon.resize((25, 25), Image.Resampling.LANCZOS) + level_icon = level_icon.convert('RGBA') bg.paste(level_icon, (368, 11), level_icon) # 在指定位置粘贴皮肤等级图标 text = zhconv.convert(skin_name, 'zh-cn') # 将名字简体化 draw = ImageDraw.Draw(bg) # 让bg这个图层能被写字 From e5f6babc257170f947726d82871b0b942fbcb258 Mon Sep 17 00:00:00 2001 From: Ewait Date: Sun, 15 Jan 2023 11:56:36 +0800 Subject: [PATCH 09/18] fix(main): add status update in shop/notify task for vip user --- code/main.py | 21 +++++++++++++-------- screenshot/log.png | Bin 7514 -> 7459 bytes 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/code/main.py b/code/main.py index 1902bd0..22caca8 100644 --- a/code/main.py +++ b/code/main.py @@ -413,7 +413,8 @@ async def buy_vip_uuid(msg: Message, uuid: str = 'err', *arg): try: #把bot传过去是为了让阿狸在有人成兑换激活码之后发送消息到log频道 ret = await using_vip_uuid(msg, uuid, bot,debug_ch) - + global VipShopBgDict #在用户兑换vip的时候就创建此键值 + VipShopBgDict['cache'][msg.author_id] = {'cache_time':0,'cache_img':None} except Exception as result: await BaseException_Handler("vip-u",traceback.format_exc(),msg,bot,None,None,"建议加入帮助频道找我康康到底是啥问题") err_str = f"ERR! [{GetTime()}] vip-u\n```\n{traceback.format_exc()}\n```" @@ -1403,10 +1404,10 @@ def is_CacheLatest(kook_user_id:str): # 判断图片是不是今天的(可能出现早八提醒的时候出错,导致缓存没有更新,是昨天的图) if kook_user_id in VipShopBgDict['cache']: is_Today = (VipShopBgDict['cache'][kook_user_id]['cache_time']-GetTimeStampOf8AM())>=0 - is_Key = ('cache_img' in VipShopBgDict['cache'][kook_user_id]) # 键值是否存在 - return is_Today and is_Status and is_Key# 有一个为false,结果就是false - else: - VipShopBgDict['cache'][kook_user_id] = {'cache_time':0} + is_Cache = VipShopBgDict['cache'][kook_user_id]['cache_img'] != None + return is_Today and is_Status and is_Cache# 有一个为false,结果就是false + else:# 如果不在,初始化为none + VipShopBgDict['cache'][kook_user_id] = {'cache_time':0,'cache_img':None} return False # 获取每日商店的命令 @@ -1450,7 +1451,8 @@ async def get_daily_shop(msg: Message, *arg): } log_time = "" a_time = time.time() - global UserShopDict # UserShopDict每天早八会被清空,如果用户在里面且玩家id一样,那么说明已经获取过当日商店了 + global UserShopDict,VipShopBgDict + # UserShopDict每天早八会被清空,如果用户在里面且玩家id一样,那么说明已经获取过当日商店了 if msg.author_id in UserShopDict and isSame_Authuuid(msg): #直接使用本地已有的当日商店 list_shop = UserShopDict[msg.author_id]["SkinsPanelLayout"]["SingleItemOffers"] # 商店刷出来的4把枪 timeout = shop_time_remain() # 通过当前时间计算商店剩余时间 @@ -1501,7 +1503,8 @@ async def get_daily_shop(msg: Message, *arg): bg.save(imgByteArr, format='PNG') imgByte = imgByteArr.getvalue() dailyshop_img_src = await bot_upimg.client.create_asset(imgByte) # 上传图片 - if is_vip: #vip缓存图片 + if is_vip: #vip缓存图片+设置状态 + if msg.author_id in VipShopBgDict['bg']: VipShopBgDict['bg'][msg.author_id]['status'] = True VipShopBgDict['cache'][msg.author_id]['cache_img'] = dailyshop_img_src #设置图片url VipShopBgDict['cache'][msg.author_id]['cache_time'] = time.time() #设置图片缓存的时间 # 结束shop的总计时,结果为浮点数,保留两位小数 @@ -2138,7 +2141,7 @@ async def check_notify_err_user(msg:Message): #独立函数,为了封装成命令+定时 async def auto_skin_notify(): - global SkinNotifyDict, SkinRateDict, UserShopDict + global SkinNotifyDict, SkinRateDict, UserShopDict,VipShopBgDict try: print(f"[BOT.TASK.NOTIFY] Start at {GetTime()}") #开始的时候打印一下 UserShopDict = {}#清空用户的商店 @@ -2204,8 +2207,10 @@ async def auto_skin_notify(): log_time += f"- [Drawing] {format(time.time() - draw_time,'.4f')} - [Au] {vip}" print(log_time) dailyshop_img_src = await bot_upimg.client.create_asset(img_shop_path) # 上传图片 + VipShopBgDict['cache'][vip] = {} VipShopBgDict['cache'][vip]['cache_img'] = dailyshop_img_src # 缓存图片url VipShopBgDict['cache'][vip]['cache_time'] = time.time() #设置图片缓存的时间 + if vip in VipShopBgDict['bg']: VipShopBgDict['bg'][vip]['status'] = True else: #如果图片没有正常返回,那就发送文字版本 shop_text = "" for skinuuid in list_shop: diff --git a/screenshot/log.png b/screenshot/log.png index f9aa67b35456ddda0fcc8f6ba4c12fc98f07596c..6bf07fe178fa278e5c32fdfc4491ea224fd9c5bf 100644 GIT binary patch literal 7459 zcmbtZWmHsOyB|bkXhs?-M+B6SPH7lGr9>G*>28p8NP!WC22lwK2?0^MyFqCrrKB4X zaOk+3|NGu`*Zp+gweAs{RP*Lq1V9A zZA3^11j4lb5GkkiGI=Y-+gWRbxznF0fE`IfWTWb94DGdeIcAz2(DE_<<749opT-sK znW#hN6%&G`H)Gy?=6e^mF+j@|t$0_E*dXDUo`mFE>ko@8>eXQ4+f@%pJal0`=2U2m z&k3O`&&o`Ft+!`f@BHs=!8py|QY%xg9{wu_QjL369|$0Ae59>>JvvF7S~{;x=z~oX z_FDt{E0SRq!im+_j>Qg5W}xvFZQ5Ayp~)zI)g)ZbNw}TTR6s^`@(| zUs^>^Pp{1X;#^DT^+Q;q=>{nk1!C1k-qlr5>S!@;czpap2nB0YqM=w@aB#4Cu0dxp zde8D%nKcXs^Zh%he5Zgcj(EP@J!2!NN!)drz1osA?wRhu5Jv5T$l&kk+EDCjpTu@V zqF-|$0r;|nOUiHH{8mzl7CAab!heF%zHck$<#|Q%w z`#v}|JX~5@Dsz~uc>BJYoruo}EuT(Ft%wH;z|Oisi1V|Ph2OQ?N^){|Vd3HY&a<)z{i*?N2GwgQjQcLO%))QcZ&eI~9ad49N1Gp%e2P8hc3b9RiY z=rVpnNOG(LD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rC5fZ;sUXgLkG7HDyg?fudRPe*h^D Brz!vd From 99b7b4dab1d53f34ed4ef19ec587b1311f66324d Mon Sep 17 00:00:00 2001 From: Ewait Date: Sun, 15 Jan 2023 12:27:55 +0800 Subject: [PATCH 10/18] fix(ApiHandler): only fetch vp/rp when 16-9 img --- code/endpoints/ApiHandler.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/endpoints/ApiHandler.py b/code/endpoints/ApiHandler.py index 30122a9..0e0a7e6 100644 --- a/code/endpoints/ApiHandler.py +++ b/code/endpoints/ApiHandler.py @@ -90,7 +90,6 @@ async def base_img_request(request): resp = await fetch_daily_shop(userdict) #获取每日商店 print(f'[{GetTime()}] [Api] fetch_daily_shop success') list_shop = resp["SkinsPanelLayout"]["SingleItemOffers"] # 商店刷出来的4把枪 - res_vprp = await fetch_vp_rp_dict(userdict) # 获取vp和r点 # 自定义背景 if 'img_src' in params: @@ -105,6 +104,7 @@ async def base_img_request(request): if 'img_ratio' in params and params['img_ratio']=='1': ret = await get_shop_img_11(list_shop,bg_img_src=img_src) else: + res_vprp = await fetch_vp_rp_dict(userdict) # 只有16-9的图片需获取vp和r点 ret = await get_shop_img_169(list_shop,vp=res_vprp['vp'],rp=res_vprp['rp'],bg_img_src=img_src) # 打印计时 print("[IMGdraw]",format(time.perf_counter() - start, '.2f'))# 结果为浮点数,保留两位小数 From 34d12146a54dc32bb8302b3c61c5a0abb1cfa4f6 Mon Sep 17 00:00:00 2001 From: Ewait Date: Sun, 15 Jan 2023 12:28:13 +0800 Subject: [PATCH 11/18] docs(api): update api docs --- docs/valorant-shop-img-api.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/valorant-shop-img-api.md b/docs/valorant-shop-img-api.md index 67e5df1..ed93efb 100644 --- a/docs/valorant-shop-img-api.md +++ b/docs/valorant-shop-img-api.md @@ -13,7 +13,7 @@ Api是一个网页链接,能够方便的被用户使用或被开发者调用 | ---------- | --------------------- | -------- | | /shop-img | 直接返回并跳转商店的图片 | 正常 | | /shop-url | 以`json`格式返回商店图片url | 正常 | -| /tfa | 邮箱验证接口,需和/shop-url接口配合使用 | 正常 | +| /tfa | 邮箱验证接口,需和`/shop-url`接口配合使用 | 正常 | ## 1.使用示例 @@ -51,7 +51,11 @@ https://val.outpost54.top/shop-img?token=API的密钥&account=账户&passwd=密 结果示例图(16-9) -16-9-img-result +16-9-img-result + +结果示例图(1-1) + +1-1-img-result ## 2.注意事项 From 6a38519a747a3488fee1a45f720bb7b67ef0b9f0 Mon Sep 17 00:00:00 2001 From: Ewait Date: Sun, 15 Jan 2023 16:19:17 +0800 Subject: [PATCH 12/18] feat(api): add traceback print in except --- code/api.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/code/api.py b/code/api.py index 98bcd41..deb3119 100644 --- a/code/api.py +++ b/code/api.py @@ -26,7 +26,9 @@ async def get_dailshop_img(request): else: return web.Response(body=json.dumps(ret,ensure_ascii=False), content_type='application/json') except: - return web.Response(body=json.dumps({'code':200,'message': 'unkown err','info':f'未知错误','except':f'{traceback.format_exc()}'},ensure_ascii=False), content_type='application/json') + err_cur = traceback.format_exc() + print(f"[{GetTime()}] [Api] ERR in /shop-img\n{err_cur}") + return web.Response(body=json.dumps({'code':200,'message': 'unkown err','info':f'未知错误','except':f'{err_cur}'},ensure_ascii=False), content_type='application/json') # 获取图片url @routes.get('/shop-url') @@ -36,7 +38,9 @@ async def get_dailshop_img(request): ret = await base_img_request(request) return web.Response(body=json.dumps(ret,ensure_ascii=False), content_type='application/json') except: - return web.Response(body=json.dumps({'code':200,'message': 'unkown err','info':f'未知错误','except':f'{traceback.format_exc()}'},ensure_ascii=False), content_type='application/json') + err_cur = traceback.format_exc() + print(f"[{GetTime()}] [Api] ERR in /shop-url\n{err_cur}") + return web.Response(body=json.dumps({'code':200,'message': 'unkown err','info':f'未知错误','except':f'{err_cur}'},ensure_ascii=False), content_type='application/json') @routes.post('/tfa') async def get_dailshop_img(request): @@ -45,7 +49,9 @@ async def get_dailshop_img(request): ret = await tfa_code_requeset(request) return web.Response(body=json.dumps(ret,ensure_ascii=False), content_type='application/json') except: - return web.Response(body=json.dumps({'code':200,'message': 'unkown err','info':f'未知错误','except':f'{traceback.format_exc()}'},ensure_ascii=False), content_type='application/json') + err_cur = traceback.format_exc() + print(f"[{GetTime()}] [Api] ERR in /tfa\n{err_cur}") + return web.Response(body=json.dumps({'code':200,'message': 'unkown err','info':f'未知错误','except':f'{err_cur}'},ensure_ascii=False), content_type='application/json') print(f"[API Start] starting at {GetTime()}") From 91672755799e24dbd80ad3cf25d9f94aba3782f5 Mon Sep 17 00:00:00 2001 From: Ewait Date: Sun, 15 Jan 2023 16:19:33 +0800 Subject: [PATCH 13/18] feat(makefile): add ps to search for pid --- code/makefile | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/code/makefile b/code/makefile index 7c2aa9d..0356db3 100644 --- a/code/makefile +++ b/code/makefile @@ -1,3 +1,7 @@ .PHONY:run run: - nohup py3 -u start.py >> ./log/bot.log 2>&1 & \ No newline at end of file + nohup py3 -u start.py >> ./log/bot.log 2>&1 & + +.PHONY:ps +ps: + ps jax | head -1 && ps jax | grep start.py | grep -v grep \ No newline at end of file From 59f27f38d8d4dc4fc1d369ea85a14abc8593764f Mon Sep 17 00:00:00 2001 From: Ewait Date: Sun, 15 Jan 2023 20:46:58 +0800 Subject: [PATCH 14/18] fix(ShopImg): using standrand_x/y to replace 1.78(1280/720) --- code/endpoints/ShopImg.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/code/endpoints/ShopImg.py b/code/endpoints/ShopImg.py index 22c903f..e21f156 100644 --- a/code/endpoints/ShopImg.py +++ b/code/endpoints/ShopImg.py @@ -98,7 +98,7 @@ def resize_standard(standard_x, standard_y, img): log_info = "[resize_std] " log_info += f"原始图片大小:({w},{h}) - " ratio = w / h - if ratio <= 1.78: + if ratio <= standard_x/standard_y: sizeco = w / standard_x log_info += f"缩放系数:{format(sizeco,'.3f')} - " w_s = int(w / sizeco) From 69ca8993f42d561f1fe9c12ae3dc923e7b76edcb Mon Sep 17 00:00:00 2001 From: Ewait Date: Sun, 15 Jan 2023 20:49:56 +0800 Subject: [PATCH 15/18] feat(api): add GetTime print in api log --- code/endpoints/ApiHandler.py | 2 +- code/endpoints/ApiToken.py | 11 ++++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/code/endpoints/ApiHandler.py b/code/endpoints/ApiHandler.py index 0e0a7e6..a66c3c3 100644 --- a/code/endpoints/ApiHandler.py +++ b/code/endpoints/ApiHandler.py @@ -107,7 +107,7 @@ async def base_img_request(request): res_vprp = await fetch_vp_rp_dict(userdict) # 只有16-9的图片需获取vp和r点 ret = await get_shop_img_169(list_shop,vp=res_vprp['vp'],rp=res_vprp['rp'],bg_img_src=img_src) # 打印计时 - print("[IMGdraw]",format(time.perf_counter() - start, '.2f'))# 结果为浮点数,保留两位小数 + print(f"[{GetTime()}] [IMGdraw]",format(time.perf_counter() - start, '.2f'))# 结果为浮点数,保留两位小数 start = time.perf_counter() if ret['status']: diff --git a/code/endpoints/ApiToken.py b/code/endpoints/ApiToken.py index 7cd82fe..086e97e 100644 --- a/code/endpoints/ApiToken.py +++ b/code/endpoints/ApiToken.py @@ -1,6 +1,7 @@ import uuid import json import time +from endpoints.Gtime import GetTime # 所有token with open("./log/ApiToken.json", 'r', encoding='utf-8') as frpr: @@ -16,7 +17,7 @@ def save_token_files(text=''): global ApiTokenDict with open("./log/ApiToken.json", 'w', encoding='utf-8') as fw2: json.dump(ApiTokenDict, fw2, indent=2, sort_keys=True, ensure_ascii=False) - print(f"[token] files saved! {text}") + print(f"[{GetTime()}] [API token] files saved! [{text}]") # 生成uuid def create_token_uuid(num: int = 10, day: int = 30): @@ -53,7 +54,7 @@ def create_token_uuid(num: int = 10, day: int = 30): for uuid in NewUuid: text += f"{uuid}" + "\n" - print(f"[token] create_token_uuid - num:{num} - day:{day}") + print(f"[{GetTime()}] [token] create_token_uuid - num:{num} - day:{day}") return text # 检查用户token是否失效或者不是token @@ -71,13 +72,13 @@ async def token_ck(token:str): del ApiTokenDict['data'][token] # 更新uuid save_token_files("token expire") - print(f"[token-ck] T:{token} out of date") + print(f"[{GetTime()}] [token-ck] T:{token} out of date") return False else:#没有过期,返回真 - print(f"[token-ck] T:{token} is token") + print(f"[{GetTime()}] [token-ck] T:{token} is token") return True else:#token不在 - print(f"[token-ck] T:{token} not token") + print(f"[{GetTime()}] [token-ck] T:{token} not token") return False From 0e2c66134a0425e80b879b52c5fa0673e3ff21f2 Mon Sep 17 00:00:00 2001 From: Ewait Date: Sun, 15 Jan 2023 20:50:10 +0800 Subject: [PATCH 16/18] docs(api): update api docs --- docs/valorant-shop-img-api.md | 22 ++++++---------------- 1 file changed, 6 insertions(+), 16 deletions(-) diff --git a/docs/valorant-shop-img-api.md b/docs/valorant-shop-img-api.md index ed93efb..4351d85 100644 --- a/docs/valorant-shop-img-api.md +++ b/docs/valorant-shop-img-api.md @@ -142,29 +142,19 @@ import requests url = "https://val.outpost54.top/shop-url" params = { - "token":"你的api-token", + "token":"api-token", "account": "拳头账户", "passwd": "拳头密码", "img-src": "https://img.kookapp.cn/assets/2022-09/KV5krdRx080qo0f0.jpg" } -res = requests.get(url,params=params,verify=False) +res = requests.get(url,params=params) print(res.json()) ~~~ -由于ssl证书原因,您使用的时候可能会遇到下面的报错,请忽略。 +运行即可获得商店返回结果 -~~~ -/home/muxue/.local/lib/python3.10/site-packages/urllib3/connectionpool.py:1045: InsecureRequestWarning: Unverified HTTPS request is being made to host 'val.outpost54.top'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings - warnings.warn( -~~~ - -网站使用的是`JOYSSL`提供的ssl证书,直接访问**不会**报不安全。本人很菜,不知道这里的报错是啥原因 +~~~~ +{'code': 0, 'message': 'https://img.kookapp.cn/attachments/2023-01/15/mLjpR95mZ20rs0rs.png', 'info': '商店图片获取成功'} +~~~~ -可以用下面的办法解除这个报错 - -~~~python -from urllib3.connectionpool import InsecureRequestWarning -import urllib3 -urllib3.disable_warnings(InsecureRequestWarning) -~~~ From 87fa9125ed7ca1a90067c532b016f24a79947f2f Mon Sep 17 00:00:00 2001 From: Ewait Date: Sun, 15 Jan 2023 23:14:20 +0800 Subject: [PATCH 17/18] feat(EzAuth): add cookie transfer from EzAuth to RiotAuth --- code/endpoints/EzAuth.py | 19 ++++++++++++++++++- code/main.py | 6 +++--- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/code/endpoints/EzAuth.py b/code/endpoints/EzAuth.py index 5101499..9fd02a3 100644 --- a/code/endpoints/EzAuth.py +++ b/code/endpoints/EzAuth.py @@ -11,6 +11,7 @@ import copy import random from riot_auth import auth_exceptions,RiotAuth +from http.cookies import SimpleCookie RiotClient = "RiotClient/62.0.1.4852117.4789131" User2faCode = {} @@ -115,6 +116,7 @@ def authorize(self,username, password,key): self.base_headers = {'User-Agent': f"{RiotClient} %s (Windows;10;;Professional, x64)",'Authorization': f'Bearer {self.access_token}',} self.session.headers.update(self.base_headers) + self.cookie = self.session.cookies self.entitlements_token = self.get_entitlement_token() self.emailverifed = self.get_emailverifed() @@ -214,7 +216,22 @@ def get_Token(self): } return userdict -#EzAuth(username="",password="") + def get_CookieDict(self): + # cookie转换成dict + ck_dict = requests.utils.dict_from_cookiejar(self.cookie) + return ck_dict + + async def get_RiotAuth(self): + # cookie dict导入到SimpleCookie + Scookie = SimpleCookie(self.get_CookieDict()) + rauth = RiotAuth() + # 更新cookie + rauth._cookie_jar.update_cookies(Scookie) + ret = await rauth.reauthorize() # 测试登录 + if ret: + return rauth + else: #失败返回None + raise Exception('EzAuth change to RiotAuth failed') ###################################### Riot Auth ###################################################### diff --git a/code/main.py b/code/main.py index 22caca8..2b91365 100644 --- a/code/main.py +++ b/code/main.py @@ -1079,7 +1079,7 @@ async def login_authtoken(msg: Message, user: str = 'err', passwd: str = 'err',t th = threading.Thread(target=auth2fa, args=(user,passwd,key)) th.start() resw = await auth2faWait(key=key,msg=msg) # 随后主执行流来这里等待 - res_auth = resw['auth'] + res_auth = await resw['auth'].get_RiotAuth() # 直接获取RiotAuth对象 # 如果没有抛出异常,那就是完成登录了 UserTokenDict[msg.author_id] = {'auth_user_id': res_auth.user_id, 'GameName':'None', 'TagLine':'0000'} userdict = { @@ -1234,8 +1234,8 @@ async def check_re_auth(def_name: str = "", msg: Union[Message, str] = ''): user_id = "[ERR!]" #先给userid赋值,避免下方打印的时候报错(不出意外是会被下面的语句修改的) try: user_id = msg if isinstance(msg, str) else msg.author_id #如果是str就直接用 - if UserAuthDict[user_id]['2fa']: - return True #先判断是否为2fa账户,如果是,那就不进行reauthrize操作 + # if UserAuthDict[user_id]['2fa']: + # return True #先判断是否为2fa账户,如果是,那就不进行reauthrize操作 auth = UserAuthDict[user_id]['auth'] userdict = { 'auth_user_id': auth.user_id, From ba3234a31df649773dce1a9fff85a0d7e7098568 Mon Sep 17 00:00:00 2001 From: Ewait Date: Mon, 16 Jan 2023 08:52:40 +0800 Subject: [PATCH 18/18] docs(README): update README/README_EN --- README.md | 43 ++++++++++++++++-------------------------- README_EN.md | 53 +++++++++++++++++----------------------------------- 2 files changed, 33 insertions(+), 63 deletions(-) diff --git a/README.md b/README.md index 203ed63..95c9362 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ ## 功能 -当前机器人基本完善,目前支持回复Valorant游戏错误码、查询Valorant每日商店/夜市/vp/r点,和一些简单功能。 +当前机器人基本完善,目前支持回复Valorant游戏错误码、查询Valorant每日商店/夜市/vp/r点,和一些简单功能。邮箱验证用户登录也已添加。 下面是目前支持的功能列表: @@ -29,7 +29,6 @@ | `/Ahri` | 回复使用帮助(因`/help`和其他机器人冲突,故用阿狸的英文名`Ahri`替代) | | `/vhelp` | Valorant相关查询功能的帮助命令 | -关于商店查询的**初步功能**已经添加,但是其`稳定性/是否封号`未知,建议**谨慎**使用! | 游戏相关 | 功能 | @@ -42,7 +41,7 @@ | `/logout` | 退出riot账户登录 | | `/shop` | 获取每日商店的4个皮肤 | | `/night` | 获取夜市的6个皮肤 | -| `/uinfo`或`/point` | 获取玩家卡面和称号,剩余vp和r点 | +| `/uinfo` 或 `/point` | 获取玩家卡面和称号,剩余vp和r点 | | `/notify-a 皮肤名` | 搜索皮肤名,并提供选项将指定皮肤加入商店提醒 | | `/notify-l` | 查看当前已经设置了提醒的皮肤 | | `/notify-d 皮肤uuid` | 使用uuid删除不需要提醒的皮肤 | @@ -56,17 +55,11 @@ |`/rts 序号 打分 吐槽`|选中皮肤序号,给该皮肤打个分(0~100) 再吐槽一下!| |`/kkn`|查看昨日评分最高/最低的用户| -更多vip用户的特殊功能 +每日商店刷枪提醒功能 `/notify-a` 需要用户**保持登录状态**,bot会在每天的`08:00AM`遍历列表,查看您的商店是否刷出了您想要的皮肤;如果是vip用户,则会直接发送当日商店的图片。 ->* 「全新商店返回值」vip用户将获取到16-9的超帅商店返回值 ->* 「保存登录信息」vip用户登陆后,阿狸会自动保存您的cookie。在阿狸维护重启的时候,您的登录信息不会丢失 ->* 「早八商店提醒」阿狸将在早8点获取vip用户的每日商店并私聊发图给用户,同时会对这张图片进行缓存,当天使用/shop命令的时候,只需2s获取结果,三倍于普通用户的响应速度! -> ->目前商店查询背景图diy支持16-9(横屏)的图片,图片url获取:`PC端将图片上传到kook→点击图片→底部...处复制图片链接→使用/vip-shop命令设置背景` [教程图](https://img.kookapp.cn/assets/2022-12/nICYcewY8a0u00yt.png) -> ->请不要设置违规图片(擦边也不行)!若因为您上传违禁图片后导致阿狸被封,您将被剥夺vip并永久禁止兑换vip +cookie 登录信息将在2-3天后失效,所以皮肤提醒功能会出现用户没有登录而无法获取的情况。 -每日商店刷枪提醒功能需要用户**保持登录状态**,bot会在每天的`08:01`遍历列表,查看您的商店是否刷出了您想要的皮肤 +`/rate` 参与的打分,其会显示在 `/shop` 商店查询结果的尾部,同时统计当日商店最高分和最低分,可以在第二天用 `/kkn` 来查看。 | 其他命令 | 功能 | | ----------------- | ------------------------------------------------------------ | @@ -99,6 +92,8 @@ vip_shop +---- + ### valorant-shop-img-api > Api源码见 [api.py](./code/api.py) @@ -123,13 +118,9 @@ Api请求返回示例图: pip install -r requirements.txt ~~~ -> Q:为何`khl.py`只需要3.6.8以上版本,而本仓库需要3.8+? -> -> A:因为Valorant的第三方`Python Api`需要3.8+版本 - -建议根据[khl.py](https://github.com/TWT233/khl.py)的`example`教程,学习KOOK机器人的基本搭建(很简单的,相信我) +建议根据 [khl.py/example](https://github.com/TWT233/khl.py/tree/main/example) 的教程,学习KOOK机器人的基本搭建(很简单的,相信我) -如果你想直接使用本机器人,可以转到本仓库[WIKI](https://github.com/Aewait/Valorant-kaiheila-bot/wiki)查看更多引导内容 +如果你想直接使用本机器人,可以转到本仓库 [WIKI](https://github.com/Aewait/Valorant-kaiheila-bot/wiki) 查看更多引导内容 ---- @@ -148,9 +139,7 @@ pip install -r requirements.txt - [ ] 以类似抽卡的方式,用按钮、图片等等方式显示用户的夜市 - [ ] Api增加使用Riot Token调用的接口,方便本地管理登录信息,调用api画图 -~~由于很多人在使用类似商店查询软件后被ban,我决定正式停止相关功能的开发~~ - -咳咳,虽然初步的商店查询功能已经上线,但是其是否`封号`依旧有争论!目前功能已经上线一个月有余,且询问过外网开发者,其表示没有听说过有人因为使用api被封号。 +咳咳,虽然初步的商店查询功能已经上线,但是其是否`封号`依旧有争论!目前功能已经上线半年有余,未出现异常现象;且询问过外网开发者,其表示没有听说过有人因为使用api查询而被封号。 **如果您担心风险,请不要使用相关功能**!bot的`/vhelp`命令`/login`命令中有相关警告提示,使用即代表您同意了承担风险! @@ -161,16 +150,16 @@ pip install -r requirements.txt ## 依赖 由于本人压根没有系统的学过Python,所以本仓库的很多代码都是根据他人教程修改后使用的 -* 基本框架参考[khl.py](https://github.com/TWT233/khl.py)提供的`kook sdk`以及使用教程 -* Valorant游戏`leaderboard`排行榜获取基于 [frissyn/valorant.py](https://github.com/frissyn/valorant.py/) 提供的`sdk` -* Valorant游戏主要查询代码基于 [ValorantClientAPI](https://github.com/HeyM1ke/ValorantClientAPI) 项目提供的`api文档` +* 基本框架参考[khl.py](https://github.com/TWT233/khl.py)提供的 `kook sdk` 以及使用教程 +* Valorant游戏皮肤/捆绑包/玩家卡面等素材源自 [valorant-api.com](https://valorant-api.com/) +* Valorant游戏主要商店查询代码基于 [ValorantClientAPI](https://github.com/HeyM1ke/ValorantClientAPI) 项目提供的 `api文档` * 通过账户密码获取 `riot_auth_token` 基于 [floxay/python-riot-auth](https://github.com/floxay/python-riot-auth) 项目 ### 特别鸣谢🎁 -* [@DeeChael](https://github.com/DeeChael) for helping me debug -* [@Edint386](https://github.com/Edint386) for adding `PIL_code` for `/shop` -* [@staciax](https://github.com/staciax) for [Valorant-DiscordBot/issues/74](https://github.com/staciax/Valorant-DiscordBot/issues/74) +* [@DeeChael](https://github.com/DeeChael) 帮我 debug +* [@Edint386](https://github.com/Edint386) 帮助添加了 `PIL` 代码来进行 `/shop` 的画图 +* [@staciax](https://github.com/staciax) for [Valorant-DiscordBot/issues/74](https://github.com/staciax/Valorant-DiscordBot/issues/74) & [issues/97](https://github.com/staciax/Valorant-DiscordBot/issues/97) ### 支持本项目😘 diff --git a/README_EN.md b/README_EN.md index 1b633bc..3ff2067 100644 --- a/README_EN.md +++ b/README_EN.md @@ -19,11 +19,6 @@ KOOK(once called kaiheila) is a Chinese voice communication software. >Because this bot are only used in Chinese platform,so I didn't write a more detail Readme in English.Sorry for that -I just develop basic `/login` and `/shop` to fetch daily shop, hoping it's save for using - -* night market check as `/night` command was publish at `v0.2.4` - ----- ## Command @@ -59,9 +54,9 @@ Recommended to use after the Valorant_Function is stable. |`/rts NO. point comment`|select skin_no. to rate a point(0~100) and leave a comment to it| |`/kkn`|checkout yesterday's heighest/lowest rate_point of daily shop | -notify function require user to stay `login`, bot wil fetch your daily shop at `08:01AM GMT+8` .If the skin is in daily shop, bot will send a private message to user. +notify function require user to stay `login`, bot wil fetch your daily shop at `08:00AM GMT+8` .If the skin is in daily shop, bot will send a private message to user. -If the user is a vip, the bot will also send the full picture of the store on that day through private message. +If the user is a vip, the bot will also send the full picture of the daily-shop on that day through private message. >Because the bot is only using in Chinese platform, the skin `name` only support `zh-TW` @@ -93,56 +88,42 @@ You can find image examples for the functions in [screenshot](./screenshot) flod night +api_shop_img + -For more guild and information, check out [wiki pages](https://github.com/Aewait/Valorant-kaiheila-bot/wiki) ---- -## Breaking Changes at `V0.2.0` -First Breaking Changes for bot -## 1. publish vip! -### 1.1 add vip daily shop reply -vip user will get different daily shop reply from bot. -* normal user get `1000*1000` img -* vip user get `1280*720` img +## How to used? + -this background can be modified by vip-user,using picture they liked! +make sure your Windows/Linux `Python` version `3.8+` -vip_shop +~~~ +pip install -r requirements.txt +~~~ -### 1.2 add special command for vip user -* `vip-u`: get vip from uuid -* `vip-c`: check remaining time for vip -* `vip-l`: list vip user -* `vip-shop`: vip user can modify their background of daily shop +It is highly recommand to checkout [khl.py/example](https://github.com/TWT233/khl.py/tree/main/example) first for basic kook bot init -### 1.3 more great fuctions! -* vip user will get automatic daily shop reply at `8AM BJS` -* bot will log vip user daily shop img, next time when vip user use `/shop` command, bot will upload it from local path instead of drawing the img,which will save `2-3s` of response time -* using `aiohttp cookie_jar` to save vip user cookie, don't need to login again when bot restart because of maintenance。 +If you want to use this bot, go [WIKI](https://github.com/Aewait/Valorant-kaiheila-bot/wiki) for more infomation -## 2. other changes -* `add_date` will fetch `debug_channel` at start,don't need to fetch every time when exception -* change err reply to card message, bot will update msg instead of replying a new one when using `/shop` or `/uinfo` -* add `class icon` for easy manage icon-url --- ## About Many codes in this repo are modified and used according to others' tutorials -* KOOK_api base on [khl.py](https://github.com/TWT233/khl.py) -* ValorantGameApi base on [frissyn/valorant.py](https://github.com/frissyn/valorant.py/) +* KOOK Bot base on [khl.py](https://github.com/TWT233/khl.py) +* Valorant Skin Api base on [valorant-api.com](https://valorant-api.com/) * Main fetch_code base on [ValorantClientAPI](https://github.com/HeyM1ke/ValorantClientAPI) -* Fetch riot_auth_token base on [floxay/python-riot-auth](https://github.com/floxay/python-riot-auth) +* Fetch riot_auth_token base on [floxay/python-riot-auth](https://github.com/floxay/python-riot-auth) & ### Special Thanks🎁 * [@DeeChael](https://github.com/DeeChael) for helping me debug * [@Edint386](https://github.com/Edint386) for adding PIL_code for `/shop` -* [@staciax](https://github.com/staciax) for [Valorant-DiscordBot/issues/74](https://github.com/staciax/Valorant-DiscordBot/issues/74) +* [@staciax](https://github.com/staciax) for [Valorant-DiscordBot/issues/74](https://github.com/staciax/Valorant-DiscordBot/issues/74) & [issues/97](https://github.com/staciax/Valorant-DiscordBot/issues/97) -If you like this project,please hit a star!✨ -> sorry for my poor English +If you like this project,please hit a star!✨ \ No newline at end of file