Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
musnows committed Jan 22, 2023
2 parents 937206e + ee6823e commit 311f3c7
Show file tree
Hide file tree
Showing 20 changed files with 324 additions and 292 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@


![python](https://img.shields.io/badge/Python-3.8%2B-green) ![commit](https://img.shields.io/github/last-commit/Aewait/Valorant-kaiheila-bot) ![release](https://img.shields.io/github/v/release/Aewait/Valorant-kaiheila-bot)
[![khl server](https://www.kaiheila.cn/api/v3/badge/guild?guild_id=3566823018281801&style=3)](https://kaihei.co/oqz7Xg) ![githubstars](https://img.shields.io/github/stars/Aewait/Valorant-kaiheila-bot?style=social)
[![khl server](https://www.kaiheila.cn/api/v3/badge/guild?guild_id=3986996654014459&style=0)](https://kook.top/gpbTwZ) ![githubstars](https://img.shields.io/github/stars/Aewait/Valorant-kaiheila-bot?style=social)

<img src="./screenshot/log.png" height="55px" alt="Bot Log Image">
</div>
Expand Down Expand Up @@ -153,7 +153,7 @@ pip install -r requirements.txt
* 基本框架参考[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) 项目
* 通过账户密码获取 `riot_auth_token` 基于 [floxay/python-riot-auth](https://github.com/floxay/python-riot-auth) & [Prodzify/Riot-auth](https://github.com/Prodzify/Riot-auth)


### 特别鸣谢🎁
Expand Down
4 changes: 2 additions & 2 deletions README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Kook-Valorant-Bot</h1>
English | [简体中文](./README.md)

![python](https://img.shields.io/badge/Python-3.8%2B-green) ![commit](https://img.shields.io/github/last-commit/Aewait/Valorant-kaiheila-bot) ![release](https://img.shields.io/github/v/release/Aewait/Valorant-kaiheila-bot)
[![khl server](https://www.kaiheila.cn/api/v3/badge/guild?guild_id=3566823018281801&style=3)](https://kaihei.co/oqz7Xg) ![githubstars](https://img.shields.io/github/stars/Aewait/Valorant-kaiheila-bot?style=social)
[![khl server](https://www.kaiheila.cn/api/v3/badge/guild?guild_id=3986996654014459&style=0)](https://kook.top/gpbTwZ) ![githubstars](https://img.shields.io/github/stars/Aewait/Valorant-kaiheila-bot?style=social)

<img src="./screenshot/log.png" height="55px" alt="Bot Log Image">
</div>
Expand Down Expand Up @@ -117,7 +117,7 @@ Many codes in this repo are modified and used according to others' tutorials
* 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) & [Prodzify/Riot-auth](https://github.com/Prodzify/Riot-auth)


### Special Thanks🎁
Expand Down
19 changes: 16 additions & 3 deletions code/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import traceback
from aiohttp import web
from endpoints.Gtime import GetTime
from endpoints.ApiHandler import base_img_request,tfa_code_requeset
from endpoints.ApiHandler import base_img_request,tfa_code_requeset,afd_request

# 初始化节点
routes = web.RouteTableDef()
Expand Down Expand Up @@ -43,7 +43,7 @@ async def get_dailshop_img(request):
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):
async def post_tfa_code(request):
print(f"[{GetTime()}] [request] /tfa")
try:
ret = await tfa_code_requeset(request)
Expand All @@ -53,8 +53,21 @@ async def get_dailshop_img(request):
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')

from main import bot
# 爱发电的wh
@routes.post('/afd')
async def aifadian_webhook(request):
print(f"[{GetTime()}] [request] /afd")
try:
ret = await afd_request(request,bot)
return web.Response(body=json.dumps(ret,ensure_ascii=False), content_type='application/json')
except:
err_cur = traceback.format_exc()
print(f"[{GetTime()}] [Api] ERR in /afd\n{err_cur}")
return web.Response(body=json.dumps({"ec":0,"em":"err ouccer"},ensure_ascii=False), content_type='application/json')


print(f"[API Start] starting at {GetTime()}")
app = web.Application()
app.add_routes(routes)
# web.run_app(app, host='127.0.0.1', port=14725)
#web.run_app(app, host='127.0.0.1', port=14726)
26 changes: 13 additions & 13 deletions code/config/color_emoji.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
{
"msg_id":"6fec1aeb-9d5c-4642-aa95-862e3db8aa61",
"guild_id":"3566823018281801",
"sp_role_id":"1454428",
"data":{
"🐷":"2881825",
"❤":"3970687",
"🖤":"4196071",
"💛":"2882418",
"💙":"2928540",
"💜":"2907567",
"💚":"2904370",
"👍":"0"
}
"data": {
"❤": "3970687",
"🐷": "2881825",
"👍": "0",
"💙": "2928540",
"💚": "2904370",
"💛": "2882418",
"💜": "2907567",
"🖤": "4196071"
},
"guild_id": "3566823018281801",
"msg_id": "6fec1aeb-9d5c-4642-aa95-862e3db8aa61",
"sp_role_id": "1454428"
}
49 changes: 42 additions & 7 deletions code/endpoints/ApiHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,10 @@

TOKEN_RATE_LIMITED = 10
# bot的token文件
with open('./config/config.json', 'r', encoding='utf-8') as f:
config = json.load(f)
# 之前没有处理完毕的2fa用户信息
with open("./log/Api2fa.json", 'r', encoding='utf-8') as frpr:
Api2faDict = json.load(frpr)
from endpoints.FileManage import config
# 用来给kook上传文件的bot token
api_bot_token = config['api_bot_token']

Api2faDict = {'data':{}} # 保存2fa用户登录的过程信息
# 默认的背景图
img_bak_169 = 'https://img.kookapp.cn/assets/2022-10/KcN5YoR5hC0zk0k0.jpg'
img_bak_11 = 'https://img.kookapp.cn/assets/2023-01/lzRKEApuEP0rs0rs.jpg'
Expand Down Expand Up @@ -144,4 +140,43 @@ async def tfa_code_requeset(request):
key = Api2faDict['data'][account]
User2faCode[key]['vcode'] = vcode
User2faCode[key]['2fa_status'] = True
return {'code':0,'message':'email verify code post success,wait for shop img return','info':'两步验证码获取成功,请等待主接口返回','vcode':vcode}
return {'code':0,'message':'email verify code post success,wait for shop img return','info':'两步验证码获取成功,请等待主接口返回','vcode':vcode}

from endpoints.FileManage import AfdWebhook
from khl.card import CardMessage,Card,Module,Types,Element
# 爱发电webhook
async def afd_request(request,bot):
body = await request.content.read()
params = json.loads(body.decode('UTF8'))
global AfdWebhook
AfdWebhook.append(params)

text=""
if 'plan_title' in params['data']['order']:
text =f"商品 {params['data']['order']['plan_title']}\n"
user_id = params['data']['order']['user_id']
user_id = user_id[:6]
text+=f"用户 {params['data']['order']['user_id']}\n"
for i in params['data']['order']['sku_detail']:
text+=f"发电了{i['count']}{i['name']}\n"
text+=f"共计 {params['data']['order']['total_amount']} 猿"

trno = params['data']['order']['out_trade_no']
trno_f = trno[0:8]
trno_b = trno[-4:]
trno_f+="####"
trno_f+=trno_b

cm = CardMessage()
c = Card(
Module.Header(f"爱发电有新动态啦!"),
Module.Context(Element.Text(f"订单号: {trno_f}")),
Module.Divider(),
Module.Section(Element.Text(text, Types.Text.KMD))
)
cm.append(c)
#print(json.dumps(cm))
debug_ch = await bot.client.fetch_public_channel(config['debug_ch'])
await bot.client.send(debug_ch,cm)
print(f"[{GetTime()}] trno:{params['data']['order']['out_trade_no']} afd-cm-send")
return {"ec":200,"em":"success"}
6 changes: 2 additions & 4 deletions code/endpoints/ApiToken.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
from endpoints.Gtime import GetTime

# 所有token
with open("./log/ApiToken.json", 'r', encoding='utf-8') as frpr:
ApiTokenDict = json.load(frpr)
from endpoints.FileManage import ApiTokenDict

#获取uuid
def get_uuid():
Expand All @@ -15,8 +14,7 @@ def get_uuid():

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)
ApiTokenDict.save()
print(f"[{GetTime()}] [API token] files saved! [{text}]")

# 生成uuid
Expand Down
11 changes: 1 addition & 10 deletions code/endpoints/BotLog.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,8 @@
from endpoints.Gtime import GetTime

# 用户数量的记录文件
with open('./log/BotUserLog.json', 'r', encoding='utf-8') as f:
BotUserDict = json.load(f)
from endpoints.FileManage import BotUserDict

# 保存用户的log文件
# 因为logging的使用很频繁,所以不需要经常保存
def log_bot_save():
with open("./log/BotUserLog.json", 'w', encoding='utf-8') as fw2:
json.dump(BotUserDict, fw2, indent=2, sort_keys=True, ensure_ascii=False)

# 记录私聊的用户信息
def log_bot_user(user_id:str):
Expand All @@ -39,12 +33,10 @@ def log_bot_guild(user_id:str,guild_id:str,time):
BotUserDict['guild']['data'][guild_id] = {} #不能连续创建两个键值!
BotUserDict['guild']['data'][guild_id]['user'] = {}
BotUserDict['guild']['data'][guild_id]['user'][user_id] = time
log_bot_save()
return "GNAu"
# 服务器存在,新用户
elif user_id not in BotUserDict['guild']['data'][guild_id]['user']:
BotUserDict['guild']['data'][guild_id]['user'][user_id] = time
log_bot_save()
return "NAu"
# 旧用户更新执行命令的时间,但是不保存文件
else:
Expand Down Expand Up @@ -111,7 +103,6 @@ async def log_bot_list(msg:Message):
continue
# 保存图片和文件
await log_bot_img()
log_bot_save()
print("[log_bot_list] file handling finish, return BotUserDict")
return BotUserDict
except:
Expand Down
27 changes: 4 additions & 23 deletions code/endpoints/BotVip.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,8 @@ def get_uuid():

################################################################################

# 创建uuid dict
VipUuidDict = {}
# 成功兑换vip的用户
VipUserDict = {}

# 加载文件中的uuid
with open("./log/VipUuid.json", 'r', encoding='utf-8') as frrk:
VipUuidDict = json.load(frrk)

# 加载文件中的vip的用户
with open("./log/VipUser.json", 'r', encoding='utf-8') as frus:
VipUserDict = json.load(frus)
# 成功兑换vip的用户+vip的uuid
from endpoints.FileManage import VipUserDict,VipUuidDict


# 计算时间戳,用于给用户设置vip时间
Expand Down Expand Up @@ -77,8 +67,7 @@ async def create_vip_uuid(num: int = 10, day: int = 30):
i -= 1

# 更新uuid
with open("./log/VipUuid.json", 'w', encoding='utf-8') as fw2:
json.dump(VipUuidDict, fw2, indent=2, sort_keys=True, ensure_ascii=False)
VipUuidDict.save()

text = ""
for uuid in NewUuid:
Expand Down Expand Up @@ -135,13 +124,6 @@ async def using_vip_uuid(msg: Message, uuid1: str,bot:Bot,debug_ch:Channel):
print(log_str)
return False

# 更新uuid
with open("./log/VipUuid.json", 'w', encoding='utf-8') as fw2:
json.dump(VipUuidDict, fw2, indent=2, sort_keys=True, ensure_ascii=False)
# 更新vip用户列表
with open("./log/VipUser.json", 'w', encoding='utf-8') as fw2:
json.dump(VipUserDict, fw2, indent=2, sort_keys=True, ensure_ascii=False)

# 发送卡片消息
c.append(Module.Section(Element.Text(text, Types.Text.KMD), Element.Image(src=icon_cm.ahri_kda3, size='sm')))
c.append(Module.Context(Element.Text("您的恩情,阿狸会永远铭记。", Types.Text.KMD)))
Expand Down Expand Up @@ -214,8 +196,7 @@ async def fetch_vip_user():

if vipuserdict_temp != VipUserDict:
#将修改存放到文件中
with open("./log/VipUser.json", 'w', encoding='utf-8') as fw2:
json.dump(VipUserDict, fw2, indent=2, sort_keys=True, ensure_ascii=False)
VipUserDict.save()
print(f"[vip-r] update VipUserDict")

return text
Expand Down
3 changes: 2 additions & 1 deletion code/endpoints/EzAuth.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ def authorize(self,username, password,key):
r = self.session.post(url=URLS.AUTH_URL, json = data)
r = self.session.put(url=URLS.AUTH_URL, json = data2)
data = r.json()
tokens = ["",""] # 提前定义,避免下方出错(理论上来说应该走不到下面)

if "access_token" in r.text:
pattern = compile('access_token=((?:[a-zA-Z]|\d|\.|-|_)*).*id_token=((?:[a-zA-Z]|\d|\.|-|_)*).*expires_in=(\d*)')
Expand Down Expand Up @@ -107,7 +108,7 @@ def authorize(self,username, password,key):
User2faCode[key]['err']="2fa auth_failue"
raise Exception("2fa auth_failure")
else:
print(F"[EzAuth] k:{key} 2fa unkown")
print(F"[EzAuth] k:{key} 2fa unkown err")
User2faCode[key]['err']="auth_failue, maybe wrong 2fa code"
raise Exception("unkown auth err, maybe wrong 2fa code")

Expand Down
Loading

0 comments on commit 311f3c7

Please sign in to comment.