Skip to content

Commit

Permalink
Merge pull request #15 from Valorant-Shop-CN/develop
Browse files Browse the repository at this point in the history
chown(v1.2.2): release  v1.2.2
  • Loading branch information
musnows committed Jun 9, 2023
2 parents 9e5c51e + fd8d267 commit a5a2d6d
Show file tree
Hide file tree
Showing 11 changed files with 249 additions and 136 deletions.
55 changes: 39 additions & 16 deletions code/api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import json
import traceback
from aiohttp import web
from aiohttp import web, web_request
from pkg.utils.Gtime import get_time
from pkg.utils.api import ApiHandler
from pkg.utils.log.Logging import _log
Expand All @@ -11,7 +11,7 @@

# 基础返回
@routes.get('/')
async def hello_world(request): # put application's code here
async def hello_world(request:web_request.Request): # put application's code here
_log.info(f"request | root-url")
return web.Response(body=json.dumps(
{
Expand All @@ -30,7 +30,7 @@ async def hello_world(request): # put application's code here

# 提供4个皮肤uuid,返回图片
@routes.get('/shop-draw')
async def get_shop_draw(request):
async def get_shop_draw(request:web_request.Request):
_log.info(f"request | /shop-draw")
try:
ret = await ApiHandler.img_draw_request(request)
Expand All @@ -55,14 +55,14 @@ async def get_shop_draw(request):

# 直接跳转图片
@routes.get('/shop-img')
async def get_shop_img(request):
async def get_shop_img(request:web_request.Request):
_log.info(f"request | /shop-img")
try:
params = request.rel_url.query
ret = await ApiHandler.login_request(request,"GET")
if ret['code'] == 0:
# 如果url不在,或者值不为0,则303跳转图片
if 'url' not in params or str(params['url']) != '0':
# 如果url不在,或者值不为1,则303跳转图片
if 'url' not in params or str(params['url']) != '1':
return web.Response(headers={'Location': ret['message']}, status=303) # 303是直接跳转到图片
else:
return web.Response(body=json.dumps(ret, indent=2, sort_keys=True, ensure_ascii=False),
Expand All @@ -89,7 +89,7 @@ async def get_shop_img(request):

# 登录接口
@routes.post('/login')
async def post_login(request):
async def post_login(request:web_request.Request):
_log.info(f"request | /login")
try:
ret = await ApiHandler.login_request(request,"POST")
Expand All @@ -113,7 +113,7 @@ async def post_login(request):

# 邮箱验证登录
@routes.post('/tfa')
async def post_tfa_code(request):
async def post_tfa_code(request:web_request.Request):
_log.info(f"request | /tfa")
try:
ret = await ApiHandler.tfa_code_requeset(request)
Expand All @@ -136,7 +136,7 @@ async def post_tfa_code(request):
content_type='application/json')

@routes.post('/shop')
async def post_shop(request):
async def post_shop(request:web_request.Request):
_log.info(f"request | /shop")
try:
body = await request.content.read()
Expand All @@ -154,6 +154,7 @@ async def post_shop(request):
content_type='application/json',status=200)
# 画图请求,不需要检测token速率
ret = await ApiHandler.shop_get_request(params,params['account'])
_log.info(f"/shop return | {ret['code']} | {ret['message']}")
return web.Response(body=json.dumps(ret, indent=2, sort_keys=True, ensure_ascii=False),
content_type='application/json',status=200)
except:
Expand All @@ -174,7 +175,7 @@ async def post_shop(request):

# 用于控制db中ShopCmp的更新
@routes.post('/shop-cmp')
async def post_shop_cmp(request):
async def post_shop_cmp(request:web_request.Request):
_log.info(f"request | /shop-cmp")
try:
ret = await ApiHandler.shop_cmp_request(request)
Expand All @@ -201,7 +202,7 @@ async def post_shop_cmp(request):
# 爱发电的wh
from pkg.utils.file.Files import bot
@routes.post('/afd')
async def aifadian_webhook(request):
async def aifadian_webhook(request:web_request.Request):
_log.info(f"request | /afd")
try:
ret = await ApiHandler.afd_request(request, bot)
Expand All @@ -219,11 +220,33 @@ async def aifadian_webhook(request):

# 机器人加入的服务器/命令总数等等信息
from pkg.utils.log.BotLog import log_bot_list
@routes.get('/bot-log')
async def bot_log_get(request):
_log.info(f"request | /bot-log")
WEB_ROOT = "./web/ahri"
async def html_response(path:str):
try:
ret_dict = await log_bot_list()
with open(f'{WEB_ROOT}{path}','r') as f:
return web.Response(body=f.read(),content_type='text/html')
except:
_log.exception(f"Exception in /bot | {path}")
return web.Response(status=503)

@routes.get('/bot')
async def bot_log_html1(request:web_request.Request):
_log.info(f"request | /bot")
return await html_response("/index.html")
@routes.get('/bot/gu')
async def bot_log_html2(request:web_request.Request):
_log.info(f"request | /bot")
return await html_response("/gu/index.html")
@routes.get('/bot/ngu')
async def bot_log_html3(request:web_request.Request):
_log.info(f"request | /bot")
return await html_response("/ngu/index.html")
# 机器人命令使用情况json
@routes.get('/bot/log')
async def bot_log_get(request:web_request.Request):
_log.info(f"request | /bot/log")
try:
ret_dict = await log_bot_list(log_img_draw=False) # 不画图
ret = {
"guild_total":ret_dict["guild"]["guild_total"],
"guild_active":ret_dict["guild"]["guild_active"],
Expand All @@ -233,7 +256,7 @@ async def bot_log_get(request):
return web.Response(body=json.dumps(ret, indent=2, sort_keys=True, ensure_ascii=False),
content_type='application/json')
except:
_log.exception("Exception in /afd")
_log.exception("Exception in /bot/log")
return web.Response(status=503)


Expand Down
8 changes: 4 additions & 4 deletions code/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,8 +534,8 @@ async def get_daily_shop(msg: Message,index:str = "0",*arg):
# 5.1.2 本地缓存路径不存在,或者缓存过期
elif is_vip:
play_currency = await Riot.fetch_vp_rp_dict(riotUser) # 获取用户的vp和rp
# 如果没有设置背景图,那就设置为err
background_img = ('err' if msg.author_id not in VipShopBgDict['bg'] else
# 如果没有设置背景图,那就设置为空
background_img = ('' if msg.author_id not in VipShopBgDict['bg'] else
VipShopBgDict['bg'][msg.author_id]["background"][0])
img_ret = await ShopImg.get_shop_img_169(list_shop,
vp=play_currency['vp'],
Expand Down Expand Up @@ -1264,7 +1264,7 @@ async def auto_skin_notify():
# 获取用户的vp和rp
play_currency = await Riot.fetch_vp_rp_dict(riotUser)
# 设置用户背景图,如果在则用,否则返回err
background_img = ('err' if vip not in VipShopBgDict['bg'] else
background_img = ('' if vip not in VipShopBgDict['bg'] else
VipShopBgDict['bg'][vip]["background"][0])
# 开始画图
img_ret = await ShopImg.get_shop_img_169(list_shop,
Expand Down Expand Up @@ -1427,7 +1427,7 @@ async def bot_start_task(bot: Bot):
startup_msg = send_msg['msg_id'] # 赋值msgid
_log.info("[BOT.TASK] fetch_public_channel success")
# 管理员命令
Admin.init(bot,bot_upd_img,debug_ch)
Admin.init(bot,bot_upd_img,debug_ch,startup_msg)
# 注册其他命令
Funny.init(bot,debug_ch)
GrantRoles.init(bot)
Expand Down
40 changes: 25 additions & 15 deletions code/pkg/Admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,12 @@ def is_admin(user_id:str):
"""是管理员返回True"""
return user_id == master_id

def init(bot:Bot,bot_upd_img:Bot,debug_ch:Channel):
def init(bot:Bot,bot_upd_img:Bot,debug_ch:Channel,startup_msg:str = ""):
"""Admin command
- bot: main bot
- bot_upd_img: bot for img upload
- debug_ch: channel obj
- LoginForbidden: global value from .utils.file.Files
- NightMarketOff: global value from .utils.file.Files
- startup_msg: msg_id
"""

@bot.command(name='kill',case_sensitive=False)
Expand All @@ -44,8 +43,8 @@ async def kill_bot_cmd(msg: Message, at_text = '', *arg):
if isinstance(msg,PrivateMessage) or f"(met){cur_bot.id}(met)" in at_text:
# 保存所有文件
await save_all_file(False)
cm = CardMessage(Card(Module.Section(
Element.Text(f"[KILL] 保存全局变量成功,bot下线\n当前时间:{Gtime.get_time()}", Types.Text.KMD))))
await KookApi.bot_alive_card(startup_msg,"!KILL!") # 更新启动消息
cm = await KookApi.get_card_msg(f"[KILL] 保存全局变量成功,bot下线\n当前时间:{Gtime.get_time()}")
await msg.reply(cm)
res = "webhook"
if config['kook']['bot']['ws']: # 用的是ws才需要调用
Expand Down Expand Up @@ -219,28 +218,39 @@ async def exit_guild_cmd(msg:Message,guild="",*arg):
_log.info(f"Au:{msg.author_id} | guild_leave {guild} | {ret}")
# 没有指定,退出不活跃的服务器
else:
global BotUserDict
cm = await KookApi.get_card_msg("收到命令,开始退出不活跃服务器",img_url=KookApi.icon_cm.rgx_card)
send_msg = await msg.reply(cm)
start_time = time.perf_counter()
i,good,err =0,0,0
guild_text = ""
for g,ginfo in BotUserDict['guild']['data'].items():
i,good,err = 0,0,0 # 初始化
guild_text = "" # 日志信息
start_time = time.perf_counter() # 开始计时
if 'exit' not in BotUserDict['guild']:
BotUserDict['guild']['exit'] = {}
BotUserDictTemp = copy.deepcopy(BotUserDict) # 深拷贝
for g,ginfo in BotUserDictTemp['guild']['data'].items():
try:
i += 1
if ginfo['cmd'] > IN_ACTIVATE_GUILD:
continue
# 走到这里是不活跃服务器
ret = await KookApi.guild_leave(g)
# 没有错误,删除键值并打印日志
BotUserDict['guild']['exit'][g] = copy.deepcopy(BotUserDictTemp['guild']['data'][g])
del BotUserDict['guild']['data'][g] # 删除键值
if ret['code'] !=0: # 有错误
raise Exception(f"guild_leave Err | {ret}")
i += 1
good+=1
good +=1
_log.info(f"[i{i}/g{good}] exited guild {g}")
guild_text+= f"({g})"
await asyncio.sleep(0.4)
if i>=100:# 超过100个多睡一会
cm = await KookApi.get_card_msg(f"已处理 [g{good}/e{err}]",guild_text[0:4800])
# 超过100个多睡一会
if i>=100:
time_diff = format(time.perf_counter()-start_time,".2f")
cm = await KookApi.get_card_msg(f"已处理 [g{good}/e{err}] 用时 {time_diff}s",guild_text[0:4800])
await KookApi.upd_card(send_msg['msg_id'],cm) # 更新消息
await asyncio.sleep(20)
await asyncio.sleep(15)
i = 0
else:
await asyncio.sleep(0.5)
except:
err+=1
_log.exception(f"Err while G:{g}")
Expand Down
Loading

0 comments on commit a5a2d6d

Please sign in to comment.