Skip to content

Commit

Permalink
Merge pull request #14 from Valorant-Shop-CN/develop
Browse files Browse the repository at this point in the history
chown(v1.2.1): release v1.2.1
  • Loading branch information
musnows authored May 12, 2023
2 parents 98d0366 + 71c396c commit 9e5c51e
Show file tree
Hide file tree
Showing 20 changed files with 259 additions and 152 deletions.
2 changes: 1 addition & 1 deletion code/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ async def get_shop_img(request):
params = request.rel_url.query
ret = await ApiHandler.login_request(request,"GET")
if ret['code'] == 0:
# 如果url不在,或者值不为1,则303跳转图片
# 如果url不在,或者值不为0,则303跳转图片
if 'url' not in params or str(params['url']) != '0':
return web.Response(headers={'Location': ret['message']}, status=303) # 303是直接跳转到图片
else:
Expand Down
9 changes: 7 additions & 2 deletions code/config/config.exp.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"token": {
"kook": {
"bot": {
"token": "bot webhook/websocket token",
"verify_token": "webhook verify token",
Expand All @@ -17,6 +17,12 @@
"debug_ch": "发送错误日志的频道",
"img_upload_ch": "用来测试vip商店图片的频道"
},
"cache": {
"shop_img":{
"memory":false,
"storage":true
}
},
"lsky": {
"url": "lsky图床的url(该功能未启用,可留空)",
"token": "lsky图床的token(该功能未启用,可留空)"
Expand All @@ -28,6 +34,5 @@
"user_name": "数据库内置用户id",
"user_pwd": "数据库内置用户密码"
},
"no": 1000,
"platform": "kook"
}
35 changes: 24 additions & 11 deletions code/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from pkg.utils.log import BotLog
from pkg.utils.log.Logging import _log
from pkg.utils.valorant import Reauth,AuthCache
from pkg.utils.KookApi import icon_cm, upd_card, get_card,get_card_msg
from pkg.utils.KookApi import icon_cm, upd_card, get_card,get_card_msg,bot_alive_card
from pkg.utils.valorant.api import Assets,Riot,Local
from pkg.utils.valorant.EzAuth import EzAuth, EzAuthExp
from pkg.utils.Gtime import get_time, get_8am_time_stamp,shop_time_remain,get_time_str_from_stamp,get_date
Expand All @@ -30,8 +30,13 @@
# 在bot一开机的时候就获取log频道作为全局变量
debug_ch: Channel
"""发送错误信息的日志频道"""
cm_send_test: Channel
cm_test_ch: Channel
"""进行卡片消息发送测试的频道"""
startup_msg = ""
"""机器人开机发送的启动消息id。
- 用于后续更新来创造事件激活replit的机器人,避免repl休眠;
- 同时也可能看到机器人上一次活动是什么时候,能判断机器人有没有假死
"""
NOTIFY_NUM = 3
"""非vip用户皮肤提醒栏位"""
RATE_LIMITED_TIME = 180
Expand All @@ -46,17 +51,20 @@ async def botmarket_ping_task():
headers = {'uuid': 'a87ebe9c-1319-4394-9704-0ad2c70e2567'}
async with aiohttp.ClientSession() as session:
await session.post(api, headers=headers)
# 更新在线卡片
await bot_alive_card(startup_msg,"botmarket")
_log.info(f"[botmarket] ping at {get_time()}")

@bot.task.add_interval(minutes=5)
async def save_file_task():
"""每5分钟保存一次文件"""
"""每5分钟保存一次所有数据文件"""
try:
await bot_alive_card(startup_msg,"save-file")
await save_all_file()
except:
err_cur = f"ERR! [{get_time()}] [Save.File.Task]\n```\n{traceback.format_exc()}\n```"
_log.exception("ERR in [Save.File.Task]")
await bot.client.send(debug_ch, err_cur) # type: ignore
_log.exception("ERR in save.file.task")
cm = await get_card_msg(f"ERR! [{get_time()}] save.file.task\n```\n{traceback.format_exc()}\n```")
await bot.client.send(debug_ch, cm)


######################################## help ##########################################
Expand Down Expand Up @@ -1388,6 +1396,7 @@ async def auto_skin_notify():
# 早八自动执行
@bot.task.add_cron(hour=8, minute=0, timezone="Asia/Shanghai")
async def auto_skin_notify_task():
await bot_alive_card(startup_msg,"notify")
await auto_skin_notify()

# 手动执行notify task
Expand All @@ -1403,15 +1412,19 @@ async def auto_skin_notify_cmd(msg: Message, *arg):


@bot.on_startup
async def loading_cache(bot: Bot):
async def bot_start_task(bot: Bot):
"""
- 在阿狸开机的时候自动加载所有保存过的cookie
- 注册其他命令
"""
try:
global debug_ch, cm_send_test
cm_send_test = await bot_upd_img.client.fetch_public_channel(config['channel']["img_upload_ch"])
global debug_ch, cm_test_ch, startup_msg
cm_test_ch = await bot_upd_img.client.fetch_public_channel(config['channel']["img_upload_ch"])
debug_ch = await bot.client.fetch_public_channel(config['channel']['debug_ch'])
# 获取到频道后,发送一条启动消息,并在后续更新这个消息
cm = await get_card_msg(f"[BOT.START] {StartTime}")
send_msg = await debug_ch.send(cm)
startup_msg = send_msg['msg_id'] # 赋值msgid
_log.info("[BOT.TASK] fetch_public_channel success")
# 管理员命令
Admin.init(bot,bot_upd_img,debug_ch)
Expand All @@ -1423,7 +1436,7 @@ async def loading_cache(bot: Bot):
Match.init(bot,debug_ch)
GameHelper.init(bot)
ValFileUpd.init(bot,bot_upd_img)
Vip.init(bot,bot_upd_img,debug_ch,cm_send_test)
Vip.init(bot,bot_upd_img,debug_ch,cm_test_ch,startup_msg)
Mission.init(bot,debug_ch)
StatusWeb.init(bot)
_log.info("[BOT.TASK] load plugins")
Expand Down Expand Up @@ -1463,7 +1476,7 @@ async def loading_cache(bot: Bot):
continue
# 结束任务
_log.info("TASK.INFO\n\t" + log_str_success + "\n\t" + log_str_failed + "\n\t" + log_not_exits)
_log.info(f"[BOT.TASK] loading user cookie finished")
_log.info(f"[BOT.TASK] loading user cookie finish | begin loading api auth")

# api缓存的用户列表
log_str_success = "[BOT.TASK] api load cookie success = Au:"
Expand Down
8 changes: 5 additions & 3 deletions code/pkg/Admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from .utils.valorant.Reauth import LoginForbidden,NightMarketOff
from .utils import Gtime,KookApi,ShopRate
# 画图缓存
from .utils.ShopImg import weapon_icon_temp_11,weapon_icon_temp_169,skin_level_icon_temp
from .utils.ShopImg import weapon_icon_temp_11,weapon_icon_temp_169,skin_level_icon_temp,IMG_MEMORY_CACHE

master_id = config['master_id']
"""机器人开发者用户id"""
Expand Down Expand Up @@ -48,7 +48,7 @@ async def kill_bot_cmd(msg: Message, at_text = '', *arg):
Element.Text(f"[KILL] 保存全局变量成功,bot下线\n当前时间:{Gtime.get_time()}", Types.Text.KMD))))
await msg.reply(cm)
res = "webhook"
if config['token']['bot']['ws']: # 用的是ws才需要调用
if config['kook']['bot']['ws']: # 用的是ws才需要调用
res = await KookApi.bot_offline() # 调用接口下线bot
# 打印日志
_log.info(f"KILL | bot-off: {res}\n")
Expand All @@ -68,11 +68,13 @@ async def check_user_auth_len_cmd(msg: Message,*arg):
c = Card(Module.Header("当前机器人缓存情况"),Module.Context(f"记录于:{Gtime.get_time()}"),Module.Divider())
text = "EzAuth登录缓存\n```\n"
text+= f"bot: {len(UserAuthCache['kook'])}\napi: {len(UserAuthCache['api'])}\n```\n"
text+= "商店画图缓存\n```\n"
text+= "商店画图 内存缓存\n```\n"
text+= f"皮肤单图 1-1:{len(weapon_icon_temp_11)}\n"
text+= f"皮肤单图 16-9:{len(weapon_icon_temp_169)}\n"
text+= f"皮肤等级图: {len(skin_level_icon_temp)}\n"
text+= "```"
if not IMG_MEMORY_CACHE:
text+= "\n当前内存缓存处于关闭状态"
c.append(Module.Section(Element.Text(text,Types.Text.KMD)))
cm = CardMessage(c)
await msg.reply(cm)
Expand Down
66 changes: 43 additions & 23 deletions code/pkg/plugins/BotStatus.py
Original file line number Diff line number Diff line change
@@ -1,40 +1,60 @@
import traceback
from khl import Bot,Message
from ..utils.log import BotLog
from ..utils.KookApi import status_active_game,status_active_music,status_delete
from ..utils.KookApi import status_active_game,status_active_music,status_delete,get_card_msg,_log
from ..Admin import is_admin

def init(bot:Bot):
"""机器人动态相关命令
- bot: main bot
"""
# 开始打游戏
@bot.command(name="gaming")
async def gaming(msg: Message, game: int = 1):
BotLog.log_msg(msg)
#await bot.client.update_playing_game(3,1)# 英雄联盟
if game == 1:
ret = await status_active_game(453027) # 瓦洛兰特
await msg.reply(f"{ret['message']},阿狸上号valorant啦!")
elif game == 2:
ret = await status_active_game(3) # 英雄联盟
await msg.reply(f"{ret['message']},阿狸上号LOL啦!")
try:
BotLog.log_msg(msg)
# await bot.client.update_playing_game(3,1)# 英雄联盟
if not is_admin(msg.author_id):return
if game == 1:
ret = await status_active_game(453027) # 瓦洛兰特
await msg.reply(f"{ret['message']},阿狸上号valorant啦!")
elif game == 2:
ret = await status_active_game(3) # 英雄联盟
await msg.reply(f"{ret['message']},阿狸上号LOL啦!")
except:
await BotLog.base_exception_handler("gaming",traceback.format_exc(),msg)


# 开始听歌
@bot.command(name="singing")
async def singing(msg: Message, music: str = "err", singer: str = "err"):
BotLog.log_msg(msg)
if music == "err" or singer == "err":
await msg.reply(f"函数参数错误,music: `{music}` singer: `{singer}`")
return
async def singing(msg: Message, music: str = "err", singer: str = "err",*arg):
try:
BotLog.log_msg(msg)
if not is_admin(msg.author_id):return
if music == "err" or singer == "err":
return await msg.reply(f"函数参数错误,music: `{music}` singer: `{singer}`")

ret = await status_active_music(music, singer)
await msg.reply(f"{ret['message']},阿狸开始听歌啦!")
ret = await status_active_music(music, singer)
text = f"{ret['message']},阿狸开始听歌啦!"
sub_text = f"歌名:{music} 歌手:{singer}"
await msg.reply(await get_card_msg(text,sub_text))
except:
await BotLog.base_exception_handler("singing",traceback.format_exc(),msg)


# 停止打游戏1/听歌2
@bot.command(name='sleeping')
async def sleeping(msg: Message, d: int = 1):
BotLog.log_msg(msg)
ret = await status_delete(d)
if d == 1:
await msg.reply(f"{ret['message']},阿狸下号休息啦!")
elif d == 2:
await msg.reply(f"{ret['message']},阿狸摘下了耳机~")
#await bot.client.stop_playing_game()
try:
BotLog.log_msg(msg)
if not is_admin(msg.author_id):return
ret = await status_delete(d)
if d == 1:
await msg.reply(f"{ret['message']},阿狸下号休息啦!")
elif d == 2:
await msg.reply(f"{ret['message']},阿狸摘下了耳机~")
#await bot.client.stop_playing_game()
except:
await BotLog.base_exception_handler("sleeping",traceback.format_exc(),msg)

_log.info("[plugins] load BotStatus.py")
11 changes: 7 additions & 4 deletions code/pkg/plugins/Funny.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
import traceback
from datetime import datetime,timedelta

from khl import Bot,Message,PrivateMessage,Channel
from khl.card import Card, CardMessage, Element, Module, Types, Struct
from khl import Bot,Message,Channel
from khl.card import Card, CardMessage, Element, Module, Types
from ..utils.log import BotLog
from ..utils.log.Logging import _log


# 历史上的今天,来自https://www.free-api.com/doc/317
Expand Down Expand Up @@ -102,7 +103,7 @@ async def roll(msg: Message, t_min: int = 1, t_max: int = 100, n: int = 1, *args
await BotLog.base_exception_handler("roll", traceback.format_exc(), msg, debug_send=debug_ch)

# 返回天气
@bot.command(name='we')
@bot.command(name='we',aliases=['weather'],case_sensitive=False)
async def Weather(msg: Message, city: str = "err"):
BotLog.log_msg(msg)
if city == "err":
Expand All @@ -112,4 +113,6 @@ async def Weather(msg: Message, city: str = "err"):
try:
await weather(msg, city)
except Exception as result:
await BotLog.base_exception_handler("Weather", traceback.format_exc(), msg, debug_send=debug_ch)
await BotLog.base_exception_handler("Weather", traceback.format_exc(), msg, debug_send=debug_ch)

_log.info("[plugins] load Funny.py")
2 changes: 1 addition & 1 deletion code/pkg/plugins/GameHelper.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,4 +107,4 @@ async def dx(msg: Message):
await dx123(msg)


_log.info("[plugins] load GameHelper")
_log.info("[plugins] load GameHelper.py")
4 changes: 3 additions & 1 deletion code/pkg/plugins/GrantRoles.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,4 +158,6 @@ async def color_set_msg_cmd(msg: Message):
# # 感谢助力者(每天19点进行检查)
# @bot.task.add_cron(hour=19, minute=0, timezone="Asia/Shanghai")
# async def thanks_sponser_task():
# await thanks_sponser(bot)
# await thanks_sponser(bot)

_log.info("[plugins] load GrantRoles.py")
2 changes: 1 addition & 1 deletion code/pkg/plugins/Mission.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,4 @@ async def mission(msg:Message,*arg):
except Exception as result:
await BotLog.base_exception_handler("mission",traceback.format_exc(),msg)

_log.info("[plugins] load mission")
_log.info("[plugins] load Mission.py")
4 changes: 3 additions & 1 deletion code/pkg/plugins/Translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,4 +253,6 @@ async def translation_on(msg: Message):
@bot.command(name='TLOFF',case_sensitive=False)
async def translation_off(msg: Message):
BotLog.log_msg(msg)
await tl_close(msg)
await tl_close(msg)

_log.info("[plugins] load Transalte.py")
Loading

0 comments on commit 9e5c51e

Please sign in to comment.