forked from cc004/pcrjjc2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
321 lines (262 loc) · 10.9 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
from json import load, dump
from nonebot import get_bot, on_command
from hoshino import priv
from hoshino.typing import NoticeSession
from .pcrclient import pcrclient, ApiException, bsdkclient
from asyncio import Lock
from os.path import dirname, join, exists
from copy import deepcopy
from traceback import format_exc
from .safeservice import SafeService
import time
sv_help = '''[竞技场绑定 uid] 绑定竞技场排名变动推送,默认双场均启用,仅排名降低时推送
[竞技场查询 (uid)] 查询竞技场简要信息
[停止竞技场订阅] 停止战斗竞技场排名变动推送
[停止公主竞技场订阅] 停止公主竞技场排名变动推送
[启用竞技场订阅] 启用战斗竞技场排名变动推送
[启用公主竞技场订阅] 启用公主竞技场排名变动推送
[删除竞技场订阅] 删除竞技场排名变动推送绑定
[竞技场订阅状态] 查看排名变动推送绑定状态
[详细查询 (uid)] 查询详细状态'''
sv = SafeService('竞技场推送',help_=sv_help, bundle='pcr查询')
@sv.on_fullmatch('竞技场帮助', only_to_me=False)
async def send_jjchelp(bot, ev):
self_ids = bot._wsr_api_clients.keys()
for sid in self_ids:
gl = await bot.get_group_list(self_id=sid)
msg = f"本Bot目前服务群数目{len(gl)}"
await bot.send(ev, f'{sv_help}\n{msg}')
curpath = dirname(__file__)
config = join(curpath, 'binds.json')
root = {
'arena_bind' : {}
}
cache = {}
client = None
lck = Lock()
if exists(config):
with open(config) as fp:
root = load(fp)
binds = root['arena_bind']
captcha_lck = Lock()
with open(join(curpath, 'account.json')) as fp:
acinfo = load(fp)
bot = get_bot()
validate = None
validating = False
acfirst = False
async def captchaVerifier(gt, challenge, userid):
global acfirst, validating
if not acfirst:
await captcha_lck.acquire()
acfirst = True
if acinfo['admin'] == 0:
bot.logger.error('captcha is required while admin qq is not set, so the login can\'t continue')
else:
url = f"https://help.tencentbot.top/geetest/?captcha_type=1&challenge={challenge}>={gt}&userid={userid}&gs=1"
await bot.send_private_msg(
user_id = acinfo['admin'],
message = f'pcr账号登录需要验证码,请完成以下链接中的验证内容后将第一行validate=后面的内容复制,并用指令/pcrval xxxx将内容发送给机器人完成验证\n验证链接:{url}'
)
validating = True
await captcha_lck.acquire()
validating = False
return validate
async def errlogger(msg):
await bot.send_private_msg(
user_id = acinfo['admin'],
message = f'pcrjjc2登录错误:{msg}'
)
bclient = bsdkclient(acinfo, captchaVerifier, errlogger)
client = pcrclient(bclient)
qlck = Lock()
async def query(id: str):
if validating:
raise ApiException('账号被风控,请联系管理员输入验证码并重新登录', -1)
async with qlck:
while client.shouldLogin:
await client.login()
res = (await client.callapi('/profile/get_profile', {
'target_viewer_id': int(id)
}))
return res
# 如需查看所有输出数据,需要将return res改为print (res),然后在qq发送 竞技场查询,最后在终端查看详细输出数据。
def save_binds():
with open(config, 'w') as fp:
dump(root, fp, indent=4)
@sv.on_rex(r'^竞技场绑定 ?(\d{13})$')
async def on_arena_bind(bot, ev):
global binds, lck
async with lck:
uid = str(ev['user_id'])
last = binds[uid] if uid in binds else None
binds[uid] = {
'id': ev['match'].group(1),
'uid': uid,
'gid': str(ev['group_id']),
'arena_on': last is None or last['arena_on'],
'grand_arena_on': last is None or last['grand_arena_on'],
}
save_binds()
await bot.finish(ev, '竞技场绑定成功', at_sender=True)
@sv.on_rex(r'^竞技场查询 ?(\d{13})?$')
async def on_query_arena(bot, ev):
global binds, lck
robj = ev['match']
id = robj.group(1)
async with lck:
if id == None:
uid = str(ev['user_id'])
if not uid in binds:
await bot.finish(ev, '您还未绑定竞技场', at_sender=True)
return
else:
id = binds[uid]['id']
try:
res = await query(id)
last_login_time = int (res['user_info']['last_login_time'])
last_login_date = time.localtime(last_login_time)
last_login_str = time.strftime('%Y-%m-%d %H:%M:%S',last_login_date)
await bot.finish(ev,
f'''昵称:{res['user_info']["user_name"]}
jjc:{res['user_info']["arena_rank"]}
pjjc:{res['user_info']["grand_arena_rank"]}
最后登录:{last_login_str}''', at_sender=False)
except ApiException as e:
await bot.finish(ev, f'查询出错,{e}', at_sender=True)
@sv.on_rex(r'^详细查询 ?(\d{13})?$')
async def on_query_arena_all(bot, ev):
global binds, lck
robj = ev['match']
id = robj.group(1)
async with lck:
if id == None:
uid = str(ev['user_id'])
if not uid in binds:
await bot.finish(ev, '您还未绑定竞技场', at_sender=True)
return
else:
id = binds[uid]['id']
try:
res = await query(id)
arena_time = int (res['user_info']['arena_time'])
arena_date = time.localtime(arena_time)
arena_str = time.strftime('%Y-%m-%d',arena_date)
grand_arena_time = int (res['user_info']['grand_arena_time'])
grand_arena_date = time.localtime(grand_arena_time)
grand_arena_str = time.strftime('%Y-%m-%d',grand_arena_date)
last_login_time = int (res['user_info']['last_login_time'])
last_login_date = time.localtime(last_login_time)
last_login_str = time.strftime('%Y-%m-%d %H:%M:%S',last_login_date)
await bot.finish(ev,
f'''id:{res['user_info']["viewer_id"]}
昵称:{res['user_info']["user_name"]}
公会:{res["clan_name"]}
简介:{res['user_info']["user_comment"]}
最后登录:{last_login_str}
jjc:{res['user_info']["arena_rank"]}
pjjc:{res['user_info']["grand_arena_rank"]}
战力:{res['user_info']["total_power"]}
等级:{res['user_info']["team_level"]}
jjc场次:{res['user_info']["arena_group"]}
jjc创建日:{arena_str}
pjjc场次:{res['user_info']["grand_arena_group"]}
pjjc创建日:{grand_arena_str}
角色数:{res['user_info']["unit_num"]}
''', at_sender=False)
except ApiException as e:
await bot.finish(ev, f'查询出错,{e}', at_sender=True)
@sv.on_rex('(启用|停止)(公主)?竞技场订阅')
async def change_arena_sub(bot, ev):
global binds, lck
key = 'arena_on' if ev['match'].group(2) is None else 'grand_arena_on'
uid = str(ev['user_id'])
async with lck:
if not uid in binds:
await bot.send(ev,'您还未绑定竞技场',at_sender=True)
else:
binds[uid][key] = ev['match'].group(1) == '启用'
save_binds()
await bot.finish(ev, f'{ev["match"].group(0)}成功', at_sender=True)
@on_command('/pcrval')
async def validate(session):
global binds, lck, validate
if session.ctx['user_id'] == acinfo['admin']:
validate = session.ctx['message'].extract_plain_text().strip()[8:]
captcha_lck.release()
@sv.on_prefix('删除竞技场订阅')
async def delete_arena_sub(bot,ev):
global binds, lck
uid = str(ev['user_id'])
if ev.message[0].type == 'at':
if not priv.check_priv(ev, priv.SUPERUSER):
await bot.finish(ev, '删除他人订阅请联系维护', at_sender=True)
return
uid = str(ev.message[0].data['qq'])
elif len(ev.message) == 1 and ev.message[0].type == 'text' and not ev.message[0].data['text']:
uid = str(ev['user_id'])
if not uid in binds:
await bot.finish(ev, '未绑定竞技场', at_sender=True)
return
async with lck:
binds.pop(uid)
save_binds()
await bot.finish(ev, '删除竞技场订阅成功', at_sender=True)
@sv.on_fullmatch('竞技场订阅状态')
async def send_arena_sub_status(bot,ev):
global binds, lck
uid = str(ev['user_id'])
if not uid in binds:
await bot.send(ev,'您还未绑定竞技场', at_sender=True)
else:
info = binds[uid]
await bot.finish(ev,
f'''
当前竞技场绑定ID:{info['id']}
竞技场订阅:{'开启' if info['arena_on'] else '关闭'}
公主竞技场订阅:{'开启' if info['grand_arena_on'] else '关闭'}''',at_sender=True)
@sv.scheduled_job('interval', minutes=1) # minutes是刷新频率,可按自身服务器性能输入其他数值,可支持整数、小数
async def on_arena_schedule():
global cache, binds, lck
bot = get_bot()
bind_cache = {}
async with lck:
bind_cache = deepcopy(binds)
for user in bind_cache:
info = bind_cache[user]
try:
sv.logger.info(f'querying {info["id"]} for {info["uid"]}')
res = await query(info['id'])
res = (res['user_info']['arena_rank'], res['user_info']['grand_arena_rank'])
if user not in cache:
cache[user] = res
continue
last = cache[user]
cache[user] = res
if res[0] > last[0] and info['arena_on']:
await bot.send_group_msg(
group_id = int(info['gid']),
message = f'[CQ:at,qq={info["uid"]}]jjc:{last[0]}->{res[0]} ▼{res[0]-last[0]}'
)
if res[1] > last[1] and info['grand_arena_on']:
await bot.send_group_msg(
group_id = int(info['gid']),
message = f'[CQ:at,qq={info["uid"]}]pjjc:{last[1]}->{res[1]} ▼{res[1]-last[1]}'
)
except ApiException as e:
sv.logger.info(f'对{info["id"]}的检查出错\n{format_exc()}')
if e.code == 6:
async with lck:
binds.pop(user)
save_binds()
sv.logger.info(f'已经自动删除错误的uid={info["id"]}')
except:
sv.logger.info(f'对{info["id"]}的检查出错\n{format_exc()}')
@sv.on_notice('group_decrease.leave')
async def leave_notice(session: NoticeSession):
global lck, binds
uid = str(session.ctx['user_id'])
async with lck:
if uid in binds:
binds.pop(uid)
save_binds()