Skip to content

Commit

Permalink
为exe做好了铺垫
Browse files Browse the repository at this point in the history
  • Loading branch information
NekoRabi committed Jul 30, 2022
1 parent 29ab484 commit 3ab59fc
Show file tree
Hide file tree
Showing 9 changed files with 176 additions and 141 deletions.
2 changes: 1 addition & 1 deletion data/sys/help.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ grouphelp:
- "我的塔罗牌 : 获取你的塔罗牌记录"
- "项目地址 : 获取项目链接\n"

privatehelp:
friendhelp:
- "私聊指令:\n"
- "addadmin / deladmin QQ号 :添加或者删除机器人管理员\n"
- "addwhitelist /delwhitelist QQ号 :修改白名单\n"
Expand Down
83 changes: 46 additions & 37 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,21 +55,21 @@


async def sendMsgChain(msg: Union[MessageChain, str, MessageComponent], event: MessageEvent = None,
grouptarget: int = None,
friendtarget: int = None):
grouptarget: int = None, friendtarget: int = None, errortext: str = None):
res = 0
if msg is str:
msg = MessageChain(Plain(msg))
elif msg is MessageComponent:
if msg is not MessageChain:
msg = MessageChain(msg)
errtext = "消息发送失败"
onlyImg = False
imgSendErrText = f"图片发送失败,这肯定不是{botname}的问题!"
msgComponentTypeList = set()
if errortext:
errtext = errortext
imgSendErrText = errortext
onlyImg = False
msgComponentTypeList = []

for component in msg:
msgComponentTypeList.add(component.type)
if msgComponentTypeList == set('Image'):
msgComponentTypeList.append(component.type)
if msgComponentTypeList == ['Image']:
onlyImg = True
if event:
res = await bot.send(event, msg)
Expand Down Expand Up @@ -101,22 +101,25 @@ async def sendMsgChain(msg: Union[MessageChain, str, MessageComponent], event: M

async def asyqh_autopaipu():
print("开始查询雀魂信息")
result = majsoul.asygetqhpaipu()
result = await majsoul.asygetqhpaipu()
print(result)
for msgobj in result:
for group in msgobj['groups']:
await bot.send_group_message(group, msgobj['msg'])
b64 = text_to_image(text=msgobj['msg'], needtobase64=True)
# await bot.send_group_message(group, msgobj['msg'])
await sendMsgChain(grouptarget=group, msg=makeMsgChain(imgbase64=b64))
return


async def asyth_all():
print("开始查询天凤信息")
result = tenhou.asygetTH()
result = await tenhou.asygetTH()
print(result)
for msgobj in result:
for group in msgobj['groups']:
# await bot.send_group_message(group,makeMsgChain()(imgbase64=msgobj['imgbase']))
await bot.send_group_message(group, msgobj['msg'])
b64 = text_to_image(text=msgobj['msg'], needtobase64=True)
# await bot.send_group_message(group, msgobj['msg'])
await sendMsgChain(grouptarget=group, msg=makeMsgChain(imgbase64=b64))
return


Expand Down Expand Up @@ -383,12 +386,11 @@ async def getsomesetu(event: GroupMessage):
if not cmdbuffer.updategroupcache(groupcommand(event.group.id, event.sender.id, 'setu')):
return bot.send(event, makeMsgChain(text="你冲的频率太频繁了,休息一下吧", rndimg=True, at=event.sender.id))
try:
imginfo = stfinder.getsetu(
imginfo = await stfinder.getsetu(
m1.group(2), groupid=event.group.id)
if imginfo['FoundError']:
return await sendMsgChain(event=event,
msg=makeMsgChain(at=event.sender.id, text=imginfo['ErrorMsg']))
# await bot.send(event, MessageChain([Image(url=imginfo['url'])]))
await sendMsgChain(event=event, msg=makeMsgChain(imgurl=imginfo['url']))
except Exception as e:
print(f"色图请求失败:{e}")
Expand All @@ -404,7 +406,7 @@ async def getsomesetu(event: GroupMessage):
return bot.send(event, makeMsgChain(at=event.sender.id, text="你冲的频率太频繁了,休息一下吧", rndimg=True))

try:
imginfo = stfinder.getsetu(
imginfo = await stfinder.getsetu(
m2.group(2), event.group.id, m2.group(1))
if imginfo['FoundError']:
return await bot.send(event, makeMsgChain(at=event.sender.id, text=imginfo['ErrorMsg']))
Expand Down Expand Up @@ -720,15 +722,19 @@ async def qhpt(event: GroupMessage):
return bot.send(event, makeMsgChain(text="你查的太频繁了,休息一下好不好", rndimg=True, at=event.sender.id))
if m.group(3):
if m.group(4):
await bot.send(event, majsoul.getcertaininfo(m.group(2), m.group(3), int(m.group(4))))
await sendMsgChain(event=event,
msg=majsoul.getcertaininfo(m.group(2), m.group(3), int(m.group(4))))
else:
await bot.send(event, majsoul.getcertaininfo(m.group(2), m.group(3)))
await sendMsgChain(msg=majsoul.getcertaininfo(m.group(2), m.group(3)), event=event)
else:
result = majsoul.query(m.group(2))
if result['error']:
await bot.send(event, result['msg'])
# await bot.send(event, result['msg'])
await sendMsgChain(msg=result['msg'], event=event)
else:
await bot.send(event, Image(path=f'./images/MajsoulInfo/qhpt{m.group(2)}.png'))
await sendMsgChain(msg=Image(path=f'./images/MajsoulInfo/qhpt{m.group(2)}.png'), event=event,
errortext=result['msg'])
# await bot.send(event, Image(path=f'./images/MajsoulInfo/qhpt{m.group(2)}.png'))
return


Expand All @@ -740,25 +746,26 @@ async def getrecentqhpaipu(event: GroupMessage):
if qhsettings['qhpaipu'] and event.group.id not in qhsettings['dispaipugroup']:

if not cmdbuffer.updategroupcache(groupcommand(event.group.id, event.sender.id, 'qhpaipu')):
return bot.send(event, makeMsgChain(text="你查的太频繁了,休息一下好不好", rndimg=True, at=event.sender.id))
return sendMsgChain(event=event,
msg=makeMsgChain(text="你查的太频繁了,休息一下好不好", rndimg=True, at=event.sender.id))
playername = m.group(2)
searchtype = m.group(3)
searchnumber = 5
if searchtype:
if searchtype not in ['3', '4']:
await bot.send(event, '牌局参数有误,请输入 3 或 4')
return
return await sendMsgChain(event=event, msg='牌局参数有误,请输入 3 或 4')

if m.group(4):
searchnumber = int(m.group(4))
if 0 < searchnumber < 11:
await bot.send(event,
majsoul.getsomeqhpaipu(playername=playername, type=searchtype,
counts=searchnumber))
return
else:
await bot.send(event, "牌局数量有误,最多支持10场牌局")
return
if not 0 < searchnumber < 11:
return await bot.send(event, "牌局数量有误,最多支持10场牌局")
result = await majsoul.getsomeqhpaipu(playername=playername, type=searchtype,
counts=searchnumber)
if not result['err']:
await sendMsgChain(event=event,
msg=makeMsgChain(imgbase64=result['img64']), errortext=result['msg'])
else:
await bot.send(event, majsoul.getsomeqhpaipu(playername=playername, type=searchtype))
await sendMsgChain(event=event, msg=result['msg'])


@bot.on(GroupMessage)
Expand Down Expand Up @@ -1049,7 +1056,7 @@ async def ranktenhouplayer(event: GroupMessage):
reset = False
else:
reset = False
await sendMsgChain(makeMsgChain(text=tenhou.getthpt(m.group(2), reset)), event=event)
await sendMsgChain(makeMsgChain(text=await tenhou.getthpt(m.group(2), reset)), event=event)
# await bot.send(event, tenhou.getthpt(m.group(2), reset))


Expand Down Expand Up @@ -1367,7 +1374,9 @@ async def touchhead(event: GroupMessage):
if At in event.message_chain:
target = event.message_chain.get_first(At).target
await petpet(target)
await bot.send(event, MessageChain(Image(path=f'./images/PetPet/temp/tempPetPet-{target}.gif')))
if await bot.send(event,
MessageChain(Image(path=f'./images/PetPet/temp/tempPetPet-{target}.gif'))) == -1:
print('摸头发送失败')
# else:
# target = m.group(2)
# await petpet(target)
Expand Down Expand Up @@ -1525,8 +1534,8 @@ async def Nudgepetpet(event: NudgeEvent):
await petpet(target)
await bot.send_group_message(event.subject.id,
MessageChain(
Image(
path=f'./images/PetPet/temp/tempPetPet-{target}.gif')))
await Image.from_local(
filename=f'./images/PetPet/temp/tempPetPet-{target}.gif')))
else:
if random.random() < nudgeconfig['sendnudgechance']:
if random.random() < nudgeconfig['supersendnudgechance']:
Expand Down
77 changes: 44 additions & 33 deletions plugin/MajSoulInfo/majsoulinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,11 +191,11 @@ def getplayerdetail(self, playername: str, selecttype: str, selectlevel: list =
text_to_image(path=f"MajsoulInfo/detail{playername}.png", text=msg)
return dict(msg=msg, error=False)

def getsomeqhpaipu(self, playername: str, type="4", counts=5):
async def getsomeqhpaipu(self, playername: str, type="4", counts=5):
nowtime = time.time()
ptupdate = 0
nowtime = math.floor(nowtime / 10) * 10000 + 9999

ERROR = False
async def asyrecordsrequest(playerid, type, counts) -> list:
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False, limit=5), timeout=aiotimeout,
headers={'User-Agent': random.choice(user_agent_list)}) as session:
Expand Down Expand Up @@ -223,27 +223,33 @@ async def asyrecordsrequest(playerid, type, counts) -> list:
return "查询失败,数据库中无此用户,请先用 qhpt 查询该用户。"
playerid = playerid[0][0]
paipuInfo = f"最近{counts}场对局信息如下:"
content = finish_all_asytasks(
[asyrecordsrequest(playerid=playerid, type=type, counts=counts)])[0]
for item in content:
paipuurl = f'https://game.maj-soul.net/1/?paipu={item["uuid"]}'
startTime = time.strftime(
'%Y-%m-%d %H:%M:%S', time.localtime(item["startTime"]))
endTime = time.strftime('%Y-%m-%d %H:%M:%S',
time.localtime(item["endTime"]))
players = item['players']
paipuInfo += f"\n牌谱链接 : {paipuurl}\n"
paipuInfo += f"开始时间: {startTime}\n结束时间: {endTime}\n对局玩家:\n"
for player in players:
if player['nickname'].strip() == playername.strip():
ptupdate += int(player['gradingScore'])
paipuInfo += f"{player['nickname']} : {player['score']} ({player['gradingScore']})\n"
paipuInfo += "\n"
paipuInfo += f"\n总PT变化 : {ptupdate}"
return paipuInfo
# s = requests.Session()
# s.mount('http://', HTTPAdapter(max_retries=3))
# s.mount('https://', HTTPAdapter(max_retries=3))
# content = finish_all_asytasks(
# [asyrecordsrequest(playerid=playerid, type=type, counts=counts)])[0]
try:
content = await asyrecordsrequest(playerid=playerid, type=type, counts=counts)
for item in content:
# paipuurl = f'https://game.maj-soul.net/1/?paipu={item["uuid"]}'
paipuurl = f'{item["uuid"]}'
startTime = time.strftime(
'%Y-%m-%d %H:%M:%S', time.localtime(item["startTime"]))
endTime = time.strftime('%Y-%m-%d %H:%M:%S',
time.localtime(item["endTime"]))
players = item['players']
paipuInfo += f"\n牌谱UID: {paipuurl}\n开始时间: {startTime}\n结束时间: {endTime}\n对局玩家:\n"
for player in players:
if player['nickname'].strip() == playername.strip():
ptupdate += int(player['gradingScore'])
paipuInfo += f"{player['nickname']} : {player['score']} ({player['gradingScore']})\n"
paipuInfo += "\n"
paipuInfo += f"\n总PT变化 : {ptupdate}"
except asyncio.TimeoutError as e:
print(e)
ERROR = True
paipuInfo = '牌谱查询超时'
result = dict(msg=paipuInfo,err=ERROR)
if not ERROR:
result['img64'] = text_to_image(text=paipuInfo, needtobase64=True)
return result

def getpaipu(self, playerid: str) -> dict:
nowtime = time.time()
Expand Down Expand Up @@ -679,7 +685,7 @@ def clearallwatch(self, groupid: int):
self.tagoffplayer(groupid=groupid)
return "清除成功"

def asygetqhpaipu(self):
async def asygetqhpaipu(self):
nowtime = time.time()
nowtime = math.floor(nowtime / 10) * 10000 + 9999
cx = sqlite3.connect('./database/MajSoulInfo/majsoul.sqlite')
Expand All @@ -692,11 +698,15 @@ def asygetqhpaipu(self):
content = []
for item in res:
playeridlist.append(item[0])
results = finish_all_asytasks(
[paipu_pl3(playeridlist, nowtime), paipu_pl4(playeridlist, nowtime)])
for result in results:
content.extend(msganalysis(result))
return content
# results = finish_all_asytasks(
# [paipu_pl3(playeridlist, nowtime), paipu_pl4(playeridlist, nowtime)])
results = await paipu_pl3(playeridlist, nowtime) + await paipu_pl4(playeridlist, nowtime)
# for result in results:
# content.extend(msganalysis(result))
return msganalysis(results)
# content.extend(msganalysis(results))

# return content

def query(self, username: str, selecttype: str = "", selectindex: int = 0) -> dict:
userinfo = getinfo(username)
Expand Down Expand Up @@ -1002,7 +1012,7 @@ def getinfo(username: str, selecttype: str = "4", selectindex: int = 0) -> dict:
# print("查询玩家时读取超时")
# return dict(error=True, muti3=muti3, muti4=muti4, offline=False)

async def paipu_pl3(playeridlist, nowtime):
async def paipu_pl3(playeridlist, nowtime) -> list:
contentlist = []
if len(playeridlist) >= 25:
timeout = aiohttp.ClientTimeout(total=15)
Expand All @@ -1015,7 +1025,7 @@ async def paipu_pl3(playeridlist, nowtime):
async with session.get(
f"https://ak-data-1.sapk.ch/api/v2/pl3/player_records/{playerid}/{nowtime}/1262304000000"
"?limit=1&mode=21,22,23,24,25,26&descending=true") as response:
text: list = eval(await response.text())
text: list = json.loads(await response.text())
if len(text) > 0:
contentlist.append(
dict(playerid=playerid, content=text[0]))
Expand Down Expand Up @@ -1044,7 +1054,7 @@ async def paipu_pl4(playeridlist, nowtime) -> list:
async with session.get(
f"https://ak-data-5.sapk.ch/api/v2/pl4/player_records/{playerid}/{nowtime}/1262304000000"
"?limit=1&mode=8,9,11,12,15,16&descending=true") as response:
text: list = eval(await response.text())
text: list = json.loads(await response.text())
if len(text) > 0:
contentlist.append(
dict(playerid=playerid, content=text[0]))
Expand Down Expand Up @@ -1239,7 +1249,8 @@ def getScore(e):
if len(msgitem) == 0:
continue
paipuInfo = ""
paipuurl = f'https://game.maj-soul.net/1/?paipu={msgitem["uuid"]}'
# paipuurl = f'https://game.maj-soul.net/1/?paipu={msgitem["uuid"]}'
paipuurl = f'{msgitem["uuid"]}'
startTime = time.strftime(
'%Y-%m-%d %H:%M:%S', time.localtime(msgitem["startTime"]))
endTime = time.strftime('%Y-%m-%d %H:%M:%S',
Expand Down
Loading

0 comments on commit 3ab59fc

Please sign in to comment.