koishi-plugin-bilibili-notify 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ import { Context } from "koishi";
2
+ declare class Authority {
3
+ constructor(ctx: Context);
4
+ }
5
+ export default Authority;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class Authority {
4
+ constructor(ctx) {
5
+ // 授予权限
6
+ ctx.permissions.provide('qqguild.admin', async (name, session) => {
7
+ return session.event.user.id === '12814193631283946447';
8
+ });
9
+ }
10
+ }
11
+ exports.default = Authority;
package/lib/biliAPI.d.ts CHANGED
@@ -24,6 +24,6 @@ declare class BiliAPI extends Service {
24
24
  createNewClient(): void;
25
25
  getCookies(): Promise<string>;
26
26
  loadCookiesFromDatabase(): Promise<void>;
27
- checkIfTokenNeedRefresh(refreshToken: string, csrf: string): Promise<void>;
27
+ checkIfTokenNeedRefresh(refreshToken: string, csrf: string, times?: number): Promise<void>;
28
28
  }
29
29
  export default BiliAPI;
package/lib/biliAPI.js CHANGED
@@ -35,42 +35,87 @@ class BiliAPI extends koishi_1.Service {
35
35
  this.logger.info('BiliAPI已被注册到Context中');
36
36
  }
37
37
  async getTimeNow() {
38
- const { data } = await this.client.get(GET_TIME_NOW);
39
- return data;
38
+ try {
39
+ const { data } = await this.client.get(GET_TIME_NOW);
40
+ return data;
41
+ }
42
+ catch (e) {
43
+ throw new Error('网络异常,本次请求失败!');
44
+ }
40
45
  }
41
46
  async getUserSpaceDynamic(mid) {
42
- const { data } = await this.client.get(`${GET_USER_SPACE_DYNAMIC_LIST}?host_mid=${mid}`);
43
- return data;
47
+ try {
48
+ const { data } = await this.client.get(`${GET_USER_SPACE_DYNAMIC_LIST}?host_mid=${mid}`);
49
+ return data;
50
+ }
51
+ catch (e) {
52
+ throw new Error('网络异常,本次请求失败!');
53
+ }
44
54
  }
45
55
  // Check if Token need refresh
46
56
  async getCookieInfo(refreshToken) {
47
- const { data } = await this.client.get(`${GET_COOKIES_INFO}?csrf=${refreshToken}`);
48
- return data;
57
+ try {
58
+ const { data } = await this.client.get(`${GET_COOKIES_INFO}?csrf=${refreshToken}`);
59
+ return data;
60
+ }
61
+ catch (e) {
62
+ throw new Error('网络异常,本次请求失败!');
63
+ }
49
64
  }
50
65
  async getUserInfo(mid) {
51
- const wbi = await this.ctx.wbi.getWbi({ mid });
52
- const { data } = await this.client.get(`${GET_USER_INFO}?${wbi}`);
53
- return data;
66
+ try {
67
+ const wbi = await this.ctx.wbi.getWbi({ mid });
68
+ const { data } = await this.client.get(`${GET_USER_INFO}?${wbi}`);
69
+ return data;
70
+ }
71
+ catch (e) {
72
+ throw new Error('网络异常,本次请求失败!');
73
+ }
54
74
  }
55
75
  async getMyselfInfo() {
56
- const { data } = await this.client.get(GET_MYSELF_INFO);
57
- return data;
76
+ try {
77
+ const { data } = await this.client.get(GET_MYSELF_INFO);
78
+ return data;
79
+ }
80
+ catch (e) {
81
+ throw new Error('网络异常,本次请求失败!');
82
+ }
58
83
  }
59
84
  async getLoginQRCode() {
60
- const { data } = await this.client.get(GET_LOGIN_QRCODE);
61
- return data;
85
+ try {
86
+ const { data } = await this.client.get(GET_LOGIN_QRCODE);
87
+ return data;
88
+ }
89
+ catch (e) {
90
+ throw new Error('网络异常,本次请求失败!');
91
+ }
62
92
  }
63
93
  async getLoginStatus(qrcodeKey) {
64
- const { data } = await this.client.get(`${GET_LOGIN_STATUS}?qrcode_key=${qrcodeKey}`);
65
- return data;
94
+ try {
95
+ const { data } = await this.client.get(`${GET_LOGIN_STATUS}?qrcode_key=${qrcodeKey}`);
96
+ return data;
97
+ }
98
+ catch (e) {
99
+ throw new Error('网络异常,本次请求失败!');
100
+ }
66
101
  }
67
102
  async getLiveRoomInfo(roomId) {
68
- const { data } = await this.client.get(`${GET_LIVE_ROOM_INFO}?room_id=${roomId}`);
69
- return data;
103
+ try {
104
+ const { data } = await this.client.get(`${GET_LIVE_ROOM_INFO}?room_id=${roomId}`);
105
+ return data;
106
+ }
107
+ catch (e) {
108
+ throw new Error('网络异常,本次请求失败!');
109
+ }
70
110
  }
71
111
  async getMasterInfo(mid) {
72
- const { data } = await this.client.get(`${GET_MASTER_INFO}?uid=${mid}`);
73
- return data;
112
+ try {
113
+ const { data } = await this.client.get(`${GET_MASTER_INFO}?uid=${mid}`);
114
+ return data;
115
+ }
116
+ catch (e) {
117
+ throw new Error('网络异常,本次请求失败!');
118
+ }
74
119
  }
75
120
  createNewClient() {
76
121
  this.jar = new tough_cookie_1.CookieJar();
@@ -120,8 +165,22 @@ class BiliAPI extends koishi_1.Service {
120
165
  // Check if token need refresh
121
166
  this.checkIfTokenNeedRefresh(decryptedRefreshToken, csrf);
122
167
  }
123
- async checkIfTokenNeedRefresh(refreshToken, csrf) {
124
- const { data } = await this.getCookieInfo(refreshToken);
168
+ async checkIfTokenNeedRefresh(refreshToken, csrf, times = 0) {
169
+ let data;
170
+ try {
171
+ const { data: cookieData } = await this.getCookieInfo(refreshToken);
172
+ data = cookieData;
173
+ }
174
+ catch (e) {
175
+ // 发送三次仍网络错误则给管理员发送错误信息
176
+ if (times > 3)
177
+ return;
178
+ // 等待3秒再次尝试
179
+ this.ctx.setTimeout(() => {
180
+ this.checkIfTokenNeedRefresh(refreshToken, csrf, times + 1);
181
+ }, 3000);
182
+ return;
183
+ }
125
184
  // 不需要刷新,直接返回
126
185
  if (!data.refresh)
127
186
  return;
@@ -1,34 +1,33 @@
1
- import { Context, Logger, Schema, Session } from "koishi";
1
+ import { Bot, Context, Logger, Schema, Session } from "koishi";
2
2
  declare class ComRegister {
3
3
  static inject: string[];
4
4
  logger: Logger;
5
5
  config: ComRegister.Config;
6
- id: number;
7
- sub: {
8
- id: number;
9
- uid: string;
10
- room_id: string;
11
- dynamic: number;
12
- video: 1;
13
- live: number;
14
- time: Date;
15
- };
6
+ num: number;
16
7
  subManager: {
8
+ id: number;
17
9
  uid: string;
18
10
  roomId: string;
11
+ targetId: string;
19
12
  live: boolean;
20
13
  dynamic: boolean;
21
14
  liveDispose: Function;
22
15
  dynamicDispose: Function;
23
16
  }[];
17
+ qqBot: Bot<Context>;
18
+ qqguildBot: Bot<Context>;
24
19
  constructor(ctx: Context, config: ComRegister.Config);
25
- dynamicDetect(ctx: Context, session: Session, uid: string): () => Promise<"账号未登录" | "未知错误">;
26
- liveDetect(ctx: Context, session: Session, roomId: string): () => Promise<void>;
20
+ dynamicDetect(ctx: Context, bot: Bot<Context>, guildId: string, uid: string): () => Promise<void>;
21
+ liveDetect(ctx: Context, bot: Bot<Context>, guildId: string, roomId: string): () => Promise<void>;
27
22
  checkIfNeedSub(comNeed: boolean, subType: string, session: Session, data?: any): Promise<boolean>;
23
+ getSubFromDatabase(ctx: Context): Promise<void>;
24
+ unsubSingle(ctx: Context, id: string, type: number): string;
28
25
  }
29
26
  declare namespace ComRegister {
30
27
  interface Config {
31
28
  pushTime: number;
29
+ liveLoopTime: number;
30
+ dynamicLoopTime: number;
32
31
  }
33
32
  const Config: Schema<Config>;
34
33
  }
@@ -16,12 +16,20 @@ class ComRegister {
16
16
  static inject = ['biliAPI', 'gimg', 'wbi', 'database'];
17
17
  logger;
18
18
  config;
19
- id = 1;
20
- sub;
19
+ num = 0;
21
20
  subManager = [];
21
+ // QQ群机器人
22
+ qqBot;
23
+ // QQ频道机器人
24
+ qqguildBot;
22
25
  constructor(ctx, config) {
23
26
  this.logger = ctx.logger('commandRegister');
24
27
  this.config = config;
28
+ // 拿到QQ群机器人
29
+ this.qqBot = ctx.bots[ctx.bots.findIndex(bot => bot.platform === 'qq')];
30
+ // 拿到QQ频道机器人
31
+ this.qqguildBot = ctx.bots[ctx.bots.findIndex(bot => bot.platform === 'qqguild')];
32
+ this.getSubFromDatabase(ctx);
25
33
  ctx.command('test')
26
34
  .subcommand('.cookies')
27
35
  .usage('测试指令,用于测试从数据库读取cookies')
@@ -61,10 +69,10 @@ class ComRegister {
61
69
  console.log(num && `Hello World`);
62
70
  });
63
71
  ctx.command('test')
64
- .subcommand('.gimg <uid:string> <index:number>')
72
+ .subcommand('.gimg <uid:string> <index:number>', '生成图片', { permissions: ['qqguild.admin'] })
65
73
  .usage('测试图片生成')
66
74
  .example('test.gimg')
67
- .action(async (_, uid, index) => {
75
+ .action(async ({ session }, uid, index) => {
68
76
  // 获取用户空间动态数据
69
77
  const { data } = await ctx.biliAPI.getUserSpaceDynamic(uid);
70
78
  const [pic] = await ctx.gimg.generateDynamicImg(data.items[index]);
@@ -77,6 +85,20 @@ class ComRegister {
77
85
  .action(() => {
78
86
  console.log(this.subManager);
79
87
  });
88
+ ctx.command('test')
89
+ .subcommand('.group')
90
+ .usage('查看session groupId')
91
+ .example('test group')
92
+ .action(({ session }) => {
93
+ console.log(session.event.channel);
94
+ });
95
+ ctx.command('test')
96
+ .subcommand('.session')
97
+ .usage('查看seesion')
98
+ .example('test session')
99
+ .action(({ session }) => {
100
+ console.log(session);
101
+ });
80
102
  ctx.command('bili', 'bili-notify插件相关指令')
81
103
  .subcommand('.login', '登录B站之后才可以进行之后的操作')
82
104
  .usage('使用二维码登录,登录B站之后才可以进行之后的操作')
@@ -84,7 +106,13 @@ class ComRegister {
84
106
  .action(async ({ session }) => {
85
107
  this.logger.info('调用bili login指令');
86
108
  // 获取二维码
87
- const content = await ctx.biliAPI.getLoginQRCode();
109
+ let content;
110
+ try {
111
+ content = await ctx.biliAPI.getLoginQRCode();
112
+ }
113
+ catch (e) {
114
+ return 'bili login getLoginQRCode() 本次网络请求失败';
115
+ }
88
116
  // 判断是否出问题
89
117
  if (content.code !== 0)
90
118
  return await session.send('出问题咯,请联系管理员解决!');
@@ -109,7 +137,14 @@ class ComRegister {
109
137
  let dispose;
110
138
  // 发起登录请求检查登录状态
111
139
  dispose = ctx.setInterval(async () => {
112
- const loginContent = await ctx.biliAPI.getLoginStatus(content.data.qrcode_key);
140
+ let loginContent;
141
+ try {
142
+ loginContent = await ctx.biliAPI.getLoginStatus(content.data.qrcode_key);
143
+ }
144
+ catch (e) {
145
+ this.logger.error(e);
146
+ return;
147
+ }
113
148
  if (loginContent.code !== 0) {
114
149
  dispose();
115
150
  return await session.send('登录失败!请联系管理员解决!');
@@ -132,27 +167,47 @@ class ComRegister {
132
167
  }, 1000);
133
168
  });
134
169
  ctx.command('bili')
135
- .subcommand('.unsub <uid:string>')
136
- .usage('取消订阅')
137
- .example('bili unsub 用户UID')
138
- .action(({ session }, uid) => {
170
+ .subcommand('.unsub <uid:string> 取消订阅')
171
+ .usage('取消订阅,加-l为取消直播订阅,加-d为取消动态订阅,什么都不加则为全部取消')
172
+ .option('live', '-l')
173
+ .option('dynamic', '-d')
174
+ .example('bili unsub 用户UID -ld')
175
+ .action(async ({ session, options }, uid) => {
176
+ this.logger.info('调用bili.unsub指令');
177
+ // 若用户UID为空则直接返回
139
178
  if (!uid)
140
179
  return '用户UID不能为空';
141
180
  // 定义是否存在
142
- let exist = false;
143
- this.subManager.forEach((sub, i) => {
181
+ let exist;
182
+ await Promise.all(this.subManager.map(async (sub, i) => {
144
183
  if (sub.uid === uid) {
145
- // 执行dispose方法,销毁定时器
146
- this.subManager[i].dynamicDispose();
147
- this.subManager[i].liveDispose();
184
+ // 取消单个订阅
185
+ if (options.live || options.dynamic) {
186
+ if (options.live)
187
+ await session.send(this.unsubSingle(ctx, sub.roomId, 0)); /* 0为取消订阅Live */
188
+ if (options.dynamic)
189
+ await session.send(this.unsubSingle(ctx, sub.uid, 1)); /* 1为取消订阅Dynamic */
190
+ // 将存在flag设置为true
191
+ exist = true;
192
+ return;
193
+ }
194
+ // 取消全部订阅 执行dispose方法,销毁定时器
195
+ if (sub.dynamic)
196
+ this.subManager[i].dynamicDispose();
197
+ if (sub.live)
198
+ this.subManager[i].liveDispose();
199
+ // 从数据库中删除订阅
200
+ await ctx.database.remove('bilibili', { uid: this.subManager[i].uid });
148
201
  // 将该订阅对象从订阅管理对象中移除
149
202
  this.subManager = this.subManager.splice(i, i);
203
+ // id--
204
+ this.num--;
150
205
  // 发送成功通知
151
206
  session.send('已取消订阅该用户');
152
207
  // 将存在flag设置为true
153
208
  exist = true;
154
209
  }
155
- });
210
+ }));
156
211
  // 未订阅该用户,无需取消订阅
157
212
  !exist && session.send('未订阅该用户,无需取消订阅');
158
213
  });
@@ -163,33 +218,39 @@ class ComRegister {
163
218
  .action(async ({ session }) => {
164
219
  let table = ``;
165
220
  this.subManager.forEach(sub => {
166
- table += 'UID:' + sub.uid + ' RoomID:' + sub.roomId + '\n';
221
+ table += `UID:${sub.uid} ${sub.dynamic ? '已订阅动态' : ''} ${sub.live ? '已订阅直播' : ''}` + '\n';
167
222
  });
168
223
  !table && session.send('没有订阅任何UP');
169
224
  table && session.send(table);
170
225
  });
171
226
  ctx.command('bili')
172
- .subcommand('.sub <mid:string> [groupid:string]')
227
+ .subcommand('.sub <mid:string> [guildId:string]')
173
228
  .option('live', '-l')
174
229
  .option('dynamic', '-d')
175
230
  .usage('订阅用户动态和直播通知,若需要订阅直播请加上-l,需要订阅动态则加上-d。若没有加任何参数,之后会向你单独询问,<>中为必选参数,[]中为可选参数,目标群号若不填,则默认为当前群聊')
176
231
  .example('bili sub 用户uid 目标QQ群号(暂不支持) -l -d')
177
- .action(async ({ session, options }, mid, groupid) => {
232
+ .action(async ({ session, options }, mid, guildId) => {
178
233
  this.logger.info('调用bili.sub指令');
234
+ // 如果订阅人数超过三个则直接返回
235
+ if (this.num >= 3)
236
+ return '目前最多只能订阅三个人';
179
237
  // 检查必选参数是否有值
180
- if (mid === undefined) {
238
+ if (!mid)
181
239
  return '请输入用户uid';
182
- }
183
240
  // 判断要订阅的用户是否已经存在于订阅管理对象中
184
- this.subManager && this.subManager.forEach((sub) => {
185
- // 已订阅该用户
186
- if (sub.uid === mid)
187
- return session.send('已订阅该用户,请勿重复订阅');
188
- });
241
+ if (this.subManager && this.subManager.some(sub => sub.uid === mid)) {
242
+ return '已订阅该用户,请勿重复订阅';
243
+ }
189
244
  // 定义是否需要直播通知,动态订阅,视频推送
190
245
  let liveMsg, dynamicMsg;
191
246
  // 获取用户信息
192
- const content = await ctx.biliAPI.getUserInfo(mid);
247
+ let content;
248
+ try {
249
+ content = await ctx.biliAPI.getUserInfo(mid);
250
+ }
251
+ catch (e) {
252
+ return 'bili sub getUserInfo() 本次网络请求失败';
253
+ }
193
254
  // 判断是否有其他问题
194
255
  if (content.code !== 0) {
195
256
  let msg;
@@ -216,99 +277,151 @@ class ComRegister {
216
277
  liveMsg = await this.checkIfNeedSub(options.live, '直播', session, data);
217
278
  // 判断是否需要订阅动态
218
279
  dynamicMsg = await this.checkIfNeedSub(options.dynamic, '动态', session);
219
- // 构造订阅对象
220
- this.sub = {
221
- id: this.id,
280
+ // 判断是哪个平台
281
+ let platform;
282
+ if (!guildId) { // 没有输入群号,默认当前聊天环境
283
+ switch (session.event.platform) {
284
+ case 'qqguild':
285
+ guildId = session.event.channel.id;
286
+ break;
287
+ case 'qq':
288
+ guildId = session.event.guild.id;
289
+ break;
290
+ default: return '暂不支持该平台';
291
+ }
292
+ }
293
+ // 定义Bot
294
+ let bot;
295
+ // 判断是哪个聊天平台
296
+ switch (session.event.platform) {
297
+ case 'qqguild': {
298
+ bot = this.qqguildBot;
299
+ platform = 'qqguild';
300
+ break;
301
+ }
302
+ case 'qq': {
303
+ bot = this.qqBot;
304
+ platform = 'qq';
305
+ break;
306
+ }
307
+ default: return '暂不支持该平台';
308
+ }
309
+ // 保存到数据库中
310
+ const sub = await ctx.database.create('bilibili', {
222
311
  uid: mid,
223
312
  room_id: data.live_room.roomid.toString(),
224
313
  dynamic: dynamicMsg ? 1 : 0,
225
314
  video: 1,
226
315
  live: liveMsg ? 1 : 0,
316
+ targetId: guildId,
317
+ platform,
227
318
  time: new Date()
228
- };
229
- // 保存到数据库中
230
- await ctx.database.upsert('bilibili', [this.sub]);
231
- // 让id自增
232
- this.id++;
319
+ });
320
+ // 订阅数+1
321
+ this.num++;
233
322
  // 开始订阅
234
323
  // 保存新订阅对象
235
324
  this.subManager.push({
325
+ id: sub.id,
236
326
  uid: mid,
327
+ targetId: guildId,
237
328
  roomId: data.live_room.roomid.toString(),
238
329
  live: liveMsg,
239
330
  dynamic: dynamicMsg,
240
331
  liveDispose: null,
241
332
  dynamicDispose: null
242
333
  });
334
+ // 获取用户信息
335
+ let userData;
336
+ try {
337
+ const { data } = await ctx.biliAPI.getMasterInfo(sub.uid);
338
+ userData = data;
339
+ }
340
+ catch (e) {
341
+ return 'bili sub指令 getMasterInfo() 网络请求失败';
342
+ }
243
343
  // 需要订阅直播
244
- if (liveMsg)
245
- await session.execute(`bili live ${data.live_room.roomid}`);
344
+ if (liveMsg) {
345
+ await session.execute(`bili live ${data.live_room.roomid} ${guildId} -b ${platform}`);
346
+ // 发送订阅消息通知
347
+ await bot.sendMessage(sub.targetId, `订阅${userData.info.uname}直播通知`);
348
+ }
246
349
  // 需要订阅动态
247
- if (dynamicMsg)
248
- await session.execute(`bili dynamic ${mid}`);
249
- // 发送订阅成功通知
350
+ if (dynamicMsg) {
351
+ await session.execute(`bili dynamic ${mid} ${guildId} -b ${platform}`);
352
+ // 发送订阅消息通知
353
+ await bot.sendMessage(sub.targetId, `订阅${userData.info.uname}动态通知`);
354
+ }
250
355
  });
251
356
  ctx.command('bili')
252
- .subcommand('.dynamic <uid:string>')
357
+ .subcommand('.dynamic <uid:string> <guildId:string>')
358
+ .option('bot', '-b <type:string>')
253
359
  .usage('订阅用户动态推送')
254
360
  .example('bili dynamic 1')
255
- .action(async ({ session }, uid) => {
361
+ .action(async ({ session, options }, uid, guildId) => {
256
362
  this.logger.info('调用bili.dynamic指令');
257
363
  // 如果uid为空则返回
258
- if (!uid) {
259
- await session.send('用户uid不能为空');
260
- return;
261
- }
262
- // 定义订阅对象索引
263
- let index;
264
- // 定义要订阅的对象是否存在于订阅管理对象中
265
- let exist;
364
+ if (!uid)
365
+ return '用户uid不能为空';
366
+ if (!guildId)
367
+ return '目标群组或频道不能为空';
368
+ if (!options.bot)
369
+ return '非法调用';
266
370
  // 保存到订阅管理对象
267
- this.subManager.forEach((sub, i) => {
268
- if (sub.uid === uid) {
269
- exist = true;
270
- index = i;
271
- }
272
- });
371
+ const index = this.subManager.findIndex(sub => sub.uid === uid);
273
372
  // 不存在则直接返回
274
- if (!exist) {
373
+ if (index === -1) {
275
374
  session.send('请勿直接调用该指令');
276
375
  return;
277
376
  }
377
+ // 获取对应Bot
378
+ let bot;
379
+ switch (options.bot) {
380
+ case 'qq':
381
+ bot = this.qqBot;
382
+ break;
383
+ case 'qqguild':
384
+ bot = this.qqguildBot;
385
+ break;
386
+ default: return '非法调用';
387
+ }
278
388
  // 开始循环检测
279
- const dispose = ctx.setInterval(this.dynamicDetect(ctx, session, uid), 60000);
389
+ const dispose = ctx.setInterval(this.dynamicDetect(ctx, bot, guildId, uid), 60000);
280
390
  // 将销毁函数保存到订阅管理对象
281
391
  this.subManager[index].dynamicDispose = dispose;
282
392
  });
283
393
  ctx.command('bili')
284
- .subcommand('.live <roomId:string>')
394
+ .subcommand('.live <roomId:string> <guildId:string>')
395
+ .option('bot', '-b <type:string>')
285
396
  .usage('订阅主播开播通知')
286
397
  .example('bili live 732')
287
- .action(async ({ session }, roomId) => {
398
+ .action(async ({ options }, roomId, guildId) => {
288
399
  this.logger.info('调用bili.live指令');
289
400
  // 如果room_id为空则返回
290
- if (!roomId) {
291
- await session.send('订阅主播房间号不能为空');
292
- return;
293
- }
294
- // 定义订阅对象索引
295
- let index;
296
- // 定义要订阅的对象是否存在于订阅管理对象中
297
- let exist;
401
+ if (!roomId)
402
+ return '订阅主播房间号不能为空';
403
+ if (!guildId)
404
+ return '目标群组或频道不能为空';
405
+ if (!options.bot)
406
+ return '非法调用';
298
407
  // 保存到订阅管理对象
299
- this.subManager.forEach((sub, i) => {
300
- if (sub.roomId === roomId) {
301
- exist = true;
302
- index = i;
303
- }
304
- });
408
+ const index = this.subManager.findIndex(sub => sub.roomId === roomId);
305
409
  // 要订阅的对象不在订阅管理对象中,直接返回
306
- if (!exist) {
307
- await session.send('请勿直接调用该指令');
308
- return;
410
+ if (index === -1)
411
+ return '请勿直接调用该指令';
412
+ // 获取对应Bot
413
+ let bot;
414
+ switch (options.bot) {
415
+ case 'qq':
416
+ bot = this.qqBot;
417
+ break;
418
+ case 'qqguild':
419
+ bot = this.qqguildBot;
420
+ break;
421
+ default: return '非法调用';
309
422
  }
310
423
  // 开始循环检测
311
- const dispose = ctx.setInterval(this.liveDetect(ctx, session, roomId), 5000);
424
+ const dispose = ctx.setInterval(this.liveDetect(ctx, bot, guildId, roomId), 5000);
312
425
  // 保存销毁函数
313
426
  this.subManager[index].liveDispose = dispose;
314
427
  });
@@ -320,9 +433,22 @@ class ComRegister {
320
433
  this.logger.info('调用bili.status指令');
321
434
  if (!roomId)
322
435
  return session.send('请输入房间号!');
323
- const content = await ctx.biliAPI.getLiveRoomInfo(roomId);
436
+ let content;
437
+ try {
438
+ content = await ctx.biliAPI.getLiveRoomInfo(roomId);
439
+ }
440
+ catch (e) {
441
+ return 'bili status指令 getLiveRoomInfo() 本次网络请求失败';
442
+ }
324
443
  const { data } = content;
325
- const { data: userData } = await ctx.biliAPI.getMasterInfo(data.uid);
444
+ let userData;
445
+ try {
446
+ const { data: userInfo } = await ctx.biliAPI.getMasterInfo(data.uid);
447
+ userData = userInfo;
448
+ }
449
+ catch (e) {
450
+ return 'bili status指令 getMasterInfo() 网络请求失败';
451
+ }
326
452
  // B站出问题了
327
453
  if (content.code !== 0) {
328
454
  if (content.msg === '未找到该房间') {
@@ -340,16 +466,12 @@ class ComRegister {
340
466
  session.send(string);
341
467
  });
342
468
  }
343
- dynamicDetect(ctx, session, uid) {
469
+ dynamicDetect(ctx, bot, guildId, uid) {
344
470
  let firstSubscription = true;
345
471
  let timePoint;
346
472
  return async () => {
347
- // 第一次的判断
473
+ // 第一次订阅判断
348
474
  if (firstSubscription) {
349
- // 获取用户信息
350
- const { data: userData } = await ctx.biliAPI.getMasterInfo(uid);
351
- // 发送订阅消息通知
352
- session.send(`订阅${userData.info.uname}动态通知!`);
353
475
  // 设置第一次的时间点
354
476
  timePoint = Date.now();
355
477
  // 设置第一次为false
@@ -357,17 +479,26 @@ class ComRegister {
357
479
  return;
358
480
  }
359
481
  // 获取用户空间动态数据
360
- const content = await ctx.biliAPI.getUserSpaceDynamic(uid);
482
+ let content;
483
+ try {
484
+ content = await ctx.biliAPI.getUserSpaceDynamic(uid);
485
+ }
486
+ catch (e) {
487
+ return this.logger.error('dynamicDetect getUserSpaceDynamic() 网络请求失败');
488
+ }
361
489
  // 判断是否出现其他问题
362
490
  if (content.code !== 0) {
363
491
  switch (content.code) {
364
492
  case -101: { // 账号未登录
365
- return '账号未登录';
493
+ bot.sendMessage(guildId, '账号未登录,请登录后重新订阅动态');
366
494
  }
367
495
  default: { // 未知错误
368
- return '未知错误';
496
+ bot.sendMessage(guildId, '未知错误,请重新订阅动态');
369
497
  }
370
498
  }
499
+ // 取消订阅
500
+ this.unsubSingle(ctx, uid, 1); /* 1为取消动态订阅 */
501
+ return;
371
502
  }
372
503
  // 获取数据内容
373
504
  const items = content.data.items;
@@ -391,100 +522,126 @@ class ComRegister {
391
522
  }
392
523
  // 推送该条动态
393
524
  const [pic] = await ctx.gimg.generateDynamicImg(items[num]);
394
- session.send(pic);
525
+ await bot.sendMessage(guildId, pic);
395
526
  }
396
527
  }
397
528
  };
398
529
  }
399
- liveDetect(ctx, session, roomId) {
530
+ liveDetect(ctx, bot, guildId, roomId) {
400
531
  let firstSubscription = true;
401
532
  let timer = 0;
402
533
  let open = false;
403
534
  let liveTime;
404
535
  let uData;
536
+ // 相当于锁的作用,防止上一个循环没处理完
537
+ let flag = true;
405
538
  return async () => {
406
- // Test code
407
- /* console.log('===========================>');
408
- console.log(timer);
409
- console.log(open);
410
- console.log('===========================>'); */
411
- // 发送请求检测直播状态
412
- const content = await ctx.biliAPI.getLiveRoomInfo(roomId);
413
- const { data } = content;
414
- // B站出问题了
415
- if (content.code !== 0) {
416
- if (content.msg === '未找到该房间') {
417
- session.send('未找到该房间!');
539
+ try {
540
+ // 如果flag为false则说明前面的代码还未执行完,则直接返回
541
+ if (!flag)
542
+ return;
543
+ // 发送请求检测直播状态
544
+ let content;
545
+ try {
546
+ content = await ctx.biliAPI.getLiveRoomInfo(roomId);
418
547
  }
419
- else {
420
- session.send('未知错误,请呼叫管理员检查问题!');
548
+ catch (e) {
549
+ return this.logger.error('liveDetect getLiveRoomInfo 网络请求失败');
421
550
  }
422
- // dispose
423
- return;
424
- }
425
- if (firstSubscription) {
426
- firstSubscription = false;
427
- // 获取主播信息
428
- const { data: userData } = await ctx.biliAPI.getMasterInfo(data.uid);
429
- // 主播信息不会变,请求一次即可
430
- uData = userData;
431
- // 发送订阅消息通知
432
- session.send(`订阅${userData.info.uname}直播通知`);
433
- if (data.live_status === 1) { // 当前正在直播
434
- // 改变开播状态
435
- open = true;
436
- // 推送直播信息
437
- await session.send(await ctx
438
- .gimg
439
- .generateLiveImg(data, uData, LiveType.LiveBroadcast));
440
- } // 未开播,直接返回
441
- return;
442
- }
443
- // 检查直播状态
444
- switch (data.live_status) {
445
- case 0:
446
- case 2: { // 状态 0 和 2 说明未开播
447
- if (open) { // 之前开播,现在下播了
448
- // 更改直播状态
449
- open = false;
450
- // 下播了将定时器清零
451
- timer = 0;
452
- // 发送下播通知
453
- session.send(`${uData.info.uname}下播啦,本次直播了${ctx.gimg.getTimeDifference(liveTime)}`);
551
+ const { data } = content;
552
+ // B站出问题了
553
+ if (content.code !== 0) {
554
+ if (content.msg === '未找到该房间') {
555
+ await bot.sendMessage(guildId, '未找到该房间,请检查房间号后重新订阅');
454
556
  }
455
- // 未进循环,还未开播,继续循环
456
- break;
557
+ else {
558
+ await bot.sendMessage(guildId, '未知错误,请呼叫管理员检查问题后重新订阅');
559
+ }
560
+ // dispose
561
+ this.unsubSingle(ctx, roomId, 0); /* 0为取消Live订阅 */
562
+ return;
457
563
  }
458
- case 1: {
459
- if (!open) { // 之前未开播,现在开播了
460
- // 更改直播状态
564
+ if (firstSubscription) {
565
+ firstSubscription = false;
566
+ // 获取主播信息
567
+ let userData;
568
+ try {
569
+ const { data: userInfo } = await ctx.biliAPI.getMasterInfo(data.uid);
570
+ userData = userInfo;
571
+ }
572
+ catch (e) {
573
+ return this.logger.error('liveDetect first sub getMasterInfo() 网络请求错误');
574
+ }
575
+ // 主播信息不会变,请求一次即可
576
+ uData = userData;
577
+ // 判断直播状态
578
+ if (data.live_status === 1) { // 当前正在直播
579
+ // 推送直播信息
580
+ await bot.sendMessage(guildId, await ctx
581
+ .gimg
582
+ .generateLiveImg(data, uData, LiveType.LiveBroadcast));
583
+ // 改变开播状态
461
584
  open = true;
462
- // 设置开播时间
463
- liveTime = data.live_time;
464
- // 获取主播信息
465
- const { data: userData } = await ctx.biliAPI.getMasterInfo(data.uid);
466
- // 主播信息不会变,开播时刷新一次即可
467
- uData = userData;
468
- // 发送直播通知
469
- await session.send(await ctx.gimg.generateLiveImg(data, uData, LiveType.StartBroadcasting));
585
+ } // 未开播,直接返回
586
+ return;
587
+ }
588
+ // 检查直播状态
589
+ switch (data.live_status) {
590
+ case 0:
591
+ case 2: { // 状态 0 和 2 说明未开播
592
+ if (open) { // 之前开播,现在下播了
593
+ // 更改直播状态
594
+ open = false;
595
+ // 下播了将定时器清零
596
+ timer = 0;
597
+ // 发送下播通知
598
+ bot.sendMessage(guildId, `${uData.info.uname}下播啦,本次直播了${ctx.gimg.getTimeDifference(liveTime)}`);
599
+ }
600
+ // 未进循环,还未开播,继续循环
601
+ break;
470
602
  }
471
- else { // 还在直播
472
- if (this.config.pushTime > 0) {
473
- timer++;
474
- // 开始记录时间
475
- if (timer >= (12 * 30 * this.config.pushTime)) { // 到时间推送直播消息
476
- // 到时间重新计时
477
- timer = 0;
478
- // 发送状态信息
479
- session.send(await ctx
480
- .gimg
481
- .generateLiveImg(data, uData, LiveType.LiveBroadcast));
603
+ case 1: {
604
+ if (!open) { // 之前未开播,现在开播了
605
+ // 更改直播状态
606
+ open = true;
607
+ // 设置开播时间
608
+ liveTime = data.live_time;
609
+ // 获取主播信息
610
+ let userData;
611
+ try {
612
+ const { data: userInfo } = await ctx.biliAPI.getMasterInfo(data.uid);
613
+ userData = userInfo;
482
614
  }
615
+ catch (e) {
616
+ return this.logger.error('liveDetect open getMasterInfo() 网络请求错误');
617
+ }
618
+ // 主播信息不会变,开播时刷新一次即可
619
+ uData = userData;
620
+ // 发送直播通知
621
+ await bot.sendMessage(guildId, await ctx.gimg.generateLiveImg(data, uData, LiveType.StartBroadcasting));
622
+ }
623
+ else { // 还在直播
624
+ if (this.config.pushTime > 0) {
625
+ timer++;
626
+ // 开始记录时间
627
+ if (timer >= (12 * 30 * this.config.pushTime)) { // 到时间推送直播消息
628
+ // 到时间重新计时
629
+ timer = 0;
630
+ // 发送状态信息
631
+ bot.sendMessage(guildId, await ctx
632
+ .gimg
633
+ .generateLiveImg(data, uData, LiveType.LiveBroadcast));
634
+ }
635
+ }
636
+ // 否则继续循环
483
637
  }
484
- // 否则继续循环
485
638
  }
486
639
  }
487
640
  }
641
+ finally {
642
+ // 执行完方法体不论如何都把flag设置为true
643
+ flag = true;
644
+ }
488
645
  };
489
646
  }
490
647
  async checkIfNeedSub(comNeed, subType, session, data) {
@@ -521,10 +678,118 @@ class ComRegister {
521
678
  }
522
679
  }
523
680
  }
681
+ async getSubFromDatabase(ctx) {
682
+ // 从数据库中获取数据
683
+ const subData = await ctx.database.get('bilibili', { id: { $gt: 0 } });
684
+ // 设定订阅数量
685
+ this.num = subData.length;
686
+ // 如果订阅数量超过三个则被非法修改数据库
687
+ // 向管理员发送重新订阅通知
688
+ if (this.num > 3)
689
+ return;
690
+ // 定义Bot
691
+ let bot;
692
+ // 循环遍历
693
+ subData.forEach(sub => {
694
+ // 拿到对应bot
695
+ switch (sub.platform) {
696
+ case 'qq': bot = this.qqBot;
697
+ case 'qqguild': bot = this.qqguildBot;
698
+ }
699
+ // 构建订阅对象
700
+ let subManagerItem = {
701
+ id: sub.id,
702
+ uid: sub.uid,
703
+ roomId: sub.room_id,
704
+ targetId: sub.targetId,
705
+ live: +sub.live === 1 ? true : false,
706
+ dynamic: +sub.dynamic === 1 ? true : false,
707
+ liveDispose: null,
708
+ dynamicDispose: null
709
+ };
710
+ // 判断需要订阅的服务
711
+ if (sub.dynamic) { // 需要订阅动态
712
+ // 开始循环检测
713
+ const dispose = ctx.setInterval(this.dynamicDetect(ctx, bot, sub.targetId, sub.uid), this.config.dynamicLoopTime * 1000);
714
+ // 保存销毁函数
715
+ subManagerItem.dynamicDispose = dispose;
716
+ }
717
+ if (sub.live) { // 需要订阅动态
718
+ // 开始循环检测
719
+ const dispose = ctx.setInterval(this.liveDetect(ctx, bot, sub.targetId, sub.room_id), this.config.liveLoopTime * 1000);
720
+ // 保存销毁函数
721
+ subManagerItem.liveDispose = dispose;
722
+ }
723
+ // 保存新订阅对象
724
+ this.subManager.push(subManagerItem);
725
+ // 发送订阅成功通知
726
+ });
727
+ }
728
+ unsubSingle(ctx, id /* UID或RoomId */, type /* 0取消Live订阅,1取消Dynamic订阅 */) {
729
+ let index;
730
+ switch (type) {
731
+ case 0: { // 取消Live订阅
732
+ index = this.subManager.findIndex(sub => sub.roomId === id);
733
+ if (index === -1)
734
+ return '未订阅该用户,无需取消订阅';
735
+ // 取消订阅
736
+ this.subManager[index].live && this.subManager[index].liveDispose();
737
+ // 如果没有对这个UP的任何订阅,则移除
738
+ if (!this.subManager[index].dynamic) {
739
+ // 获取要删除行的id
740
+ const id = this.subManager[index].id;
741
+ // 从管理对象中移除
742
+ this.subManager = this.subManager.splice(index, index);
743
+ // 从数据库中删除
744
+ ctx.database.remove('bilibili', [id]);
745
+ // num--
746
+ this.num--;
747
+ return '已取消订阅该用户';
748
+ }
749
+ this.subManager[index].liveDispose = null;
750
+ this.subManager[index].live = false;
751
+ // 更新数据库
752
+ ctx.database.upsert('bilibili', [{
753
+ id: +`${this.subManager[index].id}`,
754
+ live: 0
755
+ }]);
756
+ return '已取消订阅Live';
757
+ }
758
+ case 1: { // 取消Dynamic订阅
759
+ index = this.subManager.findIndex(sub => sub.uid === id);
760
+ if (index === -1)
761
+ return '未订阅该用户,无需取消订阅';
762
+ // 取消订阅
763
+ this.subManager[index].dynamic && this.subManager[index].dynamicDispose();
764
+ // 如果没有对这个UP的任何订阅,则移除
765
+ if (!this.subManager[index].live) {
766
+ // 获取要删除行的id
767
+ const id = this.subManager[index].id;
768
+ // 从管理对象中移除
769
+ this.subManager = this.subManager.splice(index, index);
770
+ // 从数据库中删除
771
+ ctx.database.remove('bilibili', [id]);
772
+ // num--
773
+ this.num--;
774
+ return '已取消订阅该用户';
775
+ }
776
+ this.subManager[index].dynamicDispose = null;
777
+ this.subManager[index].dynamic = false;
778
+ // 更新数据库
779
+ ctx.database.upsert('bilibili', [{
780
+ id: +`${this.subManager[index].id}`,
781
+ dynamic: 0
782
+ }]);
783
+ return '已取消订阅Dynamic';
784
+ }
785
+ }
786
+ }
524
787
  }
525
788
  (function (ComRegister) {
526
789
  ComRegister.Config = koishi_1.Schema.object({
527
- pushTime: koishi_1.Schema.number().required()
790
+ pushTime: koishi_1.Schema.number().required(),
791
+ liveLoopTime: koishi_1.Schema.number().default(5),
792
+ dynamicLoopTime: koishi_1.Schema.number().default(60)
528
793
  });
529
794
  })(ComRegister || (ComRegister = {}));
530
795
  exports.default = ComRegister;
package/lib/database.d.ts CHANGED
@@ -12,6 +12,8 @@ export interface Bilibili {
12
12
  dynamic: number;
13
13
  video: number;
14
14
  live: number;
15
+ targetId: string;
16
+ platform: string;
15
17
  time: Date;
16
18
  }
17
19
  export interface LoginBili {
package/lib/database.js CHANGED
@@ -17,7 +17,9 @@ function apply(ctx) {
17
17
  dynamic: 'unsigned',
18
18
  video: 'unsigned',
19
19
  live: 'unsigned',
20
+ targetId: 'string',
21
+ platform: 'string',
20
22
  time: 'timestamp'
21
- });
23
+ }, { autoInc: true });
22
24
  }
23
25
  exports.apply = apply;
package/lib/index.js CHANGED
@@ -31,6 +31,7 @@ const koishi_1 = require("koishi");
31
31
  // import crypto
32
32
  const crypto_1 = __importDefault(require("crypto"));
33
33
  // import plugins
34
+ const authority_1 = __importDefault(require("./authority"));
34
35
  const comRegister_1 = __importDefault(require("./comRegister"));
35
36
  const Database = __importStar(require("./database"));
36
37
  // import Service
@@ -68,6 +69,7 @@ function apply(ctx, config) {
68
69
  ctx.plugin(generateImg_1.default, { cardColorStart: config.cardColorStart, cardColorEnd: config.cardColorEnd });
69
70
  ctx.plugin(biliAPI_1.default);
70
71
  // load plugin
72
+ ctx.plugin(authority_1.default);
71
73
  ctx.plugin(comRegister_1.default, { pushTime: config.pushTime });
72
74
  // 当用户输入“恶魔兔,启动!”时,执行 help 指令
73
75
  ctx.middleware((session, next) => {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-bilibili-notify",
3
3
  "description": "Koishi bilibili notify plugin",
4
- "version": "0.1.1",
4
+ "version": "0.1.3",
5
5
  "contributors": [
6
6
  "Akokko <admin@akokko.com>"
7
7
  ],