Compare commits

..
16 Commits
Author SHA1 Message Date
shanmite 8bc053b352 fix: 增加dyid长度校验 2021-07-27 23:34:10 +08:00
shanmite f5a8ad75d2 feat: 判断专栏是否已查看 2021-07-27 22:10:26 +08:00
shanmite cbce4b113d feat: 增加从专栏获取抽奖的功能 2021-07-27 21:48:12 +08:00
shanmite a63456bd29 pref: 调整结构 2021-07-27 14:51:59 +08:00
shanmite 329e6931dd 更新readme 2021-07-18 23:55:49 +08:00
shanmite 309371fbd7 pref: 重构部分代码,优化提示 2021-07-18 23:37:27 +08:00
shanmite 6f81360d2a fix: 多账号状态清零 2021-07-18 22:27:48 +08:00
shanmite 4e377f1c41 cli: 更改颜色 2021-07-18 17:35:33 +08:00
shanmite 79c550db14 fix: 滤除过期官方抽奖 2021-07-18 17:24:11 +08:00
shanmite 28c2af93cf fix: 开奖时间过滤失效 2021-07-18 16:52:54 +08:00
shanmite 11aec87eed fix: 循环运行 2021-07-18 12:45:49 +08:00
shanmite 2442d5c46d build: 支持arm 2021-07-18 10:53:10 +08:00
shanmite a21b0dd33e feat: 清理新增clear_white_list设置 2021-07-18 10:28:14 +08:00
shanmite ce3274c258 fix: 无uid时不判断粉丝数 2021-07-18 10:08:23 +08:00
shanmite 455c81ee55 doc: 更新readme 2021-07-17 20:17:06 +08:00
shanmite 18760ebaac perf: 重构代码
- 分离动态筛选部分的网络请求和数据处理
- 优化部分ifelse判断
feat:
- 新增NOT_GO_LOTTERY环境变量
- 边转边存dyid
- 滤除的dyid也进行存储
fix: 修复部分bug
2021-07-17 17:59:56 +08:00
19 changed files with 745 additions and 680 deletions
+13 -9
View File
@@ -15,6 +15,8 @@
- [中奖推送(可选)](#中奖推送可选)
- [设置说明](#设置说明)
[Github仓库链接](https://github.com/shanmiteko/LotteryAutoScript)
已实现功能:
> 点赞 评论 转发 @好友 带话题 随机动态 检测开奖 清理
@@ -68,16 +70,18 @@ Chrome浏览器:
### 本地运行
#### 可执行文件
1. [[下载](https://github.com/shanmiteko/LotteryAutoScript/releases)|[cnpmjs镜像下载](https://github.com.cnpmjs.org/shanmiteko/LotteryAutoScript/releases)|[Fastgit镜像下载](https://hub.fastgit.org/shanmiteko/LotteryAutoScript/releases)]压缩包并解压
1. [[下载](https://github.com/shanmiteko/LotteryAutoScript/releases)|[cnpmjs镜像下载](https://github.com.cnpmjs.org/shanmiteko/LotteryAutoScript/releases)|[Fastgit镜像下载](https://hub.fastgit.org/shanmiteko/LotteryAutoScript/releases)]压缩包并解压后有三个文件
```
env.js
lottery.exe
my_config.js
env.js 便捷设置环境变量和多账号参数
lottery.exe 可执行文件
my_config.js 自定义设置文件
```
2. `env.js`中填入`COOKIE`和推送参数
3. `my_config.js`中自定义设置
4. 在当前目录下打开终端运行可执行文件`lottery`
5. 运行截图
5. 输入`lottery start`启动抽奖|`lottery check`检测中奖|`lottery clear`清理动态
> 或者新建文本文档写入`lottery start`然后更改扩展名为.bat点击运行
6. 运行截图
![lottery_start](doc/pic/lottery_start.png)
#### 以源码方式运行
@@ -138,7 +142,9 @@ npm i && npm run clear
注: **本地运行时可在设置中增大扫描页数**
> [windows系统定时运行](./doc/win_schedule.md)
> ~~[windows系统定时运行](./doc/win_schedule.md)~~
脚本已内置定时运行功能
##### Linux
[linux系统配置与定时运行](./doc/linux_schedule.md)
@@ -187,9 +193,7 @@ rm -rf lottery/
----------------------------------------
## 防重复转发
脚本将转发过的动态都写入`dyids/dyid*.txt`文件中
完整转发一轮后才会进行写入操作, 勿过早关闭运行
脚本将转发过的动态和被过滤的动态都写入`dyids/dyid*.txt`文件中
----------------------------------------
+2 -1
View File
@@ -45,7 +45,8 @@ vim env.js
`"PAT"``"GITHUB_REPOSITORY"`不填也行
5.设置定时工作
~~5.设置定时工作~~
> [linux系统定时运行](https://zhuanlan.zhihu.com/p/58719487)
输入:
Binary file not shown.

Before

Width:  |  Height:  |  Size: 163 KiB

After

Width:  |  Height:  |  Size: 123 KiB

+5 -9
View File
@@ -1,18 +1,13 @@
/**
* 使用时请将此文件命名为env.js
* RELEASE内可执行文件包中已有env.js文件
* 注: 请打开扩展名显示
*/
/**
* ## 账号相关参数
* ## 账号相关
* - `COOKIE` 是必填项
* - `NUMBER` 表示是第几个账号
* - `CLEAR` 是否启用清理功能
* - `ENABLE_MULTIPLE_ACCOUNT` 是否启用多账号
* - `MULTIPLE_ACCOUNT_PARM` 多账号参数(JSON格式)
* ## 调试相关
* - `LOTTERY_LOG_LEVEL` 输出日志等级 Error<Warn<Info<Debug 1<2<3<4
*
* - `NOT_GO_LOTTERY` 关闭抽奖行为
* ## 多账号
* 1. 将 ENABLE_MULTIPLE_ACCOUNT 的值改为true
* 2. 将账号信息依次填写于 multiple_account_parm 中, 参考例子类推
@@ -26,7 +21,8 @@ const account_parm = {
CLEAR: true,
ENABLE_MULTIPLE_ACCOUNT: false,
MULTIPLE_ACCOUNT_PARM: "",
LOTTERY_LOG_LEVEL: 3
LOTTERY_LOG_LEVEL: 3,
NOT_GO_LOTTERY: ""
}
/**
+65 -7
View File
@@ -1,5 +1,5 @@
const Ajax = require('./Ajax');
const { strToJson, log } = require('./Base');
const { strToJson, log } = require('./Util');
const GlobalVar = require('./GlobalVar');
/**
@@ -74,7 +74,6 @@ const BiliAPI = {
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.bilibili.com/x/msgfeed/unread',
hasCookies: true,
success: responseText => {
let res = strToJson(responseText);
if (res.code === 0) {
@@ -148,7 +147,6 @@ const BiliAPI = {
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.vc.bilibili.com/session_svr/v1/session_svr/single_unread',
hasCookies: true,
success: responseText => {
let res = strToJson(responseText);
if (res.code === 0) {
@@ -213,6 +211,24 @@ const BiliAPI = {
});
});
},
/**
* 获取一个动态的细节
* @param {string} dyid
* @return {Promise<string>}
*/
getOneDynamicByDyid(dyid) {
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/get_dynamic_detail',
queryStringsObj: {
dynamic_id: dyid
},
success: responseText => {
resolve(responseText)
}
})
});
},
/**
* 获取一组动态的信息
* @param {number} UID
@@ -254,7 +270,6 @@ const BiliAPI = {
queryStringsObj: {
tag_name: tagename
},
hasCookies: false,
success: responseText => {
const res = strToJson(responseText);
if (res.code !== 0) {
@@ -306,6 +321,49 @@ const BiliAPI = {
});
});
},
/**
* 搜索专栏
* @param {string} keyword
* @return {Promise<Array<number>>}
*/
searchArticlesByKeyword(keyword) {
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.bilibili.com/x/web-interface/search/type',
queryStringsObj: {
keyword,
page: 1,
order: 'pubdate',
search_type: 'article'
},
success: responseText => {
const res = JSON.parse(responseText);
if (res.code === 0) {
log.info('搜索专栏', '成功 关键词: ' + keyword)
resolve(res.data.result.map(it => it.id))
} else {
log.error('搜索专栏', '失败 原因:\n' + responseText)
resolve([])
}
}
})
});
},
/**
* 获取专栏内容
* @param {number} cv
* @returns {Promise<string>}
*/
getOneArticleByCv(cv) {
return new Promise((resolve) => {
Ajax.get({
url: `https://www.bilibili.com/read/cv${cv}`,
success: responseText => {
resolve(responseText)
}
})
});
},
/**
* 获取粉丝数
* @param {number} uid
@@ -334,8 +392,8 @@ const BiliAPI = {
success: responseText => {
const res = strToJson(responseText);
if (res.code === 0) {
resolve(res.data.follower);
log.info('获取粉丝数', 'ok');
resolve(res.data.follower);
} else {
log.error('获取粉丝数', `出错 可能是访问过频繁\n${responseText}`);
resolve(-1);
@@ -365,7 +423,6 @@ const BiliAPI = {
queryStringsObj: {
dynamic_id: dyid
},
hasCookies: false,
success: responseText => {
const res = strToJson(responseText);
/(?<=_prize_cmt":").*(?=")/.exec();
@@ -389,7 +446,7 @@ const BiliAPI = {
isMe: isMe
});
} else {
log.info('获取开奖信息', `失败\n${responseText}`);
log.error('获取开奖信息', `失败\n${responseText}`);
resolve({
ts: -1,
text: '获取开奖信息失败',
@@ -822,4 +879,5 @@ const BiliAPI = {
}
};
module.exports = BiliAPI;
-156
View File
@@ -1,156 +0,0 @@
const { createReadStream, createWriteStream } = require('fs')
const unzip = require('unzipper');
const { strToJson, tooltip } = require("./Base")
const { HttpRequest } = require("./HttpRequest")
const { GITHUB_REPOSITORY } = process.env;
const GihubAPI = {
/**
* 列出第一个构件
* @returns {Promise<{id: number, size_in_bytes: number}>}
*/
listArtifacts() {
return new Promise((resolve) => {
HttpRequest({
method: 'GET',
url: `https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/artifacts`,
config: {
retry: false
},
query: {
page: 1,
per_page: 5
},
headers: {
Accept: 'application/json, text/plain, */*',
},
success: res => {
const data = strToJson(res.body);
if (data.total_count) {
resolve(data.artifacts[0])
} else {
resolve({})
tooltip.log('之前无构件');
}
},
failure: err => {
tooltip.log(err);
resolve({})
}
})
});
},
/**
* 下载构件
* @param {number} id
* @returns {Promise<boolean>} success: true
*/
downloadArtifacts(id) {
return new Promise((resolve) => {
HttpRequest({
method: 'GET',
url: `https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/artifacts/${id}/zip`,
headers: {
accept: 'application/vnd.github.v3+json',
authorization: `token ${process.env.PAT}`
},
config: {
redirect: true,
},
stream: true,
success: res => {
let recv_length = 0;
const wtbs = createWriteStream('dyid.zip');
res.resStream.on('data', chuck => {
recv_length += chuck.length
tooltip.log(`已收到:${recv_length} Bytes`)
})
res.resStream.pipe(wtbs)
wtbs.on('finish', () => {
tooltip.log('下载完成开始解压')
createReadStream('dyid.zip').pipe(unzip.Extract({
path: 'lib',
}).on('close', () => {
tooltip.log('解压完成')
resolve(true)
}))
}).on('error', () => {
wtbs.destroy()
resolve(false)
})
},
failure: err => {
tooltip.log(err);
resolve(false)
}
})
});
},
/**
* 检查是否正在抽奖或取关
* @returns {Promise<boolean>}
*/
hasLotteryRun() {
return new Promise((resolve) => {
HttpRequest({
method: 'GET',
url: `https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/runs`,
query: {
status: "in_progress"
},
headers: {
accept: 'application/vnd.github.v3+json',
},
success: res => {
const { workflow_runs } = strToJson(res.body);
if (workflow_runs instanceof Array) {
workflow_runs.filter(wr => /sweepstakes|clear/.test(wr.name)).length > 1 ?
resolve(true) : resolve(false)
} else {
resolve(true)
}
},
failure: err => {
tooltip.log(err);
resolve(true)
}
})
});
},
/**
* 触发一个workflow
* @param {string} yaml_file
*/
trigger(yaml_file) {
return new Promise((resolve) => {
HttpRequest({
method: 'POST',
url: `https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/workflows/${yaml_file}/dispatches`,
contents: {
ref: 'main'
},
headers: {
accept: 'application/vnd.github.v3+json',
'content-type': 'application/json',
authorization: `token ${process.env.PAT}`
},
success: res => {
if (res.body === '') {
tooltip.log('成功触发'+yaml_file);
} else {
tooltip.log(`触发${yaml_file}失败 响应:\n${res.body}`);
}
resolve()
},
failure: err => {
tooltip.log(err);
resolve()
}
})
});
}
}
module.exports = GihubAPI;
+241 -167
View File
@@ -1,4 +1,4 @@
const Base = require('./Base');
const Util = require('./Util');
const BiliAPI = require('./BiliAPI');
const { sendNotify } = require('./sendNotify');
const eventBus = require('./eventBus');
@@ -6,7 +6,7 @@ const Public = require('./Public');
const GlobalVar = require("./GlobalVar");
const config = require("./config");
const MyStorage = require('./MyStorage');
const { log } = Base;
const { log, hasEnv } = Util;
/**
* 监视器
@@ -14,13 +14,18 @@ const { log } = Base;
class Monitor extends Public {
/**
* @constructor
* @param {number | string} param
* @param {[string, number | string]} lottery_param
*/
constructor(param) {
constructor(lottery_param) {
super();
typeof param === 'number' ? this.UID = param : this.tag_name = param;
this.lottery_param = lottery_param
this.tagid = config.partition_id; /* tagid初始化 */
this.attentionList = ''; /* 转为字符串的所有关注的up主uid */
this.LotteryInfoMap = new Map([
['UIDs', this.getLotteryInfoByUID.bind(this)],
['TAGs', this.getLotteryInfoByTag.bind(this)],
['Articles', this.getLotteryInfoByArticle.bind(this)],
]);
}
/**
* 初始化
@@ -37,32 +42,9 @@ class Monitor extends Public {
return
}
}
this.attentionList = await BiliAPI.getAttentionList(GlobalVar.get("myUID")); /* 获取关注列表 */
await this.startLottery();
}
/**
* 启动
* @returns {Promise<boolean>}
*/
async startLottery() {
const allLottery = await this.filterLotteryInfo();
let status = 1;
if (allLottery instanceof Array) {
if (allLottery.length) {
let dyids = [];
for (const Lottery of allLottery) {
status = await this.go(Lottery);
if (status % 2) break
dyids.push(Lottery.dyid);
}
if (dyids.length) MyStorage.updateDyid(dyids.toString())
log.info('抽奖', '开始转发下一组动态');
} else {
status = 0;
log.info('抽奖', '无未转发抽奖');
}
}
switch (status) {
/** 关注列表初始化 */
this.attentionList = await BiliAPI.getAttentionList(GlobalVar.get("myUID"));
switch (await this.startLottery()) {
case 0:
eventBus.emit('Turn_on_the_Monitor')
break;
@@ -85,155 +67,243 @@ class Monitor extends Public {
case 41:
eventBus.emit('Turn_off_the_Monitor', '转发失败')
break
case 51:
eventBus.emit('Turn_off_the_Monitor', '获取开奖时间失败')
break
case 61:
eventBus.emit('Turn_off_the_Monitor', '获取关注数失败')
break
default:
eventBus.emit('Turn_off_the_Monitor', '出错 allLottery: ' + allLottery)
eventBus.emit('Turn_off_the_Monitor', '未知错误')
break;
}
}
/**
* 启动
* @returns {Promise<number>}
*/
async startLottery() {
const allLottery = await this.filterLotteryInfo()
, len = allLottery.length;
log.info('筛选动态', `筛选完毕(${len})`);
if (len) {
for (const Lottery of allLottery) {
let status = 0;
if (Lottery.isOfficialLottery) {
let { ts } = await BiliAPI.getLotteryNotice(Lottery.dyid);
const ts_10 = Date.now() / 1000;
if (ts < 0) {
return 51
}
if (ts < ts_10) {
log.info('过滤', '已过开奖时间')
MyStorage.updateDyid(Lottery.dyid)
continue
}
if (ts > ts_10 + config.maxday * 86400) {
log.info('过滤', '超过指定开奖时间')
MyStorage.updateDyid(Lottery.dyid)
continue
}
} else if (Lottery.uid[0]) {
const followerNum = await BiliAPI.getUserInfo(Lottery.uid[0]);
if (followerNum < 0) {
return 61
}
if (followerNum < config.minfollower) {
log.info('过滤', `粉丝数(${followerNum})小于指定数量`)
MyStorage.updateDyid(Lottery.dyid)
continue
}
}
status = await this.go(Lottery)
if (status % 2 !== 0) {
return status
}
MyStorage.updateDyid(Lottery.dyid);
await Util.delay(config.wait * (Math.random() + 0.5));
}
log.info('抽奖', '开始转发下一组动态');
return 0
} else {
log.info('抽奖', '无未转发抽奖');
return 0
}
}
/**
* 抽奖配置
* @typedef {object} LotteryOptions
* @property {number[]} uid 用户标识
* @property {string} dyid 动态标识
* @property {number} type 动态类型
* @property {string} relay_chat 动态类型
* @property {boolean} isOfficialLottery 是否官方抽奖
* @property {string} relay_chat 转发词
* @property {string} ctrl 定位@
* @property {string} rid 评论类型
* @property {string} rid 评论标识
* @property {number} chat_type 评论类型
*/
/**
* @returns {Promise<LotteryOptions[] | null>}
* @returns {Promise<LotteryOptions[]>}
*/
async filterLotteryInfo() {
const self = this,
protoLotteryInfo = typeof self.UID === 'number'
? await self.getLotteryInfoByUID(self.UID)
: await self.getLotteryInfoByTag(self.tag_name);
const { lottery_param, LotteryInfoMap, attentionList } = this;
let protoLotteryInfo = await LotteryInfoMap.get(lottery_param[0])(lottery_param[1]);
if (protoLotteryInfo === null)
return [];
log.info('筛选动态', `开始筛选(${protoLotteryInfo.length})`);
log.debug('未进行筛选的动态信息', protoLotteryInfo);
/** 所有抽奖信息 */
let alllotteryinfo = [];
const { key_words, model, chatmodel, is_imitator, maxday: _maxday, minfollower, skip_official_verify, only_followed, at_users, blockword, blacklist } = config;
const maxday = _maxday * 86400
let dyids_set = new Set();
log.info('筛选动态', '正在筛选');
for (const info of protoLotteryInfo) {
const { lottery_info_type, uids, uname, dyid, official_verify, ctrl, befilter, rid, des, type, hasOfficialLottery } = info;
const { key_words, model, chatmodel, is_imitator, only_followed, at_users, blockword, blacklist } = config;
/**Map<String, Boolean> */
let dyids_map = new Map();
/**dyid去重 */
if (dyids_set.has(dyid)) continue;
dyids_set.add(dyid);
/**判断是转发源动态还是现动态 */
const uid = lottery_info_type === 'tag' ? uids[0] : uids[1];
const now_ts_10 = Date.now() / 1000;
let onelotteryinfo = {};
let isLottery = false;
let isSendChat = false;
let isBlock = false;
let ts = 0;
const description = typeof des === 'string' ? des : '';
for (let index = 0; index < blockword.length; index++) {
const word = blockword[index];
const reg = new RegExp(word);
isBlock = reg.test(description) ? true : false;
if (isBlock) break;
/**去重 */
protoLotteryInfo = protoLotteryInfo.filter(({ dyid }) => {
if (dyids_map.has(dyid)) {
return false
}
if (isBlock) continue;
const needAt = /(?:@|艾特)[^@|(艾特)]*?好友/.test(description);
const needTopic = (/(?<=[带加上](?:话题|tag))#.*#/i.exec(description) || [])[0];
const isTwoLevelRelay = /\/\/@/.test(description);
dyids_map.set(dyid, false);
return true
});
/**是否包含关键词 */
const has_key_words = key_words.map(it => new RegExp(it)).every(it => it.test(description))
/**并发查询dyid */
await Promise.all(
[...dyids_map.keys()]
.map(it => MyStorage
.searchDyid(it)
.then(hasIt => dyids_map.set(it, hasIt))
)
)
/* 检查动态是否满足要求 */
await Util.try_for_each(protoLotteryInfo, async function ({
lottery_info_type, uids,
uname, dyid,
ctrl, rid, des, type,
hasOfficialLottery
}) {
/* 遇到转发过就退出 */
if (dyids_map.get(dyid)) return false;
const
/**判断是转发源动态还是现动态 */
uid = lottery_info_type === ('tag' || 'article') ? uids[0] : uids[1]
, isFollowed = (new RegExp(uid)).test(attentionList)
, description = typeof des === 'string' ? des : ''
, needAt = /(?:@|艾特)[^@|(艾特)]*?好友/.test(description)
, needTopic = (/(?<=[带加上](?:话题|tag))#.*#/i.exec(description) || [])[0]
, isRelayDynamic = type === 1
, isTwoLevelDynamic = /\/\/@/.test(description)
, has_key_words = key_words.every(it => new RegExp(it).test(description))
, isBlock = new RegExp(blockword.join('|')).test(description)
, isLottery =
(is_imitator && lottery_info_type === 'uid' && model !== '00')
|| (hasOfficialLottery && model[0] === '1')
|| (!hasOfficialLottery && model[1] === '1' && !isTwoLevelDynamic && has_key_words)
, isSendChat =
(is_imitator && lottery_info_type === 'uid' && chatmodel !== '00')
|| (hasOfficialLottery && chatmodel[0] === '1')
|| (!hasOfficialLottery && chatmodel[1] === '1');
/**屏蔽词 */
if (isBlock) return false;
/**若勾选只转已关注 */
if (only_followed && !isFollowed) return false;
/* 获取黑名单并去重合并 */
const { blacklist: remote_blacklist } = GlobalVar.get("remoteconfig")
, new_blacklist = remote_blacklist
? [...new Set([...blacklist.split(','), ...remote_blacklist.split(',')])].join()
: blacklist;
if ((new RegExp(dyid + '|' + uid)).test(new_blacklist)) return false;
if (lottery_info_type === 'uid' && is_imitator) {
isLottery = true;
isSendChat = chatmodel[1] === '1' || chatmodel[1] === '1';
} else if (hasOfficialLottery && model[0] === '1') {
({ ts } = await BiliAPI.getLotteryNotice(dyid));
if (ts < 0) { alllotteryinfo = null; break }
isLottery = ts > now_ts_10 && ts < now_ts_10 + maxday;
isSendChat = chatmodel[0] === '1';
} else if (!hasOfficialLottery && model[1] === '1' && has_key_words && !isTwoLevelRelay) {
({ ts } = Base.getLotteryNotice(description));
if (official_verify && skip_official_verify) {
isLottery = ts === 0 || (ts > now_ts_10 && ts < now_ts_10 + maxday);
} else {
const followerNum = await BiliAPI.getUserInfo(uid);
if (followerNum < 0) { alllotteryinfo = null; break }
if (followerNum < minfollower) continue;
isLottery = !befilter && (ts === 0 || (ts > now_ts_10 && ts < now_ts_10 + maxday));
}
isSendChat = chatmodel[1] === '1';
}
if (isLottery) {
/* 判断是否关注过 */
const isFollowed = (new RegExp(uid)).test(self.attentionList);
if (only_followed && !isFollowed) continue;
/* 判断是否转发过 */
const isRelayed = await MyStorage.searchDyid(dyid);
/* 获取黑名单并去重合并 */
const { blacklist: remote_blacklist } = GlobalVar.get("remoteconfig");
const new_blacklist = remote_blacklist ?
Array.from(new Set([...blacklist.split(','), ...remote_blacklist.split(',')])).toString() : blacklist;
/* 进行判断 */
if ((new RegExp(dyid + '|' + uid)).test(new_blacklist)) continue;
onelotteryinfo.uid = [] /**初始化待关注列表 */
if (!isFollowed) onelotteryinfo.uid.push(uid);
if (!isRelayed) {
onelotteryinfo.dyid = dyid;
let RandomStr = Base.getRandomOne(config.relay);
let new_ctrl = [];
if (needTopic) {
RandomStr += needTopic
}
if (needAt) {
at_users.forEach(it => {
new_ctrl.push({
data: String(it[1]),
location: RandomStr.length,
length: it[0].length + 1,
type: 1
})
RandomStr += '@' + it[0]
})
}
if (type === 1) {
/* 转发内容长度+'//'+'@'+用户名+':'+源内容 */
const addlength = RandomStr.length + 2 + uname.length + 1 + 1;
onelotteryinfo.relay_chat = RandomStr + `//@${uname}:` + des;
let onelotteryinfo = {};
onelotteryinfo.isOfficialLottery = hasOfficialLottery;
/**初始化待关注列表 */
onelotteryinfo.uid = []
if (!isFollowed) {
onelotteryinfo.uid.push(uid);
}
onelotteryinfo.dyid = dyid;
let
/**转发评语 */
RandomStr = Util.getRandomOne(config.relay),
/**控制字段 */
new_ctrl = [];
/* 是否需要带话题 */
if (needTopic) {
RandomStr += needTopic
}
/* 是否需要@ */
if (needAt) {
at_users.forEach(it => {
new_ctrl.push({
data: String(uid),
location: RandomStr.length + 2,
length: uname.length + 1,
data: String(it[1]),
location: RandomStr.length,
length: it[0].length + 1,
type: 1
})
ctrl.map(item => {
item.location += addlength;
return item;
}).forEach(it => new_ctrl.push(it))
if (!(new RegExp(uids[1])).test(self.attentionList))
onelotteryinfo.uid.push(uids[1]);
} else {
onelotteryinfo.relay_chat = RandomStr;
}
onelotteryinfo.ctrl = JSON.stringify(new_ctrl);
RandomStr += '@' + it[0]
})
}
/* 是否是转发的动态 */
if (isRelayDynamic) {
/* 转发内容长度+'//'+'@'+用户名+':'+源内容 */
const addlength = RandomStr.length + 2 + uname.length + 1 + 1;
onelotteryinfo.relay_chat = RandomStr + `//@${uname}:` + des;
new_ctrl.push({
data: String(uid),
location: RandomStr.length + 2,
length: uname.length + 1,
type: 1
})
ctrl.map(item => {
item.location += addlength;
return item;
}).forEach(it => new_ctrl.push(it))
if (!(new RegExp(uids[1])).test(attentionList))
onelotteryinfo.uid.push(uids[1]);
} else {
onelotteryinfo.relay_chat = RandomStr;
}
onelotteryinfo.ctrl = JSON.stringify(new_ctrl);
/* 根据动态的类型决定评论的类型 */
onelotteryinfo.type = type === 2 ?
11 : type === 4 || type === 1 ?
17 : type === 8 ?
1 : 0;
onelotteryinfo.chat_type =
type === 2
? 11
: type === 4 || type === 1
? 17
: type === 8
? 1
: 0;
/* 是否评论 */
if (isSendChat) onelotteryinfo.rid = rid;
if (onelotteryinfo.dyid) alllotteryinfo.push(onelotteryinfo);
alllotteryinfo.push(onelotteryinfo);
}
}
})
return alllotteryinfo;
}
/**
@@ -249,34 +319,40 @@ class Monitor extends Public {
*/
async go(option) {
log.debug('正在转发的动态信息', option);
let status = 1;
const { uid, dyid, type, rid, relay_chat, ctrl } = option;
if (hasEnv('NOT_GO_LOTTERY')) {
log.info('NOT_GO_LOTTERY', 'ON');
return 0
}
const { uid, dyid, chat_type, rid, relay_chat, ctrl } = option;
/* 评论 */
if (typeof rid === 'string' && type !== 0) {
const send = () => BiliAPI.sendChat(rid, Base.getRandomOne(config.chat) || relay_chat, type);
if (rid && chat_type) {
let status = 0;
const max_retry_times = 5;
for (let times = 0; times < max_retry_times && status; times++) {
status = await send();
if (status) {
log.info('自动评论', `将在 ${times + 1} 分钟后再次发送评论(${times + 1}/${max_retry_times})`)
await Base.delay(60 * 1000 * (times + 1))
for (let times = 0; times < max_retry_times; times++) {
status = await BiliAPI.sendChat(rid, Util.getRandomOne(config.chat), chat_type)
if (!status) {
break
}
log.info('自动评论', `将在 ${times + 1} 分钟后再次发送评论(${times + 1}/${max_retry_times})`)
await Util.delay(60 * 1000 * (times + 1))
}
if (status) return 11;
}
/* 关注 */
if (uid.length) {
status = 0
for (let index = 0; index < uid.length && !status; index++) {
const one_uid = uid[index];
if (typeof one_uid === 'number') {
status = await BiliAPI.autoAttention(uid);
await Base.delay(5000);
if (!status) await BiliAPI.movePartition(uid, this.tagid);
}
}
const [u1, u2] = uid
if (u1) {
let status = await BiliAPI.autoAttention(u1)
if (status) return 20 + status;
status = await BiliAPI.movePartition(u1, this.tagid)
if (status) return 20 + status;
if (u2) {
Util.delay(5000)
status = await BiliAPI.autoAttention(u2)
if (status) return 20 + status;
status = await BiliAPI.movePartition(u2, this.tagid)
if (status) return 20 + status;
}
}
/* 点赞 */
@@ -285,11 +361,9 @@ class Monitor extends Public {
/* 转发 */
if (await BiliAPI.autoRelay(GlobalVar.get("myUID"), dyid, relay_chat, ctrl)) return 41;
/* 延时 */
await Base.delay(config.wait * (Math.random() + 0.5));
return 0
}
}
module.exports = Monitor;
+9 -5
View File
@@ -1,5 +1,5 @@
const Base = require("./Base");
const { log } = Base;
const Util = require("./Util");
const { log } = Util;
const MyStorage = {
/**
@@ -10,7 +10,7 @@ const MyStorage = {
searchDyid: (dyid) => {
return new Promise((resolve) => {
const Rdyid = new RegExp(dyid);
const rs = Base.readDyidFile(Number(process.env.NUMBER));
const rs = Util.readDyidFile(Number(process.env.NUMBER));
let status = false;
rs.on('data', chunk => {
if (Rdyid.test(chunk)) {
@@ -31,9 +31,12 @@ const MyStorage = {
* @param {string} dyid
*/
updateDyid: (dyid) => {
log.info('更新dyid', '写入已转发过的动态信息');
log.info('更新dyid', `写入${dyid}`);
if (dyid.length !== Util.dyid_length) {
log.error('更新dyid', `dyid(${dyid})长度不为18 若出现此问题请即时通知开发者`)
}
return new Promise((resolve) => {
const ws = Base.writeDyidFile(Number(process.env.NUMBER));
const ws = Util.writeDyidFile(Number(process.env.NUMBER));
ws.write(dyid + ',', () => {
ws.destroy();
resolve()
@@ -46,4 +49,5 @@ const MyStorage = {
}
}
module.exports = MyStorage;
+299 -211
View File
@@ -1,199 +1,239 @@
const Base = require('./Base');
const Util = require('./Util');
const BiliAPI = require('./BiliAPI');
const config = require("./config");
const { log } = Base
const MyStorage = require('./MyStorage');
const { log } = Util
/**
* 解析dynamic_detail_card
* 提取出的有用动态信息
* @typedef {object} UsefulDynamicInfo
* @property {number} uid
* @property {string} uname
* @property {number} createtime 10
* @property {string} rid_str
* @property {string} dynamic_id
* @property {number} type
* @property {string} description
* @property {boolean} hasOfficialLottery
* @property {Array<Object.<string,string|number>>} ctrl
*
* @property {number} origin_uid
* @property {string} origin_uname
* @property {string} origin_rid_str
* @property {string} origin_dynamic_id
* @property {number} orig_type
* @property {string} origin_description
* @property {boolean} origin_hasOfficialLottery
*
* @param {object} dynamic_detail_card
* @return {UsefulDynamicInfo}
*/
function parseDynamicCard(dynamic_detail_card) {
const { strToJson } = Util;
/**临时储存单个动态中的信息 */
let obj = {};
const { desc, card, extension, extend_json } = dynamic_detail_card
, { info } = desc.user_profile
, cardToJson = strToJson(card)
, { item } = cardToJson;
/* 转发者的UID */
obj.uid = info.uid;
/* 转发者的name */
obj.uname = info.uname;
/* 动态的ts10 */
obj.createtime = desc.timestamp
/* 动态类型 */
obj.type = desc.type
/* 用于发送评论 */
obj.rid_str = desc.rid_str.length > 12 ? desc.dynamic_id_str : desc.rid_str;
/* 源动态类型 */
obj.orig_type = desc.orig_type
/* 转发者的动态ID !!!!此为大数需使用字符串值,不然JSON.parse()会有丢失精度 */
obj.dynamic_id = desc.dynamic_id_str;
/* 定位@信息 */
obj.ctrl = (extend_json && strToJson(extend_json).ctrl) || [];
/* 是否有官方抽奖 */
obj.hasOfficialLottery = extension && extension.lott && true;
/* 转发者的描述 后两个分别是视频动态的描述和视频本身的描述*/
obj.description = (item && (item.content || item.description || cardToJson.dynamic || cardToJson.desc)) || '';
if (obj.type === 1) {
const { origin_extension, origin } = cardToJson
, originToJson = strToJson(origin)
, { user, item } = originToJson;
/* 被转发者的UID */
obj.origin_uid = desc.origin.uid;
/* 被转发者的rid(用于发评论) */
obj.origin_rid_str = desc.origin.rid_str.length > 12 ? desc.origin.dynamic_id_str : desc.origin.rid_str;
/* 被转发者的动态的ID !!!!此为大数需使用字符串值,不然JSON.parse()会有丢失精度 */
obj.origin_dynamic_id = desc.orig_dy_id_str;
/* 是否有官方抽奖 */
obj.origin_hasOfficialLottery = origin_extension && origin_extension.lott;
/* 被转发者的name */
obj.origin_uname = (user && (user.name || user.uname)) || '';
/* 被转发者的描述 */
obj.origin_description = (item && (item.content || item.description || originToJson.dynamic || originToJson.desc)) || '';
}
return obj
}
/**
* 处理来自个人动态或话题页面的一组动态数据
* @param {String} res
* @returns {{modifyDynamicResArray: UsefulDynamicInfo[], nextinfo: {has_more: number, next_offset: string}} | UsefulDynamicInfo |null}
*/
function modifyDynamicRes(res) {
const
strToJson = Util.strToJson
, { data, code } = strToJson(res)
, { cards = [], has_more, offset } = data;
if (code !== 0) {
log.error('处理动态数据', '获取动态数据出错,可能是访问太频繁 \n' + res);
return null;
}
if (!cards.length) {
log.warn('处理动态数据', '未找到任何动态信息')
}
const
/**
* 字符串offset防止损失精度
*/
next = {
has_more,
next_offset: typeof offset === 'string'
? offset
: /(?<=next_offset":)[0-9]+/.exec(res)[0]
},
/**
* 储存获取到的一组动态中的信息
*/
array = next.has_more === 0
? []
: cards.map(onecard => parseDynamicCard(onecard))
log.info('处理动态数据', `动态数据读取完毕(${cards.length})(${next.has_more})`);
return {
modifyDynamicResArray: array,
nextinfo: next
}
}
/**
* 基础功能
*/
class Public {
constructor() { }
/**
* 提取出的有用动态信息
* @typedef {object} UsefulDynamicInfo
* @property {number} uid
* @property {string} uname
* @property {boolean} official_verify
* @property {number} createtime 10
* @property {string} rid_str
* @property {string} dynamic_id
* @property {number} type
* @property {string} description
* @property {boolean} hasOfficialLottery
* @property {Array<Object.<string,string|number>>} ctrl
*
* @property {number} origin_uid
* @property {string} origin_uname
* @property {boolean} origin_official_verify
* @property {string} origin_rid_str
* @property {string} origin_dynamic_id
* @property {number} orig_type
* @property {string} origin_description
* @property {boolean} origin_hasOfficialLottery
*/
/**
* 检查所有的动态信息
* @param {string} UID 指定的用户UID
* @param {number} pages 读取页数
* @param {number} time 时延
* @param {string} [_offset] 默认'0'
* @returns {Promise<{allModifyDynamicResArray: UsefulDynamicInfo[];offset: string}>} 获取前 `pages*12` 个动态信息
*/
async checkAllDynamic(hostuid, pages, time = 0, _offset = '0') {
log.info('检查所有动态', `准备读取${pages}页动态`);
const mDR = this.modifyDynamicRes,
getOneDynamicInfoByUID = BiliAPI.getOneDynamicInfoByUID,
curriedGetOneDynamicInfoByUID = Base.curryify(getOneDynamicInfoByUID); /* 柯里化的请求函数 */
/**
* 储存了特定UID的请求函数
*/
let hadUidGetOneDynamicInfoByUID = curriedGetOneDynamicInfoByUID(hostuid);
/**
* 储存所有经过整理后信息
* [{}{}...{}]
*/
let allModifyDynamicResArray = [];
let offset = _offset;
for (let i = 0; i < pages; i++) {
log.info('检查所有动态', `正在读取其中第${i + 1}页动态`);
let OneDynamicInfo = await hadUidGetOneDynamicInfoByUID(offset);
const mDRdata = mDR(OneDynamicInfo);
if (mDRdata === null) {
break;
}
/**
* 储存一片动态信息
* [{}{}...{}]
*/
const mDRArry = mDRdata.modifyDynamicResArray,
nextinfo = mDRdata.nextinfo;
if (nextinfo.has_more === 0) {
offset = nextinfo.next_offset;
log.info('检查所有动态', `成功读取${i + 1}页信息(已经是最后一页了故无法读取更多)`);
break;
} else {
allModifyDynamicResArray.push.apply(allModifyDynamicResArray, mDRArry);
i + 1 < pages
? log.info('检查所有动态', `开始读取第${i + 2}页动态信息`)
: log.info('检查所有动态', `${pages}页信息全部成功读取完成`);
offset = nextinfo.next_offset;
}
await Base.delay(time);
}
return ({ allModifyDynamicResArray, offset });
}
/**
* 互动抽奖
* 处理来自动态页面的数据
* @param {String} res
* @returns {{modifyDynamicResArray: UsefulDynamicInfo[];nextinfo: {has_more: number;next_offset: string;};} | null}
*/
modifyDynamicRes(res) {
const strToJson = Base.strToJson,
{ data, code } = strToJson(res);
if (code !== 0) {
log.error('处理动态数据', '获取动态数据出错,可能是访问太频繁 \n' + res);
return null;
}
/* 字符串offset防止损失精度 */
const offset = typeof data.offset === 'string' ? data.offset : /(?<=next_offset":)[0-9]*/.exec(res)[0]
, next = {
has_more: data.has_more,
next_offset: offset
};
/**
* 储存获取到的一组动态中的信息
*/
let array = [];
if (next.has_more === 0) {
log.info('处理动态数据', '动态数据读取完毕');
} else {
/**
* 空动态无cards
*/
const Cards = data.cards || [];
Cards.forEach(onecard => {
/**临时储存单个动态中的信息 */
let obj = {};
const { desc, card } = onecard
, { info, card: user_profile_card } = desc.user_profile
, { official_verify } = user_profile_card
, cardToJson = strToJson(card);
/* 转发者的UID */
obj.uid = info.uid;
/* 转发者的name */
obj.uname = info.uname;
/* 是否官方号 */
obj.official_verify = official_verify.type > -1 ? true : false;
/* 动态的ts10 */
obj.createtime = desc.timestamp
/* 动态类型 */
obj.type = desc.type
/* 用于发送评论 */
obj.rid_str = desc.rid_str.length > 12 ? desc.dynamic_id_str : desc.rid_str;
/* 源动态类型 */
obj.orig_type = desc.orig_type
/* 转发者的动态ID !!!!此为大数需使用字符串值,不然JSON.parse()会有丢失精度 */
obj.dynamic_id = desc.dynamic_id_str;
const { extension, extend_json } = onecard;
/* 定位@信息 */
obj.ctrl = (typeof extend_json === 'undefined') ? [] : strToJson(extend_json).ctrl || [];
/* 是否有官方抽奖 */
obj.hasOfficialLottery = (typeof extension === 'undefined') ? false : typeof extension.lott === 'undefined' ? false : true;
const { item = {} } = cardToJson;
/* 转发者的描述 后两个分别是视频动态的描述和视频本身的描述*/
obj.description = item.content || item.description || cardToJson.dynamic || cardToJson.desc || '';
if (obj.type === 1) {
/* 被转发者的UID */
obj.origin_uid = desc.origin.uid;
/* 被转发者的rid(用于发评论) */
obj.origin_rid_str = desc.origin.rid_str.length > 12 ? desc.origin.dynamic_id_str : desc.origin.rid_str;
/* 被转发者的动态的ID !!!!此为大数需使用字符串值,不然JSON.parse()会有丢失精度 */
obj.origin_dynamic_id = desc.orig_dy_id_str;
const { origin_extension, origin_user } = cardToJson;
try {
/* 是否官方号 */
obj.origin_official_verify = typeof origin_user === 'undefined' ?
false : origin_user.card.official_verify.type < 0 ?
false : true;
} catch (_) {
obj.origin_official_verify = false;
}
/* 是否有官方抽奖 */
obj.origin_hasOfficialLottery = typeof origin_extension === 'undefined' ?
false : typeof origin_extension.lott === 'undefined' ?
false : true;
const origin = cardToJson.origin || '{}';
const originToJson = strToJson(origin);
const { user, item } = originToJson;
/* 被转发者的name */
obj.origin_uname = typeof user === 'undefined'
? '' : user.name || user.uname || '';
/* 被转发者的描述 */
obj.origin_description = typeof item === 'undefined'
? '' : item.content || item.description || originToJson.dynamic || originToJson.desc || '';
}
array.push(obj);
});
}
return {
modifyDynamicResArray: array,
nextinfo: next
};
}
/**
* 整理后的抽奖信息
* @typedef {object} LotteryInfo
* @property {string} lottery_info_type
* @property {number[]} uids `[uid,ouid]`
* @property {string} uname
* @property {Array<{}>} ctrl
* @property {string} dyid
* @property {boolean} befilter
* @property {boolean} official_verify 官方认证
* @property {string} rid
* @property {string} des
* @property {number} type
* @property {boolean} hasOfficialLottery 是否官方
*/
/**
* 检查指定用户的所有的动态信息
* @param {string} UID 指定的用户UID
* @param {number} pages 读取页数
* @param {number} time 时延
* @param {string} [offset] 默认'0'
* @returns {Promise<{allModifyDynamicResArray: UsefulDynamicInfo[], offset: string}>} 获取前 `pages*12` 个动态信息
*/
async checkAllDynamic(hostuid, pages, time = 0, offset = '0') {
log.info('检查所有动态', `准备读取${pages}页动态`);
const { getOneDynamicInfoByUID } = BiliAPI,
/**
* 柯里化请求函数
*/
curriedGetOneDynamicInfoByUID = Util.curryify(getOneDynamicInfoByUID),
/**
* 储存了特定UID的请求函数
*/
hadUidGetOneDynamicInfoByUID = curriedGetOneDynamicInfoByUID(hostuid);
/**
* 储存所有经过整理后信息
* @type { UsefulDynamicInfo[] }
*/
let allModifyDynamicResArray = [];
for (let i = 0; i < pages; i++) {
log.info('检查所有动态', `正在读取其中第${i + 1}页动态`);
const
OneDynamicInfo = await hadUidGetOneDynamicInfoByUID(offset),
mDRdata = modifyDynamicRes(OneDynamicInfo);
if (mDRdata === null) {
break;
}
const
/**
* 一片动态
*/
mDRArry = mDRdata.modifyDynamicResArray,
nextinfo = mDRdata.nextinfo;
if (nextinfo.has_more === 0) {
offset = nextinfo.next_offset;
log.info('检查所有动态', `成功读取${i + 1}页信息(已经是最后一页了故无法读取更多)`);
break;
} else {
/**合并 */
allModifyDynamicResArray.push.apply(allModifyDynamicResArray, mDRArry);
log.info('检查所有动态', `开始读取第${i + 2}页动态信息`)
offset = nextinfo.next_offset;
}
await Util.delay(time);
}
log.info('检查所有动态', `${pages}页信息读取完成`)
return ({ allModifyDynamicResArray, offset });
}
/**
* 获取最新动态信息(转发子动态)
* 并初步整理
* @param {string} UID
* @returns {Promise<LotteryInfo[] | null>}
*/
async getLotteryInfoByUID(UID) {
log.info('获取动态', `开始获取用户${UID}的动态信息`);
const { allModifyDynamicResArray } = await this.checkAllDynamic(UID, config.uid_scan_page, config.search_wait);
if (!allModifyDynamicResArray.length) return null;
const fomatdata = allModifyDynamicResArray.map(o => {
return {
lottery_info_type: 'uid',
uids: [o.uid, o.origin_uid],
uname: o.origin_uname,
ctrl: [],
dyid: o.origin_dynamic_id,
rid: o.origin_rid_str,
des: o.origin_description,
type: o.orig_type,
hasOfficialLottery: o.origin_hasOfficialLottery
}
}).filter(a => a.type != 0)
log.info('获取动态', `成功获取用户${UID}的动态信息`);
return fomatdata;
}
/**
* 获取tag下的抽奖信息(转发母动态)
* 并初步整理
@@ -201,34 +241,42 @@ class Public {
* @returns {Promise<LotteryInfo[] | null>}
*/
async getLotteryInfoByTag(tag_name) {
const self = this,
const
tag_id = await BiliAPI.getTagIDByTagName(tag_name),
hotdy = await BiliAPI.getHotDynamicInfoByTagID(tag_id),
modDR = self.modifyDynamicRes(hotdy);
modDR = modifyDynamicRes(hotdy);
if (modDR === null) return null;
log.info('获取动态', `开始获取带话题#${tag_name}#的动态信息`);
log.info('获取动态', '成功获取热门动态');
let mDRdata = modDR.modifyDynamicResArray; /* 热门动态 */
/**
* 热门动态
*/
let mDRdata = modDR.modifyDynamicResArray;
let next_offset = modDR.nextinfo.next_offset;
for (let index = 0; index < config.scan_page_num; index++) {
log.info('获取动态', `成功读取${index + 1}页动态`);
const newdy = await BiliAPI.getOneDynamicInfoByTag(tag_name, next_offset);
const _modify = self.modifyDynamicRes(newdy);
for (let index = 0; index < config.tag_scan_page; index++) {
log.info('获取动态', `读取第${index + 1}页动态`);
const
newdy = await BiliAPI.getOneDynamicInfoByTag(tag_name, next_offset),
_modify = modifyDynamicRes(newdy);
if (_modify === null) return null;
mDRdata.push.apply(mDRdata, _modify.modifyDynamicResArray);
next_offset = _modify.nextinfo.next_offset;
await Base.delay(config.search_wait);
await Util.delay(config.search_wait);
}
const fomatdata = mDRdata.map(o => {
const hasOrigin = o.type === 1;
return {
lottery_info_type: 'tag',
uids: [o.uid, o.origin_uid],
uname: o.uname,
ctrl: o.ctrl,
dyid: o.dynamic_id,
official_verify: o.official_verify,
befilter: hasOrigin,
rid: o.rid_str,
des: o.description,
type: o.type,
@@ -236,35 +284,75 @@ class Public {
};
})
log.info('获取动态', `成功获取带话题#${tag_name}#的动态信息`);
return fomatdata
}
/**
* 获取最新动态信息(转发子动态)
* 并初步整理
* @param {string} UID
* 从专栏中获取抽奖信息
* @param {string} key_words
* @returns {Promise<LotteryInfo[] | null>}
*/
async getLotteryInfoByUID(UID) {
log.info('获取动态', `开始获取用户${UID}动态信息`);
const { allModifyDynamicResArray: aMDRA } = await this.checkAllDynamic(UID, config.scan_page_num, config.search_wait);
if (!aMDRA.length) return null;
const fomatdata = aMDRA.map(o => {
return {
lottery_info_type: 'uid',
uids: [o.uid, o.origin_uid],
uname: o.origin_uname,
ctrl: [],
dyid: o.origin_dynamic_id,
official_verify: o.origin_official_verify,
befilter: false,
rid: o.origin_rid_str,
des: o.origin_description,
type: o.orig_type,
hasOfficialLottery: o.origin_hasOfficialLottery
async getLotteryInfoByArticle(key_words) {
log.info('获取动态', `开始获取含关键词${key_words}专栏信息`);
const cvs = (await BiliAPI.searchArticlesByKeyword(key_words)).slice(0, config.article_scan_page);
let dyinfos = [];
for (const cv of cvs) {
const content = await BiliAPI.getOneArticleByCv(cv)
, dyids = content.match(/(?<=t.bilibili.com\/)[0-9]+/g) || [];
let { length } = dyids,
/**判断此专栏是否查看过的权重 */
weight = 8;
log.info('获取动态', `提取专栏(${cv})中提及的dyid(${length})`)
for (const dyid of dyids) {
const isRelayed = await MyStorage.searchDyid(dyid);
weight = isRelayed ? weight - 1 : 8;
if (weight < 0) {
log.info('获取动态', '连续8条动态曾经转过,该专栏或已查看,故中止')
dyinfos = []
break
}
if (dyid.length === Util.dyid_length) {
if (!isRelayed) {
log.info('获取动态', `查看动态(${dyid})的细节 (${length--})`)
const res = await BiliAPI.getOneDynamicByDyid(dyid)
, { code, data } = Util.strToJson(res)
, { card } = data;
if (code !== 0) {
log.error('获取动态', '获取动态数据出错,可能是访问太频繁 \n' + res)
break
}
await Util.delay(2000)
if (card) {
dyinfos.push(parseDynamicCard(card));
}
} else {
log.info('获取动态', `动态(${dyid})已转发过 (${length--})`)
}
} else {
log.warn('获取动态', `动态(${dyid})无效 (${length--})`)
}
}
}).filter(a => a.type === 0 ? false : true)
log.info('获取动态', `成功获取用户${UID}的动态信息`);
return fomatdata;
}
const fomatdata = dyinfos.map(o => {
return {
lottery_info_type: 'article',
uids: [o.uid, o.origin_uid],
uname: o.uname,
ctrl: o.ctrl,
dyid: o.dynamic_id,
rid: o.rid_str,
des: o.description,
type: o.type,
hasOfficialLottery: o.hasOfficialLottery
};
})
log.info('获取动态', `成功获取含关键词${key_words}的专栏信息`);
return fomatdata
}
}
+33 -62
View File
@@ -6,7 +6,7 @@ const { HttpRequest } = require("./HttpRequest");
/**
* 基础工具
*/
const Base = {
const Util = {
/**环境变量设置文件 */
env_file: path.join(process.cwd(), "env.js"),
/**配置文件 */
@@ -18,7 +18,7 @@ const Base = {
* 超出精度的数转为字符串
* @param {string} params
* @return {object}
* 返回对象
* 返回对象 解析失败返回 `{}`
*/
strToJson(params) {
const isJSON = (str => {
@@ -35,11 +35,22 @@ const Base = {
})(params);
return isJSON ? isJSON : {}
},
/**
* @template T
* @param {Array<T>} iter
* @param {(value: T) => Promise<Boolean>} fn 返回true整体退出
*/
async try_for_each(iter, fn) {
for (const item of iter) {
if (await fn(item)) break
}
},
/**
* 函数柯里化
* @param {function} func
* @template T
* @param {(arg, arg) => T} func
* 要被柯里化的函数
* @returns {function}
* @returns {(arg) => (arg) => T)}
* 一次接受一个参数并返回一个接受余下参数的函数
*/
curryify(func) {
@@ -58,6 +69,7 @@ const Base = {
* @returns {Promise<void>}
*/
delay(time) {
Util.log.info('时延', `${time}ms`);
return new Promise(resolve => {
setTimeout(() => {
resolve();
@@ -83,16 +95,20 @@ const Base = {
},
/**
* 随机获取数组中的一个元素
* @param {any[]} arr
* @returns {any}
* @template T
* @param {T[]} arr
* @returns {T}
*/
getRandomOne(arr) {
let RandomOne = null;
if (arr instanceof Array && arr.length) {
if (Array.isArray(arr) && arr.length) {
RandomOne = arr[parseInt(Math.random() * arr.length)];
}
return RandomOne
},
hasEnv(env_name) {
return process.env[env_name] ? true : false;
},
/**日志 */
log: {
level: 0,
@@ -113,71 +129,22 @@ const Base = {
debug(context, msg) {
if (this.level > 3) {
if (msg instanceof Object) msg = JSON.stringify(msg, null, 4);
this.proPrint([`[${Date()}]`, chalk.grey("[Debug]"), chalk.hex('#FFA500')(`[${context}]`), '\n', chalk.hex('#0070BB')(`[${msg}]`)])
this.proPrint([chalk.hex('#64B3FF')(`[${Date()}]`), chalk.grey("[Debug]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#0070BB')(`[\n${msg}\n]`)])
}
},
info(context, msg) {
if (this.level > 2)
this.proPrint([`[${Date()}]`, chalk.grey("[Info]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#48BB31')(`[${msg}]`)])
this.proPrint([chalk.hex('#64B3FF')(`[${Date()}]`), chalk.grey("[Info]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#48BB31')(`[${msg}]`)])
},
warn(context, msg) {
if (this.level > 1)
this.proPrint([`[${Date()}]`, chalk.grey("[Warn]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#BBBB23')(`[${msg}]`)])
this.proPrint([chalk.hex('#64B3FF')(`[${Date()}]`), chalk.grey("[Warn]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#BBBB23')(`[${msg}]`)])
},
error(context, msg) {
if (this.level > 0)
this.proPrint([`[${Date()}]`, chalk.grey("[Error]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#FF0006')(`[${msg}]`)])
this.proPrint([chalk.hex('#64B3FF')(`[${Date()}]`), chalk.grey("[Error]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#FF0006')(`[${msg}]`)])
}
},
/**
* 提取开奖信息
* @param {string} des 描述
* @returns {
{
ts: number|0;
text:string|'开奖时间: 未填写开奖时间';
item:string|'请自行查看';
isMe:string|'请自行查看';
}
* }
*/
getLotteryNotice(des) {
const r = /([\d零一二两三四五六七八九十]+)[.月]([\d零一二两三四五六七八九十]+)[日号]?/;
if (des === '') return {
ts: 0,
text: `开奖时间: 未填写开奖时间`,
item: '请自行查看',
isMe: '请自行查看'
}
const _date = r.exec(des) || [];
const timestamp10 = ((month, day) => {
if (month && day) {
let date = new Date(`${new Date(Date.now()).getFullYear()}-${month}-${day} 23:59:59`).getTime()
if (!isNaN(date)) return date / 1000;
}
return 0
})(_date[1], _date[2])
if (timestamp10 === 0) return {
ts: 0,
text: `开奖时间: 未填写开奖时间`,
item: '请自行查看',
isMe: '请自行查看'
}
const timestamp13 = timestamp10 * 1000,
time = new Date(timestamp13);
const remain = (() => {
const timestr = ((timestamp13 - Date.now()) / 86400000).toString()
, timearr = timestr.replace(/(\d+)\.(\d+)/, "$1,0.$2").split(',');
const text = timearr[0][0] === '-' ? `开奖时间已过${timearr[0].substring(1)}天余${parseInt(timearr[1] * 24)}小时` : `还有${timearr[0]}天余${parseInt(timearr[1] * 24)}小时`;
return text
})();
return {
ts: timestamp10,
text: `开奖时间: ${time.toLocaleString()} ${remain}`,
item: '请自行查看',
isMe: '请自行查看'
};
},
/**
* 获取远程设置
* @returns {Promise<JSON>}
@@ -262,6 +229,10 @@ const Base = {
})
});
},
/**
* dyid长度
*/
dyid_length: 18,
/**
* 读取dyid文件
* @param {number} num
@@ -269,7 +240,7 @@ const Base = {
*/
readDyidFile(num) {
const fpath = num < 2 ? path.join(this.dyids_dir, 'dyid.txt') : path.join(this.dyids_dir, `dyid${num}.txt`);
return fs.createReadStream(fpath, { encoding: 'utf8', highWaterMark: 19 * 1000 })
return fs.createReadStream(fpath, { encoding: 'utf8', highWaterMark: (this.dyid_length + 1) * 1000 })
},
/**
* 追加dyid
@@ -283,4 +254,4 @@ const Base = {
};
module.exports = Base;
module.exports = Util;
+8 -8
View File
@@ -1,8 +1,7 @@
const { log, delay } = require("./Base");
const { log, delay } = require("./Util");
const BiliAPI = require("./BiliAPI");
const Public = require("./Public");
const GlobalVar = require('./GlobalVar');
const { followWhiteList } = require("./config");
const config = require("./config");
/**动态偏移量 */
@@ -25,8 +24,8 @@ async function getFollowList() {
if (!uids.length) break;
rmup.push(...uids)
}
return followWhiteList.length
? rmup.filter(uid => followWhiteList.split(',').indexOf(String(uid)) === -1)
return config.clear_white_list.length
? rmup.filter(uid => config.clear_white_list.split(',').indexOf(String(uid)) === -1)
: rmup;
}
@@ -34,7 +33,7 @@ async function getFollowList() {
* 清理动态和关注
*/
async function clear() {
const { clear_max_day, clear_remove_dynamic, clear_remove_attention, clear_remove_delay, clear_dynamic_type } = config;
const { clear_white_list, clear_max_day, clear_remove_dynamic, clear_remove_attention, clear_remove_delay, clear_dynamic_type } = config;
let success = true;
const uid_list = await getFollowList();
if (!clear_remove_dynamic && clear_remove_attention) {
@@ -53,9 +52,9 @@ async function clear() {
let before_separate = [];
const MY_UID = Number(GlobalVar.get('myUID'));
for (let index = 0; ; index++) {
log.info('清理动态', `开始读取第${index + 1}页(12条)`);
const { allModifyDynamicResArray, offset: _offset } = await Public.prototype.checkAllDynamic(GlobalVar.get("myUID"), 1, 5 * 1000, offset);
offset = _offset;
log.info('清理动态', `开始读取第${index + 1}页(12条)`);
for (let index = 0; index < allModifyDynamicResArray.length; index++) {
const res = allModifyDynamicResArray[index];
const { type, dynamic_id, createtime } = res;
@@ -64,7 +63,8 @@ async function clear() {
if ((now - createtime) > 86400 * clear_max_day) {
/* 移除动态 */
if (dynamic_id
&& clear_remove_dynamic) {
&& clear_remove_dynamic
&& !(new RegExp(dynamic_id).test(clear_white_list))) {
success = await BiliAPI.rmDynamic(dynamic_id)
}
@@ -86,7 +86,7 @@ async function clear() {
}
}
}
log.info('清理动态', `${index}页中的转发动态与关注全部处理成功`)
log.info('清理动态', `${index + 1}页中的转发动态与关注全部处理成功`)
if (offset === '0' || !success) break;
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
const { config_file } = require('./Base');
const { config_file } = require('./Util');
const my_config = require(config_file);
const config = {
+10 -10
View File
@@ -1,4 +1,4 @@
const Base = require('./Base');
const Util = require('./Util');
const BiliAPI = require('./BiliAPI');
const eventBus = require('./eventBus');
const GlobalVar = require('./GlobalVar');
@@ -6,7 +6,7 @@ const Public = require('./Public');
const Monitor = require('./Monitor');
const { sendNotify } = require('./sendNotify');
const config = require('./config');
const { log } = Base;
const { log } = Util;
async function createRandomDynamic(num) {
if (config.create_dy) {
@@ -14,8 +14,8 @@ async function createRandomDynamic(num) {
const Dynamic = await Public.prototype.checkAllDynamic(GlobalVar.get("myUID"), 1);
if ((Dynamic.allModifyDynamicResArray[0] || { type: 0 }).type === 1) {
for (let index = 0; index < num; index++) {
await BiliAPI.createDynamic(Base.getRandomOne(config.dy_contents));
await Base.delay(2000);
await BiliAPI.createDynamic(Util.getRandomOne(config.dy_contents));
await Util.delay(2000);
}
} else {
log.info('随机动态', '已有非抽奖动态故无需创建');
@@ -30,7 +30,7 @@ async function createRandomDynamic(num) {
*/
function start() {
return new Promise(resolve => {
let times = Base.counter();
let times = Util.counter();
/* 注册事件 */
eventBus.on('Turn_on_the_Monitor', async () => {
const lotterys = GlobalVar.get("Lottery");
@@ -47,8 +47,8 @@ function start() {
return;
}
const lottery = lotterys[times.next()];
const nlottery = Number(lottery);
await (new Monitor(isNaN(nlottery) ? lottery : nlottery)).init();
await (new Monitor(lottery)).init();
});
eventBus.on('Turn_off_the_Monitor', async (msg) => {
await createRandomDynamic(config.create_dy_num);
@@ -93,8 +93,8 @@ async function isMe() {
session_t = session_ts;
if (talker_id) {
BiliAPI.updateSessionStatus(talker_id);
await Base.delay(1000);
if (/中奖|获得|填写|写上|提供|地址|支付宝账号|码|大会员/.test(content)) {
await Util.delay(1000);
if (/中奖|获得|填写|写上|提供|收货地址|支付宝账号|码|大会员/.test(content)) {
desp += `发生时间: ${new Date(timestamp * 1000).toLocaleString()} \n\n`
desp += `用户: ${sender_uid} \n\n`
desp += `私信你(${GlobalVar.get("myUID")})说: ${content} \n\n`
@@ -104,7 +104,7 @@ async function isMe() {
}
}
if (MySession.has_more) {
await Base.delay(3e3);
await Util.delay(3e3);
MySession = await BiliAPI.getSessionInfo(type, session_t)
}
max++
+2 -2
View File
@@ -1,4 +1,4 @@
const { log } = require("./Base");
const { log } = require("./Util");
const { HttpRequest } = require("./HttpRequest");
const { createTransport } = require("nodemailer");
@@ -430,7 +430,7 @@ function ddBotNotify(text, desp) {
const dateNow = Date.now();
const hmac = crypto.createHmac('sha256', DD_BOT_SECRET);
hmac.update(`${dateNow}\n${DD_BOT_SECRET}`);
const result = encodeURIComponent(hmac.digest('base64'));
const result = encodeURIComponent(hmac.digest('Util64'));
HttpRequest({
method: 'POST',
url: `https://oapi.dingtalk.com/robot/send`,
+13 -5
View File
@@ -1,4 +1,4 @@
const Base = require("./Base");
const Util = require("./Util");
const GlobalVar = require("./GlobalVar");
const config = require("./config");
@@ -15,16 +15,24 @@ async function setVariable(cookie, n) {
config.updata(process.env.NUMBER);
GlobalVar.set('cookie', cookie);
cookie.split(/\s*;\s*/).forEach(item => {
const _item = item.split('=');
if (key_map.has(_item[0]))
GlobalVar.set(key_map.get(_item[0]), _item[1]);
});
GlobalVar.set('Lottery', [...config.UIDs, ...config.TAGs]);
GlobalVar.set('remoteconfig', await Base.getRemoteConfig());
const { UIDs = [], TAGs = [], Articles = [] } = config;
GlobalVar.set('Lottery', [
...UIDs.map(it => ['UIDs', it]),
...TAGs.map(it => ['TAGs', it]),
...Articles.map(it => ['Articles', it])
]);
GlobalVar.set('remoteconfig', await Util.getRemoteConfig());
}
await Base.createDir('dyids');
await Base.createFile(n < 2 ? 'dyid.txt' : `dyid${n}.txt`, '', 'a')
await Util.createDir('dyids');
await Util.createFile(n < 2 ? 'dyid.txt' : `dyid${n}.txt`, '', 'a')
return
}
+10 -7
View File
@@ -1,4 +1,4 @@
const { env_file, config_file, log, delay, hasFileOrDir } = require("./lib/Base");
const { env_file, config_file, log, delay, hasFileOrDir } = require("./lib/Util");
const metainfo = [
` _ _ _ _____ _ _ `,
@@ -10,7 +10,7 @@ const metainfo = [
` __/ | | | `,
` |___/ |_| `,
` `,
` by shanmite `,
` v1.9.5 by shanmite`,
]
/**多账号存储 */
let multiple_account = [];
@@ -36,6 +36,9 @@ async function main() {
await main();
await delay(acco.WAIT);
}
/**多账号状态还原 */
process.env.ENABLE_MULTIPLE_ACCOUNT = ENABLE_MULTIPLE_ACCOUNT;
} else {
if (!COOKIE) {
return '请查看README文件, 在env.js指定位置填入cookie'
@@ -110,18 +113,18 @@ async function main() {
process.env.lottery_mode = process.argv[2]
const err_msg = await main();
if (err_msg) {
log.error('错误', '\n' + err_msg + '\n');
log.warn('结束运行', '5秒后自动退出');
await delay(5 * 1000);
} else {
if (loop_wait > 0) {
while (loop_wait) {
log.info('程序休眠', `${loop_wait / 1000}秒后再次启动`)
await delay(loop_wait);
} else {
log.info('结束运行', '未设置休眠时间')
await delay(loop_wait)
await main()
}
log.info('结束运行', '未设置休眠时间')
}
process.exit(0);
})()
+31 -17
View File
@@ -12,14 +12,21 @@ module.exports = {
241675899
],
/**
* 监视的专栏关键词
*/
Articles: [
'抽奖合集'
],
/**
* 监视的tag
*/
TAGs: [
'互动抽奖',
'抽奖',
'转发抽奖',
'动态抽奖',
'抽奖',
],
/**
@@ -53,9 +60,19 @@ module.exports = {
is_imitator: false,
/**
* - 在uid或tag里检索的页数
* - 在uid里检索的页数
*/
scan_page_num: 3,
uid_scan_page: 3,
/**
* - 在tag里检索的页数
*/
tag_scan_page: 3,
/**
* - 获取专栏数量
*/
article_scan_page: 3,
/**
* - 开奖时间距离现在的最大天数
@@ -76,7 +93,7 @@ module.exports = {
* - 单位毫秒
* - 上下浮动50%
*/
wait: 100 * 1000,
wait: 30 * 1000,
/**
* - 检索动态间隔
@@ -89,11 +106,6 @@ module.exports = {
*/
minfollower: 1000,
/**
* 粉丝数限制是否跳过有官方认证的up
*/
skip_official_verify: true,
/**
* - 只转发已关注的
*/
@@ -128,19 +140,15 @@ module.exports = {
at_users: [['转发抽奖娘', 294887687], ['你的工具人老公', 100680137]],
/**
* 同步 https://gitee.com/shanmite/lottery-notice/raw/master/notice.json
* - 同步 https://gitee.com/shanmite/lottery-notice/raw/master/notice.json
* - 英文逗号分隔 如: 1,2,3
*/
blacklist: '1,2',
blacklist: '',
/**
* 屏蔽词
*/
blockword: ["脚本抽奖", "恭喜", "结果", "抽奖号", "钓鱼"],
/**
* 取关白名单
*/
followWhiteList: '1,2',
blockword: ["脚本抽奖", "恭喜", "结果", "抽奖号", "钓鱼", "涨粉"],
/**
* 转发评语
@@ -169,6 +177,12 @@ module.exports = {
*/
is_exception: false,
/**
* - 清理白名单uid或dyid
* - 英文逗号分隔 如: 1,2,3
*/
clear_white_list: '',
/**
* - 取关分区
* - 默认为: 此处存放因抽奖临时关注的up
+3 -2
View File
@@ -9,7 +9,8 @@
"check": "node main.js check",
"pkg_x86": "npx pkg . && PowerShell .\\script\\pkg\\pkg.ps1",
"pkg_clean_dist": "PowerShell -Command \"& {Remove-Item -Path .\\dist\\ -Recurse}\"",
"pkg_arm": "npx pkg -t linux-arm -o dist/lottery-in-bili-linux-arm main.js"
"pkg_arm64": "npx pkg -t linux-arm64 -o dist/lottery main.js && cp my_config.example.js my_config.js && cp env.example.js dist/env.js",
"pkg_armv7": "npx pkg -t linux-armv7 -o dist/lottery main.js && cp my_config.example.js my_config.js && cp env.example.js dist/env.js"
},
"bin": "main.js",
"pkg": {
@@ -43,4 +44,4 @@
"nodemailer": "^6.5.0",
"unzipper": "^0.10.11"
}
}
}
-1
View File
@@ -17,7 +17,6 @@ Copy-Item -Path $TEMPLATE_CONFIG_FILE -Destination $TARGET_DIR -Force
Set-Location -Path $TARGET_DIR
# 重命名文件
Move-Item -Path $TEMPLATE_ENV_FILE -Destination $ENV_FILE -Force
Move-Item -Path $TEMPLATE_CONFIG_FILE -Destination $CONFIG_FILE -Force