Skip to content

Commit

Permalink
Merge pull request #11 from Valorant-Shop-CN/develop
Browse files Browse the repository at this point in the history
chome(1.1.4): release v1.1.4
  • Loading branch information
musnows committed Apr 20, 2023
2 parents 8bb8e1a + 4ebeed1 commit b9916c6
Show file tree
Hide file tree
Showing 12 changed files with 213 additions and 517 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,14 @@ caiyun.json
*.log
btest.py


# python file
__pycache__/

# idea
.idea/
.vscode/

# webfile

code/web/
35 changes: 19 additions & 16 deletions code/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ async def Save_File_Task():
async def KillBot(msg: Message, num: str = '124124', *arg):
BotLog.logMsg(msg)
try:
if '-' in num or '.' in num:
return await msg.reply(f"参数num错误:{num}\n该参数应为bot的编号:{config['no']}")
if msg.author_id == master_id and int(num) == config['no']:
# 保存所有文件
await save_all_file(False)
Expand Down Expand Up @@ -240,21 +242,21 @@ async def check_UserAuthCache_len(msg: Message):
@bot.command(name='login')
async def login(msg: Message, user: str = 'err', passwd: str = 'err', apSave='', *arg):
_log.info(f"Au:{msg.author_id} {msg.author.username}#{msg.author.identify_num} | /login {apSave}")
BotLog.log_bot_user(msg.author_id) #这个操作只是用来记录用户和cmd总数的
global LoginForbidden, login_rate_limit, UserAuthCache
if not isinstance(msg, PrivateMessage): # 不是私聊的话,禁止调用本命令
await msg.reply(f"为了避免您的账户信息泄漏,请「私聊」使用本命令!\n用法:`/login 账户 密码`")
return
elif passwd == 'err' or user == 'err':
await msg.reply(f"参数不完整,请提供您的账户密码!\naccount: `{user}` passwd: `{passwd}`\n正确用法:`/login 账户 密码`")
return
elif LoginForbidden:
await LoginForbidden_send(msg)
return
# 提前定义,避免报错
global LoginForbidden, login_rate_limit, UserAuthCache
send_msg = {'msg_id':''}
cm = CardMessage()
try:
# 0.进行命令合法性判断
BotLog.log_bot_cmd() # 记录命令使用情况
BotLog.log_bot_user(msg.author_id,getTime()) # 记录用户和cmd总数
if not isinstance(msg, PrivateMessage): # 不是私聊的话,禁止调用本命令
return await msg.reply(f"为了避免您的账户信息泄漏,请「私聊」使用本命令!\n用法:`/login 账户 密码`")
elif passwd == 'err' or user == 'err':
return await msg.reply(f"参数不完整,请提供您的账户密码!\naccount: `{user}` passwd: `{passwd}`\n正确用法:`/login 账户 密码`")
elif LoginForbidden:
return await LoginForbidden_send(msg)

# 1.检查全局登录速率
await check_GloginRate() # 无须接收此函数返回值,直接raise
# 1.1 检查当前已经登录的用户数量,超过限制直接提示并返回
Expand Down Expand Up @@ -348,12 +350,13 @@ async def login(msg: Message, user: str = 'err', passwd: str = 'err', apSave='',
@bot.command(name='tfa')
async def tfa_verify(msg: Message, tfa: str, *arg):
_log.info(f"Au:{msg.author_id} {msg.author.username}#{msg.author.identify_num} | /tfa")
if len(tfa) != 6:
await msg.reply(f"邮箱验证码长度错误,请确认您输入了正确的6位验证码\n当前参数:`{tfa}`")
return

send_msg = {'msg_id': ''}
try:
# 0.命令合法性判断
BotLog.log_bot_cmd() # 记录命令使用情况
BotLog.log_bot_user(msg.author_id,getTime()) # 记录用户和cmd总数
if len(tfa) != 6:
return await msg.reply(f"邮箱验证码长度错误,请确认您输入了正确的6位验证码\n当前参数:`{tfa}`")
# 1. 先判断用户是否在dict里面
if msg.author_id not in UserAuthCache['tfa']:
await msg.reply("您不在UserAuthCache中,请先执行login!")
Expand Down Expand Up @@ -786,7 +789,6 @@ async def get_user_card(msg: Message, *arg):
cm = await get_card_msg("获取您所有账户的 玩家卡面/VP/R点", "阿狸正在施法!很快就好啦~", icon_cm.rgx_card,card_color="#BBFFFF")
send_msg = await msg.reply(cm)
# 2.uinfo直接使用for循环来获取不同用户的信息
cm = CardMessage()
for riot_user_id in UserAuthCache['kook'][msg.author_id]:
try:
# 执行cookie重登
Expand All @@ -797,6 +799,7 @@ async def get_user_card(msg: Message, *arg):
await upd_card(reau['msg_id'], cm, channel_type=msg.channel_type)
send_msg = reau # 再次覆盖更新消息

cm = CardMessage()
auth = UserAuthCache['data'][riot_user_id]['auth']
assert isinstance(auth, EzAuth)
riotUser = auth.get_riotuser_token()
Expand Down
13 changes: 6 additions & 7 deletions code/pkg/plugins/Funny.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,15 +87,14 @@ async def countdown(msg: Message, time: int = 60, *args):
async def roll(msg: Message, t_min: int = 1, t_max: int = 100, n: int = 1, *args):
BotLog.logMsg(msg)
if args != ():
await msg.reply(
return await msg.reply(
f"参数错误,roll命令只支持3个参数\n正确用法:\n```\n/roll 1 100 生成一个1到100之间的随机数\n/roll 1 100 3 生成三个1到100之间的随机数\n```")
return
elif t_min >= t_max: #范围小边界不能大于大边界
await msg.reply(f'范围错误,必须提供两个参数,由小到大!\nmin:`{t_min}` max:`{t_max}`')
return
elif t_max >= 90000000: #不允许用户使用太大的数字
await msg.reply(f"掷骰子的数据超出范围!")
return
return await msg.reply(f'范围错误,必须提供两个参数,由小到大!\nmin:`{t_min}` max:`{t_max}`')
elif t_max >= 10000000: #不允许用户使用太大的数字
return await msg.reply(f"掷骰子的数据超出范围!")
elif n > 32:
return await msg.reply(f"当前仅支持同时投掷32个骰子")
try:
result = [random.randint(t_min, t_max) for i in range(n)]
await msg.reply(f'掷出来啦: {result}')
Expand Down
136 changes: 91 additions & 45 deletions code/pkg/plugins/StatusWeb.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,54 +12,98 @@


def init(bot:Bot,master_id:str):
async def data_manamge():
guild_list = []
user_dict = {}
for g,ginfo in BotUserDict["guild"]["data"].items():
lt = []
for u in ginfo['user']:
tis = Gtime.getTimeStampFromStr(ginfo['user'][u])
lt.append(tis) # 当前服务器用户使用命令的时间戳
# 插入用户,必须要用户不存在dict中,或者时间比dict中的小才能添加
if u in user_dict and tis >= user_dict[u]:
continue
user_dict[u] = tis
# 获取lt中时间的最小值,即服务器第一个使用命令的用户的时间,可以认为是服务器的初始化时间
min_time = min(lt)
date = Gtime.getDateFromStamp(min_time) # 获取可读日期
# 插入服务器
flag = True
for i in guild_list:
if date == i['date'] and i['category']=="guild":
i['num']+=1 # 有相同日期的,计数器+1
flag = False
break
# 没有相同日期的,才新建键值
if flag:
guild_list.append({"date":date,"category":'guild','num':1,'time':min_time})
# 插入用户
for u in user_dict:
date = Gtime.getDateFromStamp(user_dict[u])
flag = True
for i in guild_list:
if date == i['date'] and i['category']=="user":
i['num']+=1
flag = False
break
# 没有相同日期的,才新建键值
if flag:
guild_list.append({"date":date,"category":'user','num':1,'time':user_dict[u]})
async def data_manamge(key:str)->list:
"""处理日志文件中,服务器/用户/命令的数据
Args(key):
- init_time: 获取服务器/用户日增量的数据
- used_time: 获取服务器/用户/命令日使用量的数据
"""
data_list = []
# 获取的是初始化时间
if key == 'init_time':
for g,ginfo in BotUserDict["guild"]["data"].items():
date = Gtime.getDateFromStamp(ginfo[key]) # 获取可读日期
# 插入服务器
flag = True
for i in data_list:
if date == i['date'] and i['category']=="guild":
i['num']+=1 # 有相同日期的,计数器+1
flag = False
break
# 没有相同日期的,才新建键值
if flag:
data_list.append({"date":date,"category":'guild','num':1,'time':ginfo[key]})
# 插入用户
for u,uinfo in BotUserDict['user']['data'].items():
# 用户记录的时间是可读时间,直接取出前几位就是日期22-10-02
date = uinfo[key][:8]
flag = True
for i in data_list:
if date == i['date'] and i['category']=="user":
i['num']+=1
flag = False
break
# 没有相同日期的,才新建键值
if flag:
data_list.append({"date":date,"category":'user','num':1,'time':Gtime.getTimeStampFromStr(uinfo[key])})
# 如果是used_time,则还需要处理命令
elif key == 'used_time':
for d in BotUserDict['cmd']['data']:
num = BotUserDict['cmd']['data'][d]
data_list.append({"date":d,"category":'command','num':num,'time':Gtime.getTimeStampFromStr(d)})
for d in BotUserDict['cmd']['user']:
num = BotUserDict['cmd']['user'][d]
data_list.append({"date":d,"category":'user','num':num,'time':Gtime.getTimeStampFromStr(d)})
for d in BotUserDict['cmd']['guild']:
num = BotUserDict['cmd']['guild'][d]
data_list.append({"date":d,"category":'guild','num':num,'time':Gtime.getTimeStampFromStr(d)})
# 依照日期排序
guild_list = sorted(guild_list,key=lambda kv: kv['date'])
return guild_list
data_list = sorted(data_list,key=lambda kv: kv['date'])
return data_list


async def render_gu_web(exp_raise = False):
async def render_ngu_web(exp_raise = False):
"""渲染用户/服务器增量网页
- exp_raise: 是否要重新抛出异常
"""
try:
# 获取处理好的数据
guild_list = await data_manamge()
guild_list = await data_manamge('init_time')
# 获取上个月的时间戳,只显示最近30天的时间,将之前的删除掉
last_month_time = time.time() - 86400 * SHOW_DAYS
guild_list_tmp = copy.deepcopy(guild_list)
for i in guild_list_tmp:
if i['time'] < last_month_time :
guild_list.remove(i)
# 网页参数
line = Plot("Line")
line.page_title = '服务器-用户-增长图 | Kook-Valorant-Bot'
line.set_options({
"appendPadding": 40,
"data": guild_list,
"xField": "date",
"yField": "num",
"label": {},
'seriesField': 'category',
"smooth": True,
"lineStyle": {
"lineWidth": 3,
}
})
# 生成html文件
line.render("./web/ahri/ngu/index.html")
_log.info(f"render new guild/user status web")
except Exception as result:
_log.exception("Error occur")
if exp_raise:raise result

async def render_guc_web(exp_raise = False):
"""渲染用户/服务器/命令使用情况的网页
- exp_raise: 是否要重新抛出异常
"""
try:
# 获取处理好的数据
guild_list = await data_manamge('used_time')
# 获取上个月的时间戳,只显示最近30天的时间,将之前的删除掉
last_month_time = time.time() - 86400 * SHOW_DAYS
guild_list_tmp = copy.deepcopy(guild_list)
Expand All @@ -68,7 +112,7 @@ async def render_gu_web(exp_raise = False):
guild_list.remove(i)
# 网页参数
line = Plot("Line")
line.page_title = '服务器-用户-增长图 | Kook阿狸机器人'
line.page_title = '机器人-活跃用户图 | Kook-Valorant-Bot'
line.set_options({
"appendPadding": 40,
"data": guild_list,
Expand All @@ -83,7 +127,7 @@ async def render_gu_web(exp_raise = False):
})
# 生成html文件
line.render("./web/ahri/gu/index.html")
_log.info(f"render guild/user status web")
_log.info(f"render guild/user/cmd status web")
except Exception as result:
_log.exception("Error occur")
if exp_raise:raise result
Expand All @@ -92,7 +136,8 @@ async def render_gu_web(exp_raise = False):
async def update_web_task():
try:
_log.info("web update begin")
await render_gu_web()
await render_ngu_web()
await render_guc_web()
_log.info("web update success")
except:
_log.exception("Error occur")
Expand All @@ -103,7 +148,8 @@ async def update_web_cmd(msg:Message):
try:
if msg.author_id !=master_id:
return
await render_gu_web(True)
await render_ngu_web(True)
await render_guc_web(True)
await msg.reply(f"网页更新成功")
except:
await msg.reply(f"网页渲染出现错误\n```\n{traceback.format_exc()}```\n")
Expand Down
6 changes: 5 additions & 1 deletion code/pkg/utils/Gtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ def getTimeFromStamp(timestamp:float|int):


def getTimeStampFromStr(time_str):
"""从可读时间转为时间戳, 格式 23-01-01 00:00:00"""
"""从可读时间转为时间戳,格式 23-01-01 00:00:00
- 如果传入的只有日期,如23-01-01,则会自动获取当日0点的时间戳
"""
if len(time_str) == 8:
time_str+=" 00:00:00"
dt = datetime.strptime(time_str, '%y-%m-%d %H:%M:%S')
tz = timezone(timedelta(hours=8))
dt = dt.astimezone(tz)
Expand Down
12 changes: 7 additions & 5 deletions code/pkg/utils/Help.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ def help_main(start_time: str):
c3 = Card(
Module.Header('你可以用下面这些指令呼叫本狸哦!'),
Module.Context(
Element.Text(f"开源代码见[Github](https://github.com/Aewait/Valorant-Kook-Bot),开机于 [{start_time}]",
Element.Text(f"开源代码见[Github](https://github.com/Valorant-Shop-CN/Kook-Valorant-Bot),开机于 [{start_time}]",
Types.Text.KMD)))
c3.append(Module.Section('「/hello」来和本狸打个招呼吧!\n「/Ahri」 帮助指令\n'))
c3.append(Module.Divider())
c3.append(Module.Section('图文版帮助命令', Element.Button('点我', 'https://blog.musnow.top/posts/847195815/?utm_source=kook', Types.Click.LINK,theme=Types.Theme.PRIMARY)))
# c3.append(Module.Section('「/hello」来和本狸打个招呼吧!\n「/Ahri」 帮助指令\n'))
# c3.append(Module.Divider())
c3.append(Module.Header('上号,瓦一把!'))
text = "「/val 错误码」 游戏错误码的解决方法,0为已包含的val报错码信息\n"
text += "「/dx」 关于DirectX Runtime报错的解决方案\n"
Expand All @@ -26,7 +27,7 @@ def help_main(start_time: str):
text += "「/TLON」 在本频道打开实时翻译\n"
text += "「/TLOFF」在本频道关闭实时翻译\n"
text += "「/we 城市」查询城市未来3天的天气情况\n"
text += "「更多…」还有一些隐藏指令哦~\n"
# text += "「更多…」还有一些隐藏指令哦~\n"
c3.append(Module.Section(Element.Text(text, Types.Text.KMD)))
c3.append(Module.Divider())
c3.append(Module.Section(' 游戏打累了?想来本狸的家坐坐吗~', Element.Button('让我康康', 'https://kook.top/gpbTwZ', Types.Click.LINK)))
Expand All @@ -39,7 +40,8 @@ def help_val():
c3 = Card(
Module.Header('目前阿狸支持查询的valorant信息如下'),
Module.Context(
Element.Text("开源代码见[Github](https://github.com/Aewait/Valorant-Kook-Bot),更多查询功能上线中...", Types.Text.KMD)))
Element.Text("开源代码见[Github](https://github.com/Valorant-Shop-CN/Kook-Valorant-Bot),更多查询功能上线中...", Types.Text.KMD)))
c3.append(Module.Section('图文版帮助命令', Element.Button('点我', 'https://blog.musnow.top/posts/847195815/?utm_source=kook', Types.Click.LINK,theme=Types.Theme.PRIMARY)))
text = "使用前,请确认您知晓相关功能可能有风险:\n"
text += "1.阿狸的后台不会做任何`打印`您的游戏账户密码的操作,若在使用相关功能后被盗号,阿狸可不承担任何责任;\n"
text += "2.如果您发现登陆后阿狸还提醒您没有登录,那是因为阿狸的作者正在调试阿狸,重启后登录信息会消失。感谢谅解;\n"
Expand Down
Loading

0 comments on commit b9916c6

Please sign in to comment.