Compare commits

...
19 Commits
Author SHA1 Message Date
shanmite 9842107f52 fix: (#14) 2021-08-16 13:00:12 +08:00
shanmite 89dea18ae3 feat: 账号异常时切换线路 2021-08-16 12:51:21 +08:00
shanmite a426eb48f5 fix: 账号异常处理 2021-08-14 20:14:35 +08:00
shanmite c06f69457a pref: 时区+8(#13) 2021-08-14 13:24:54 +08:00
shanmite 155332751f fix: 解构赋初值异常 2021-08-14 13:02:46 +08:00
shanmite a28ec20b12 feat: 检查更新
fix: tag在中间的情况
2021-08-13 12:32:54 +08:00
shanmite 35cb1c24c2 fix: lib/main[48:9] 2021-08-09 14:52:41 +08:00
shanmite 4f961250be feat: 不参与主站黑名单用户抽奖 2021-08-09 13:48:44 +08:00
shanmite dce1ff61fd fix: 可从环境变量中读取COOKIE 2021-08-09 11:32:45 +08:00
shanmite ab6bc97f50 chore: 部分修改 2021-08-09 10:49:33 +08:00
shanmite da8903944a doc: 更新readme 2021-08-08 11:46:39 +08:00
shanmite 08f4375c21 feat: 中奖通知设置可设黑名单 2021-08-08 10:34:14 +08:00
shanmite ec0c5da092 fix: this丢失 2021-08-07 16:01:54 +08:00
shanmite 7d3273611f refactor: 模块结构调整 2021-08-07 15:32:39 +08:00
shanmite 673b3883a8 fix: 优化截取tag的逻辑 2021-08-06 22:03:31 +08:00
shanmiteandGitHub f157761f5c Merge pull request #10 from andywang425/main
chore: 更新issue_template
2021-08-04 16:30:45 +08:00
andywang425 c57d21d4cd chore: 更新issue_template 2021-08-04 15:58:48 +08:00
shanmite 26ae391eee fix: 私信检测(#9) 2021-08-04 13:41:00 +08:00
shanmite a1b055b9de chore: 更新issue_template 2021-07-31 10:59:52 +08:00
33 changed files with 1675 additions and 1576 deletions
-11
View File
@@ -1,11 +0,0 @@
---
name: 新功能请求
about: 提出你想要的功能或你的建议
title: ''
labels: ''
assignees: ''
---
### 清晰而简明地描述
在此写下你的描述
-33
View File
@@ -1,33 +0,0 @@
---
name: Bug 反馈
about: 提出你遇到的问题, 提问之前请检索问题是否重复
title: ''
labels: ''
assignees: ''
---
### 在反馈bug之前,请确保你已经认真阅读了本项目的README和脚本的内置说明
**描述bug**
简要描述所遇到的bug
**重现bug**
说明您在进行了怎样的操作后出现了bug
1. xxx
2. xxx
**预期行为**
简要描述进行以上操作后预期的脚本行为
**截图**
如果可以,请提供有关截图
**运行日志**
控制台日志。
**使用环境:**
- Github Actions中
- 本地运行
**其他**
若您有其他想要补充的内容,请在此说明
+107
View File
@@ -0,0 +1,107 @@
name: Bug反馈
description: 提出你遇到的问题
body:
- type: markdown
attributes:
value: |
**为避免无效问题和冗余问题,提问前请确认**
- 你确定搜索引擎不能解决你的问题
- 你确定提供的Readme文档和Release说明不能解决你的问题
- 你确定已有的issue不能解决你的问题
- 你确定issue的title能简明的描述你的问题
<br />
- id: describe
type: textarea
validations:
required: true
attributes:
label: "描述Bug"
description: |
简要而清晰的描述你所遇到的bug。
- id: reproduction
type: textarea
validations:
required: true
attributes:
label: "重现Bug"
description: |
说明您在进行了怎样的操作后出现了Bug.
placeholder: |
1. xxx
2. xxx
- id: expection
type: textarea
validations:
required: true
attributes:
label: "预期行为"
description: |
简要描述进行以上操作后预期的脚本行为。
- id: picture
type: textarea
validations:
required: false
attributes:
label: "截图"
description: |
如果可以,请提供尽可能多的相关截图。
placeholder: |
可使用 QQ / Snipaste 等工具截图后在此处 ctrl + v 黏贴。
- id: log
type: textarea
validations:
required: true
attributes:
label: "运行日志"
description: |
控制台日志。
placeholder: |
请在此黏贴运行日志。
- id: system
type: input
validations:
required: true
attributes:
label: "操作系统"
description: |
请给出操作系统名称和版本号。
placeholder: |
eg: Windows 10
- id: nodejs_version
type: input
validations:
required: false
attributes:
label: "NodeJs版本"
description: |
若使用源码运行请在控制台输入`node -v`查看版本号。
placeholder: |
eg: v16.5.0
- id: lotteryAutoScript_version
type: input
validations:
required: true
attributes:
label: "脚本版本"
description: |
脚本版本。脚本开始运行后会显示版本号。
placeholder: |
eg: v2.0.2
- id: extra
type: textarea
validations:
required: false
attributes:
label: "其他"
description: |
若您有其他想要补充的内容,请在此说明
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: false
@@ -0,0 +1,19 @@
name: 新功能请求
description: 提出你想要的功能或你的建议
body:
- type: markdown
attributes:
value: |
## 欢迎
请确保你所提出的功能脚本的确没有。
<br />
- id: describe
type: textarea
validations:
required: true
attributes:
label: "描述"
description: |
请清晰而简明地描述你想要的功能或你的建议。
-123
View File
@@ -1,123 +0,0 @@
{
"HttpRequest-get": {
"scope": "javascript,typescript",
"prefix": "hrget",
"body": [
"HttpRequest({",
" method: 'GET',",
" url: '$1',",
" query: {",
" $2",
" },",
" headers: {",
" accept: 'application/json, text/plain, */*',",
" cookie: '$3',",
" },",
" success: res => {",
" $4",
" },",
" failure: err => {",
" $5",
" }",
"})$6"
],
"description": "简化http-get请求"
},
"HttpRequest-post": {
"scope": "javascript,typescript",
"prefix": "hrpost",
"body": [
"HttpRequest({",
" method: 'POST',",
" url: '$1',",
" contents: {",
" $2",
" },",
" headers: {",
" accept: 'application/json, text/plain, */*',",
" 'content-type': 'application/x-www-form-urlencoded; charset=utf-8',",
" cookie: '$3',",
" },",
" success: res => {",
" $4",
" },",
" failure: err => {",
" $5",
" }",
"})$6"
],
"description": "简化http-post请求"
},
"CORSajax-get": {
"scope": "javascript,typescript",
"prefix": "corsget",
"body": [
"CORSajax.get({",
" proxy_link: '$1',",
" proxy_querystring: {",
" $2",
" },",
" proxy_headers: {",
" Cookie: '$3'",
" },",
"},chunk => {",
" $4",
"})$5"
],
"description": "简化跨域Ajax本地nodejsのget代理"
},
"CORSajax-post": {
"scope": "javascript,typescript",
"prefix": "corspost",
"body": [
"CORSajax.post({",
" proxy_link: '$1',",
" proxy_headers: {",
" 'content-type': 'application/x-www-form-urlencoded; charset=utf-8',",
" cookie: '$2'",
" },",
" proxy_body: {",
" $3",
" },",
"},chunk => {",
" $4",
"})$5"
],
"description": "简化跨域Ajax本地nodejsのpost代理"
},
"Ajax-get": {
"scope": "javascript,typescript",
"prefix": "myget",
"body": [
"Ajax.get({",
" url: '$1',",
" queryStringsObj: {",
" $2",
" },",
" hasCookies: true,",
" success: responseText => {",
" $3",
" }",
"})",
],
"description": "简化AjaxのGet请求"
},
"Ajax-post": {
"scope": "javascript,typescript",
"prefix": "mypost",
"body": [
"Ajax.post({",
" url: '$1',",
" hasCookies: true,",
" dataType: 'application/x-www-form-urlencoded',",
" data: {",
" $2",
" },",
" success: responseText => {",
" $3",
" }",
"})",
],
"description": "简化Ajaxのpost请求"
},
}
-14
View File
@@ -1,14 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "启动程序",
"skipFiles": [
"<node_internals>/**"
],
"program": "${file}"
}
]
}
+21 -8
View File
@@ -17,12 +17,19 @@
[Github仓库链接](https://github.com/shanmiteko/LotteryAutoScript)
已实现功能:
> 点赞 评论 转发 @好友 带话题 随机动态 检测开奖 清理
已实现功能:
- 监控用户转发
- 监控话题页面
- 监控专栏合集
- 自动点赞、评论、乱序转发、@好友、带话题、可选随机动态
- 检测是否中奖
- 清理动态关注
- 检查更新
- 更多功能设置请参考配置文件
声明: 此脚本仅用于学习和测试,作者本人并不对其负责,请于运行测试完成后自行删除,请勿滥用!
**声明**: 此脚本仅用于学习和测试,作者本人并不对其负责,请于运行测试完成后自行删除,请勿滥用!
----------------------------------------
---------------------------------
## 操作步骤
@@ -70,11 +77,17 @@ 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 自定义设置文件
~/nlts-linux-x64
=> tree
.
├── dyids (自动生成的dyid存储)
│   └── dyid.txt
├── env.js (便捷设置环境变量和多账号参数)
├── lottery (可执行文件)
├── my_config.js (自定义设置文件) (!使用前必读)
└── README.md (说明文件)
```
2. 用记事本或其他编辑器修改`env.js`和`my_config.js`文件(右键选择用记事本打开)
3. 在`env.js`中填入`COOKIE`和推送参数
-42
View File
@@ -1,42 +0,0 @@
const { HttpRequest } = require('./HttpRequest');
const GlobalVar = require("./GlobalVar");
/**
* Ajax请求对象
*/
module.exports = (() => {
const get = ({ url, retry, queryStringsObj, success }) => {
HttpRequest({
method: 'GET',
url,
config: {
retry
},
query: queryStringsObj,
headers: {
"accept": 'application/json, text/plain, */*',
"cookie": GlobalVar.get("cookie")
},
success: res => success(res.body),
failure: err => success(err)
})
};
const post = ({ url, retry, data, success }) => {
HttpRequest({
method: 'POST',
url,
contents: data,
config: {
retry
},
headers: {
"accept": 'application/json, text/plain, */*',
"content-type": 'application/x-www-form-urlencoded; charset=utf-8',
"cookie": GlobalVar.get("cookie")
},
success: res => success(res.body),
failure: err => success(err)
})
};
return { get, post };
})();
-883
View File
@@ -1,883 +0,0 @@
const Ajax = require('./Ajax');
const { strToJson, log } = require('./Util');
const GlobalVar = require('./GlobalVar');
/**
* 网络请求
*/
const BiliAPI = {
/**
* 判断是否成功登录
* @returns {Promise<boolean>}
*/
async getMyinfo() {
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.bilibili.com/x/space/myinfo',
success: responseText => {
let res = strToJson(responseText);
if (res.code === 0) {
resolve(true);
} else {
resolve(false);
}
}
})
});
},
/**
* 获取被at的信息
* @typedef AtInfo
* @property {number} at_time
* @property {string} up_uname
* @property {string} business
* @property {string} source_content
* @property {string} url
* @returns {Promise<AtInfo[]>}
*/
async getMyAtInfo() {
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.bilibili.com/x/msgfeed/at',
success: responseText => {
const res = strToJson(responseText);
const atInfo = [];
if (res.code === 0) {
const items = res.data.items;
if (items.length !== 0) {
items.forEach(i => {
const { at_time, item, user } = i
, { nickname: up_uname } = user
, { business, uri: url, source_content } = item;
atInfo.push({
at_time,
up_uname,
business,
source_content,
url
});
});
}
resolve(atInfo);
} else {
resolve(atInfo);
}
}
});
});
},
/**
* 获取未读@
* @returns {Promise<number>}
*/
async getUnreadAtNum() {
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.bilibili.com/x/msgfeed/unread',
success: responseText => {
let res = strToJson(responseText);
if (res.code === 0) {
const { at } = res.data;
resolve(at)
log.info('获取未读@', `成功 数量: ${at}`)
} else {
resolve(-1)
log.error('获取未读@', `失败\n${responseText}`)
}
}
})
});
},
/**
* 获取私信
* @typedef SessionData
* @property {string} session_ts
* @property {string} content
* @property {number} timestamp
* @property {number} sender_uid
* @property {number} talker_id
*
* @typedef SessionInfo
* @property {number} has_more
* @property {SessionData[]} data
*
* @param {number} session_type 1 已关注 2 未关注
* @param {string} [ts_16]
* @returns {Promise<SessionInfo>}
*/
async getSessionInfo(session_type, ts_16 = '') {
return new Promise((resolve) => {
Ajax.post({
url: 'https://api.vc.bilibili.com/session_svr/v1/session_svr/get_sessions',
data: {
session_type,
group_fold: 1,
unfollow_fold: 1,
sort_rule: 2,
build: 0,
mobi_app: 'web',
end_ts: ts_16,
},
success: responseText => {
let res = strToJson(responseText);
if (res.code === 0) {
log.info('获取一页私信(20)', '成功 ' + (ts_16 ? 'end_ts->' + ts_16 : '第一页'));
/**@type {Array} */
const sessions = res.data.session_list || [];
const has_more = res.data.has_more;
const data = sessions.map(session => {
const { session_ts, last_msg = {}, unread_count, talker_id } = session;
const { content = '', timestamp = 0, sender_uid = 0 } = last_msg;
return { session_ts, content, timestamp, sender_uid, talker_id: unread_count ? talker_id : undefined }
})
resolve({ has_more, data })
} else {
log.error('获取私信', `失败\n${responseText}`);
resolve({ has_more: 0, data: [] });
}
}
})
});
},
/**
* 获取未读私信数量
* @returns {Promise<{ unfollow_unread: number, follow_unread: number }>}
*/
async getUnreadSessionNum() {
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.vc.bilibili.com/session_svr/v1/session_svr/single_unread',
success: responseText => {
let res = strToJson(responseText);
if (res.code === 0) {
const { unfollow_unread, follow_unread } = res.data;
resolve({ unfollow_unread, follow_unread });
log.info('获取未读私信', `成功 已关注未读数: ${follow_unread}, 未关注未读数 ${unfollow_unread}`);
} else {
resolve(null);
log.error('获取未读私信', `失败\n${responseText}`);
}
}
})
});
},
/**
* 私信已读
* @param {number} talker_id
*/
updateSessionStatus(talker_id) {
Ajax.post({
url: 'https://api.vc.bilibili.com/session_svr/v1/session_svr/update_ack',
retry: false,
data: {
talker_id,
session_type: 1,
ack_seqno: 1,
mobi_app: "web",
csrf_token: GlobalVar.get("csrf")
},
success: responseText => {
let res = strToJson(responseText);
if (res.code === 0) {
log.info('私信已读', `成功 -> talker_id: ${talker_id}`);
} else {
log.error('私信已读', `失败 -> talker_id: ${talker_id}`);
}
}
})
},
/**
* 获取关注列表
* @param {number} uid
* @returns {Promise<string | null>}
*/
getAttentionList(uid) {
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.vc.bilibili.com/feed/v1/feed/get_attention_list',
queryStringsObj: {
uid: uid
},
success: responseText => {
let res = strToJson(responseText);
if (res.code === 0) {
log.info('获取关注列表', '成功');
resolve(res.data.list.toString());
} else {
log.error('获取关注列表', `失败\n${responseText}`);
resolve(null);
}
}
});
});
},
/**
* 获取一个动态的细节
* @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
* 被查看者的uid
* @param {string} offset
* 此动态偏移量
* 初始为 0
* @returns {Promise<string>}
*/
getOneDynamicInfoByUID(UID, offset) {
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history',
queryStringsObj: {
visitor_uid: GlobalVar.get("myUID"),
host_uid: UID,
offset_dynamic_id: offset,
},
retry: false,
success: responseText => {
/* 鉴别工作交由modifyDynamicRes完成 */
resolve(responseText);
}
});
});
},
/**
* 通过tag名获取tag的id
* @param {string} tagename
* tag名
* @returns {Promise<number | -1>}
* 正确:tag_ID
* 错误:-1
*/
getTagIDByTagName(tagename) {
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.bilibili.com/x/tag/info',
queryStringsObj: {
tag_name: tagename
},
success: responseText => {
const res = strToJson(responseText);
if (res.code !== 0) {
log.error('获取TagID', '失败');
resolve(-1);
} else {
resolve(res.data.tag_id);
}
}
});
});
},
/**
* 获取tag下的热门动态以及一条最新动态
* @param {number} tagid
* @returns {Promise<string>}
*/
getHotDynamicInfoByTagID(tagid) {
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.vc.bilibili.com/topic_svr/v1/topic_svr/topic_new',
queryStringsObj: {
topic_id: tagid
},
success: responseText => {
resolve(responseText);
}
});
});
},
/**
* 获取tag下的最新动态
* @param {string} tagname
* @param {string} offset
* @returns {Promise<string>}
*/
getOneDynamicInfoByTag(tagname, offset) {
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.vc.bilibili.com/topic_svr/v1/topic_svr/topic_history',
queryStringsObj: {
topic_name: tagname,
offset_dynamic_id: offset
},
retry: false,
success: responseText => {
resolve(responseText);
}
});
});
},
/**
* 搜索专栏
* @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
* @returns {Promise<number | -1>}
*/
getUserInfo(uid) {
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.bilibili.com/x/web-interface/card',
queryStringsObj: {
mid: uid,
photo: false
},
retry: false,
success: responseText => {
const res = strToJson(responseText);
if (res.code === 0) {
resolve(res.data.follower);
} else {
log.warn('获取粉丝数', '尝试切换线路');
Ajax.get({
url: 'https://api.bilibili.com/x/relation/stat',
queryStringsObj: {
vmid: uid
},
success: responseText => {
const res = strToJson(responseText);
if (res.code === 0) {
log.info('获取粉丝数', 'ok');
resolve(res.data.follower);
} else {
log.error('获取粉丝数', `出错 可能是访问过频繁\n${responseText}`);
resolve(-1);
}
}
})
}
}
});
});
},
/**
* 获取开奖信息
* @param {string} dyid
* 动态id
* @typedef LotteryNotice
* @property {number | -1} ts
* @property {string | "获取开奖信息失败"} text
* @property {string | "null"} item
* @property {string | "未知"} isMe
* @returns {Promise<LotteryNotice>} 开奖时间
*/
getLotteryNotice(dyid) {
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.vc.bilibili.com/lottery_svr/v1/lottery_svr/lottery_notice',
queryStringsObj: {
dynamic_id: dyid
},
success: responseText => {
const res = strToJson(responseText);
/(?<=_prize_cmt":").*(?=")/.exec();
if (res.code === 0) {
const timestamp10 = res.data.lottery_time,
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;
})();
let isMeB = (new RegExp(GlobalVar.get("myUID"))).test(responseText);
const isMe = isMeB ? '中奖了!!!' : '未中奖';
const iteminfo = res.data.first_prize_cmt || '' + ' ' + res.data.second_prize_cmt || '' + ' ' + res.data.third_prize_cmt || '';
resolve({
ts: timestamp10,
text: `开奖时间: ${time.toLocaleString()} ${remain}`,
item: iteminfo,
isMe: isMe
});
} else {
log.error('获取开奖信息', `失败\n${responseText}`);
resolve({
ts: -1,
text: '获取开奖信息失败',
item: 'null',
isMe: '未知'
});
}
}
});
});
},
/**
* 之前不检查是否重复关注
* 自动关注
* 并转移分组
* @param {Number} uid
* 被关注者的UID
* @returns {Promise<number>}
* 0 - 成功
* 1 - 失败
* 2 - 异常
*/
autoAttention(uid) {
return new Promise((resolve) => {
Ajax.post({
url: 'https://api.bilibili.com/x/relation/modify',
retry: false,
data: {
fid: uid,
act: 1,
re_src: 11,
csrf: GlobalVar.get("csrf")
},
success: responseText => {
/* 重复关注code also equal 0 */
const res = strToJson(responseText)
if (res.code === 0) {
log.info('自动关注', '关注+1');
resolve(0);
} else if (res.code === 22002) {
log.error('自动关注', '您已被对方拉入黑名单');
resolve(1);
} else if (res.code === 22015) {
log.error('自动关注', '您的账号异常无法关注');
resolve(2);
} else {
log.warn('自动关注', `失败 尝试切换线路\n${responseText}`);
Ajax.post({
url: 'https://api.vc.bilibili.com/feed/v1/feed/SetUserFollow',
data: {
type: 1,
follow: uid,
csrf: GlobalVar.get("csrf")
},
success: responseText => {
if (/^{"code":0/.test(responseText)) {
log.info('自动关注', '关注+1');
resolve(0);
} else {
log.warn('自动关注', `失败 尝试切换另一条线路\n${responseText}`);
Ajax.post({
url: 'https://api.bilibili.com/x/relation/batch/modify',
data: {
fid: uid,
act: 1,
re_src: 11,
csrf: GlobalVar.get("csrf")
},
success: responseText => {
if (/^{"code":0/.test(responseText)) {
log.info('自动关注', '关注+1');
resolve(0);
} else {
log.error('自动关注', `失败\n${responseText}`);
resolve(1);
}
}
})
}
}
})
}
}
});
});
},
/**
* 移动分区
* @param {number} uid
* @param {number} tagid 关注分区的ID
* @returns {Promise<number>}
* 0 - 成功
* 1 - 失败
*/
movePartition(uid, tagid) {
return new Promise((resolve) => {
Ajax.post({
url: 'https://api.bilibili.com/x/relation/tags/addUsers',
data: {
fids: uid,
tagids: tagid,
csrf: GlobalVar.get("csrf")
},
success: responseText => {
/* 重复移动code also equal 0 */
if (/^{"code":0/.test(responseText)) {
log.info('移动分区', 'up主分区移动成功');
resolve(0);
} else {
log.error('移动分区', `up主分区移动失败\n${responseText}`);
resolve(1);
}
}
});
});
},
/**
* 取消关注
* @param {number} uid
* @returns {Promise<boolean>}
*/
cancelAttention(uid) {
return new Promise((resolve) => {
Ajax.post({
url: 'https://api.bilibili.com/x/relation/modify',
retry: false,
data: {
fid: uid,
act: 2,
re_src: 11,
csrf: GlobalVar.get("csrf")
},
success: responseText => {
const res = strToJson(responseText);
if (res.code === 0) {
log.info('自动取关', `取关成功(${uid})`);
resolve(true)
} else {
log.error('自动取关', `取关失败(${uid})\n${responseText}`);
resolve(false)
}
}
});
});
},
/**
* 动态自动点赞
* @param {string} dyid
* @returns {Promise<number>}
* 0 - 成功
* 1 - 失败
*/
autolike(dyid) {
return new Promise((resolve) => {
Ajax.post({
url: 'https://api.vc.bilibili.com/dynamic_like/v1/dynamic_like/thumb',
data: {
uid: GlobalVar.get("myUID"),
dynamic_id: dyid,
up: 1,
csrf: GlobalVar.get("csrf")
},
success: responseText => {
if (/^{"code":0/.test(responseText)) {
log.info('自动点赞', '点赞成功');
resolve(0);
} else {
log.error('自动点赞', `点赞失败\n${responseText}`);
resolve(1);
}
}
});
});
},
/**
* 转发前应查看是否重复转发
* 自动转发
* @param {Number} uid
* 自己的UID
* @param {string} dyid
* @param {string} [msg]
* 动态的ID
* @returns {Promise<number>}
* 0 - 成功
* 1 - 失败
*/
autoRelay(uid, dyid, msg = '转发动态', ctrl = '[]') {
const len = msg.length;
if (len > 233) {
msg = msg.slice(0, 233 - len)
}
return new Promise((resolve) => {
Ajax.post({
url: 'https://api.vc.bilibili.com/dynamic_repost/v1/dynamic_repost/repost',
retry: false,
data: {
uid: `${uid}`,
dynamic_id: dyid,
content: msg,
ctrl,
csrf: GlobalVar.get("csrf")
},
success: responseText => {
if (/^{"code":0/.test(responseText)) {
log.info('转发动态', '成功转发一条动态');
resolve(0);
} else {
log.error('转发动态', `转发动态失败\n${responseText}`);
resolve(1);
}
}
});
});
},
/**
* @typedef Picture
* @property {string} img_src
* @property {number} img_width
* @property {number} img_height
* 发布一条动态
* @param { string | Picture[] } content
* @return {Promise<void>}
*/
createDynamic(content) {
let data = {
csrf: GlobalVar.get("csrf"),
extension: '{"emoji_type":1,"from":{"emoji_type":1},"flag_cfg":{}}'
}
let url = '';
if (content instanceof Array) {
url = 'https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/create_draw'
data = {
...data,
biz: 3,
category: 3,
pictures: JSON.stringify(content)
}
} else {
url = 'https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/create'
data = {
...data,
content,
}
}
return new Promise((resolve) => {
Ajax.post({
url,
data,
success: responseText => {
if (/^{"code":0/.test(responseText)) {
log.info('发布动态', '成功创建一条随机内容的动态');
} else {
log.error('发布动态', `发布动态失败\n${responseText}`);
}
resolve()
}
})
});
},
/**
* 移除动态
* @param {string} dyid
* @returns {Promise<boolean>}
*/
rmDynamic(dyid) {
return new Promise((resolve) => {
Ajax.post({
url: 'https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/rm_dynamic',
data: {
dynamic_id: dyid,
csrf: GlobalVar.get("csrf")
},
retry: false,
success: responseText => {
if (/^{"code":0/.test(responseText)) {
log.info('删除动态', `成功删除一条动态(${dyid})`);
resolve(true);
} else {
log.error('删除动态', `删除动态失败(${dyid})\n${responseText}`);
resolve(false);
}
}
});
});
},
/**
* 发送评论
* @param {string} rid
* cid_str
* @param {string} msg
* @param {number} type
* 1(视频)
* 11(有图)
* 17(无图)
* @returns {Promise<number>}
* 0 - 成功
* 1 - 失败
*/
sendChat(rid, msg, type, show = true) {
return new Promise((resolve) => {
Ajax.post({
url: 'https://api.bilibili.com/x/v2/reply/add',
data: {
oid: rid,
type: type,
message: msg,
csrf: GlobalVar.get("csrf")
},
success: responseText => {
const res = strToJson(responseText);
if (res.code === 0) {
show && log.info('自动评论', '评论成功');
resolve(0);
} else if (res.code === -404) {
show && log.error('自动评论', '原动态已删除');
resolve(0);
} else if (res.code === 12002) {
show && log.error('自动评论', '评论区已关闭');
resolve(0);
} else if (res.code === 12015) {
show && log.error('自动评论', '需要输入验证码');
resolve(1);
} else {
show && log.error('自动评论', `评论失败\n${responseText}`);
resolve(0);
}
}
});
});
},
/**
* 检查分区
* 不存在指定分区时创建
* 获取到tagid添加为对象的属性
* @param {string} [name]
* @returns {Promise<number>}
*/
checkMyPartition(name) {
if (!name) name = '此处存放因抽奖临时关注的up';
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.bilibili.com/x/relation/tags',
success: responseText => {
const res = strToJson(responseText);
let tagid = undefined;
if (res.code === 0) {
const data = res.data.filter((it) => it.name === name);
if (data.length) {
log.info('获取分区id', '成功');
tagid = data[0].tagid
} else {
log.warn('获取分区id', '失败 无指定分区');
}
if (name === '此处存放因抽奖临时关注的up') {
if (typeof tagid === 'undefined') {
BiliAPI.createPartition(name).then(id => resolve(id))
} else {
resolve(tagid)
}
} else {
resolve(tagid)
}
} else {
log.error('获取分区id', `访问出错 可在my_config里手动填入\n${responseText}`)
resolve(tagid)
}
}
})
});
},
/**
* 创造分区
* @param {string} partition_name
* @returns {Promise<number>}
*/
createPartition(partition_name) {
return new Promise((resolve) => {
Ajax.post({
url: 'https://api.bilibili.com/x/relation/tag/create',
data: {
tag: partition_name,
csrf: GlobalVar.get("csrf")
},
success: responseText => {
let obj = strToJson(responseText);
if (obj.code === 0) {
log.info('新建分区', '分区新建成功')
let { tagid } = obj.data /* 获取tagid */
resolve(tagid)
} else {
log.error('新建分区', `分区新建失败\n${responseText}`);
resolve(undefined);
}
}
})
})
},
/**
* 获取一个分区中50个的id
* @param {number} tagid
* @param {number} n 1->
* @returns {Promise<number[]>}
*/
getPartitionUID(tagid, n) {
return new Promise((resolve) => {
Ajax.get({
url: 'https://api.bilibili.com/x/relation/tag',
queryStringsObj: {
mid: GlobalVar.get("myUID"),
tagid: tagid,
pn: n,
ps: 50
},
success: responseText => {
const res = strToJson(responseText);
let uids = [];
if (res.code === 0) {
res.data.forEach(d => {
uids.push(d.mid);
})
log.info(`获取分组${tagid}`, `成功获取取关分区列表${n}`);
resolve(uids)
} else {
log.error(`获取分组${tagid}`, `获取取关分区列表失败\n${responseText}`);
resolve(uids)
}
}
})
});
}
};
module.exports = BiliAPI;
-12
View File
@@ -1,12 +0,0 @@
let GlobalVar = {
inner: {},
get(key) {
return this.inner[key]
},
set(key, value) {
this.inner[key] = value
},
};
module.exports = GlobalVar;
+78
View File
@@ -0,0 +1,78 @@
const { log, delay, infiniteNumber, judge } = require('./utils')
const { sendNotify } = require('./helper/notify')
const config = require('./data/config')
const global_var = require('./data/global_var')
const bili = require('./net/bili')
/**
* 是否中奖
*/
async function isMe() {
let desp = '';
const UnreadAtNum = await bili.getUnreadAtNum();
const UnreadSessionNum = await bili.getUnreadSessionNum();
const { follow_unread, unfollow_unread } = UnreadSessionNum || { unfollow_unread: 0, follow_unread: 0 };
if (UnreadAtNum > 0) {
log.info('中奖检测', '<-- 正在检查at');
const MyAtInfo = await bili.getMyAtInfo();
MyAtInfo.forEach(async AtInfo => {
const { at_time, up_uname, business, source_content, url } = AtInfo
desp += `发生时间: ${new Date(at_time * 1000).toLocaleString()} \n\n`
desp += `用户: ${up_uname} \n\n`
desp += `${business}中@了你(${global_var.get("myUID")}) \n\n`
desp += `原内容为: ${source_content} \n\n`
desp += `[直达链接](${url}) \n\n`
desp += `\n\n`
});
log.info('中奖检测', '--> OK');
}
if (follow_unread + unfollow_unread > 0) {
const check = async (type) => {
let session_t = '';
let MySession = await bili.getSessionInfo(type)
for (const index of infiniteNumber()) {
for (const Session of MySession.data) {
const { content, sender_uid, session_ts, timestamp, unread_count, talker_id, msg_seqno } = Session;
session_t = session_ts;
if (unread_count) {
bili.updateSessionStatus(talker_id, type, msg_seqno);
await delay(1000);
if (judge(content, config.notice_key_words)) {
desp += `发生时间: ${new Date(timestamp * 1000).toLocaleString()} \n\n`
desp += `用户: ${sender_uid} \n\n`
desp += `私信你(${global_var.get("myUID")})说: ${content} \n\n`
desp += `[直达链接](https://message.bilibili.com/#/whisper/mid${sender_uid}) \n\n`
desp += `\n\n`
}
}
}
if (MySession.has_more && index < 16) {
await delay(3e3);
MySession = await bili.getSessionInfo(type, session_t)
} else {
break
}
}
}
if (follow_unread) {
log.info('中奖检测', '<-- 正在检查已关注者的私信')
await check(1)
}
if (unfollow_unread) {
log.info('中奖检测', '<-- 正在检查未关注者的私信')
await check(2)
}
log.info('中奖检测', '--> OK');
}
if (desp) {
desp += '中奖了别忘给脚本(https://github.com/shanmiteko/LotteryAutoScript)点一个Star哦, 赞助一两块也不是不可以‍_(:з」∠)_\n\n'
log.info('可能中奖了', desp);
await sendNotify('可能中奖了', desp);
} else {
log.info('中奖检测', "暂未中奖");
}
return;
}
module.exports = { isMe };
+12 -12
View File
@@ -1,22 +1,22 @@
const { log, delay, infiniteNumber } = require("./Util");
const BiliAPI = require("./BiliAPI");
const Public = require("./Public");
const GlobalVar = require('./GlobalVar');
const config = require("./config");
const { log, delay, infiniteNumber } = require("./utils");
const bili = require("./net/bili");
const { Searcher } = require("./core/searcher");
const global_var = require('./data/global_var');
const config = require("./data/config");
/**
* 获取关注分区里的uid
* @returns { Promise<number[]> }
*/
async function getFollowList() {
const tagid = await BiliAPI.checkMyPartition(config.clear_partition);
const tagid = await bili.checkMyPartition(config.clear_partition);
if (typeof tagid === 'undefined') {
log.info('获取关注列表', '未能成功获取关注分区id');
return
}
let rmup = [];
for (let index = 1; index < 42; index++) {
const uids = await BiliAPI.getPartitionUID(tagid, index);
const uids = await bili.getPartitionUID(tagid, index);
await delay(2e3);
if (!uids.length) break;
rmup.push(...uids)
@@ -44,7 +44,7 @@ async function clear() {
for (const [index, uid] of uid_list.entries()) {
log.info('清理关注', `(${index}) (${uid})`)
/* 取消关注 */
if (await BiliAPI.cancelAttention(uid)) {
if (await bili.cancelAttention(uid)) {
log.info('清理关注', '成功')
} else {
log.error('清理关注', '失败')
@@ -56,14 +56,14 @@ async function clear() {
} else {
const
Now = Date.now() / 1000,
MY_UID = Number(GlobalVar.get('myUID'));
MY_UID = Number(global_var.get('myUID'));
let next_offset = '0',
before_separate = [];
for (const page of infiniteNumber()) {
log.info('清理动态', `开始读取第${page + 1}`);
const { allModifyDynamicResArray, offset } = await Public.prototype.checkAllDynamic(MY_UID, 1, 5 * 1000, next_offset);
const { allModifyDynamicResArray, offset } = await Searcher.checkAllDynamic(MY_UID, 1, 5 * 1000, next_offset);
next_offset = offset;
for (const [index, dyinfo] of allModifyDynamicResArray.entries()) {
log.info('清理动态', `${page + 1}页中的第${index + 1}个动态`)
@@ -78,7 +78,7 @@ async function clear() {
if (dynamic_id
&& clear_remove_dynamic
&& !(new RegExp(dynamic_id).test(clear_white_list))) {
success = await BiliAPI.rmDynamic(dynamic_id)
success = await bili.rmDynamic(dynamic_id)
}
/* 取消关注 */
@@ -87,7 +87,7 @@ async function clear() {
&& clear_remove_attention
&& before_separate.indexOf(origin_uid) === -1
&& uid_list.indexOf(origin_uid) > -1) {
success = await BiliAPI.cancelAttention(origin_uid);
success = await bili.cancelAttention(origin_uid);
}
if (!success) break;
+64 -59
View File
@@ -1,17 +1,17 @@
const Util = require('./Util');
const BiliAPI = require('./BiliAPI');
const { sendNotify } = require('./sendNotify');
const eventBus = require('./eventBus');
const Public = require('./Public');
const GlobalVar = require("./GlobalVar");
const config = require("./config");
const MyStorage = require('./MyStorage');
const { log, hasEnv } = Util;
const utils = require('../utils');
const bili = require('../net/bili');
const { sendNotify } = require('../helper/notify');
const event_bus = require('../helper/event_bus');
const { Searcher } = require('./searcher');
const global_var = require("../data/global_var");
const config = require("../data/config");
const d_storage = require('../helper/d_storage');
const { log, hasEnv } = utils;
/**
* 监视器
*/
class Monitor extends Public {
class Monitor extends Searcher {
/**
* @constructor
* @param {[string, number | string]} lottery_param
@@ -32,46 +32,48 @@ class Monitor extends Public {
*/
async init() {
if (config.model === '00') {
eventBus.emit('Turn_off_the_Monitor', '已关闭所有转发行为')
event_bus.emit('Turn_off_the_Monitor', '已关闭所有转发行为')
return
}
if (!this.tagid) {
this.tagid = await BiliAPI.checkMyPartition() /* 检查关注分区 */
this.tagid = await bili.checkMyPartition() /* 检查关注分区 */
if (!this.tagid) {
eventBus.emit('Turn_off_the_Monitor', '分区获取失败')
event_bus.emit('Turn_off_the_Monitor', '分区获取失败')
return
}
}
/** 关注列表初始化 */
this.attentionList = await BiliAPI.getAttentionList(GlobalVar.get("myUID"));
this.attentionList = await bili.getAttentionList(global_var.get("myUID"));
switch (await this.startLottery()) {
case 0:
eventBus.emit('Turn_on_the_Monitor')
event_bus.emit('Turn_on_the_Monitor')
break;
case 11:
eventBus.emit('Turn_off_the_Monitor', '评论失败')
event_bus.emit('Turn_off_the_Monitor', '评论失败')
break
case 21:
eventBus.emit('Turn_on_the_Monitor')
event_bus.emit('Turn_on_the_Monitor')
break
case 22:
config.only_followed = true;
log.warn('账号异常', `UID(${global_var.get('myUID')})临时进入只转已关注模式(异常号只会对部分UP出现关注异常)`)
if (!config.is_exception) {
config.is_exception = true;
await sendNotify('[动态抽奖]账号异常通知', `UID: ${GlobalVar.get('myUID')}\n\n已自动跳过异常关注(异常号只会对部分UP出现关注异常)\n\n可在设置中令is_exception为true关闭此推送`)
await sendNotify('[动态抽奖]账号异常通知', `UID: ${global_var.get('myUID')}\n\n临时进入只转已关注模式(异常号只会对部分UP出现关注异常)\n\n可在设置中令is_exception为true关闭此推送`)
}
eventBus.emit('Turn_on_the_Monitor')
config.is_exception = true;
event_bus.emit('Turn_on_the_Monitor')
break
case 31:
eventBus.emit('Turn_off_the_Monitor', '转发失败')
event_bus.emit('Turn_off_the_Monitor', '转发失败')
break
case 41:
eventBus.emit('Turn_off_the_Monitor', '获取开奖时间失败')
event_bus.emit('Turn_off_the_Monitor', '获取开奖时间失败')
break
case 51:
eventBus.emit('Turn_off_the_Monitor', '获取关注数失败')
event_bus.emit('Turn_off_the_Monitor', '获取关注数失败')
break
default:
eventBus.emit('Turn_off_the_Monitor', '未知错误')
event_bus.emit('Turn_off_the_Monitor', '未知错误')
break;
}
}
@@ -86,41 +88,41 @@ class Monitor extends Public {
log.info('筛选动态', `筛选完毕(${len})`);
if (len) {
for (const Lottery of Util.shuffle(allLottery)) {
for (const Lottery of utils.shuffle(allLottery)) {
let status = 0;
if (Lottery.isOfficialLottery) {
let { ts } = await BiliAPI.getLotteryNotice(Lottery.dyid);
let { ts } = await bili.getLotteryNotice(Lottery.dyid);
const ts_10 = Date.now() / 1000;
if (ts < 0) {
return 41
}
if (ts < ts_10) {
log.info('过滤', '已过开奖时间')
MyStorage.updateDyid(Lottery.dyid)
d_storage.updateDyid(Lottery.dyid)
continue
}
if (ts > ts_10 + config.maxday * 86400) {
log.info('过滤', '超过指定开奖时间')
MyStorage.updateDyid(Lottery.dyid)
d_storage.updateDyid(Lottery.dyid)
continue
}
} else if (Lottery.uid[0]) {
const followerNum = await BiliAPI.getUserInfo(Lottery.uid[0]);
const followerNum = await bili.getUserInfo(Lottery.uid[0]);
if (followerNum < 0) {
return 51
}
if (followerNum < config.minfollower) {
log.info('过滤', `粉丝数(${followerNum})小于指定数量`)
MyStorage.updateDyid(Lottery.dyid)
d_storage.updateDyid(Lottery.dyid)
continue
}
}
status = await this.go(Lottery)
if (status % 2 !== 0) {
if (status) {
return status
}
MyStorage.updateDyid(Lottery.dyid);
await Util.delay(config.wait * (Math.random() + 0.5));
d_storage.updateDyid(Lottery.dyid)
await utils.delay(config.wait * (Math.random() + 0.5));
}
log.info('抽奖', '开始转发下一组动态');
return 0
@@ -173,14 +175,14 @@ class Monitor extends Public {
/**并发查询dyid */
await Promise.all(
[...dyids_map.keys()]
.map(it => MyStorage
.map(it => d_storage
.searchDyid(it)
.then(hasIt => dyids_map.set(it, hasIt))
)
)
/* 检查动态是否满足要求 */
await Util.try_for_each(protoLotteryInfo, async function ({
await utils.try_for_each(protoLotteryInfo, async function ({
lottery_info_type, uids,
uname, dyid,
ctrl, rid, des, type,
@@ -191,20 +193,20 @@ class Monitor extends Public {
const
/**判断是转发源动态还是现动态 */
uid = lottery_info_type === 'uid' ? uids[1] : uids[0]
, 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 =
uid = lottery_info_type === 'uid' ? uids[1] : uids[0],
isFollowed = (new RegExp(uid)).test(attentionList),
description = typeof des === 'string' ? des : '',
needAt = /(?:@|艾特)[^@|(艾特)]*?好友/.test(description),
needTopic = [...new Set(description.match(/(?<=[带加上](?:话题|tag).*)#.+?#|(?<=[带加上])#.+?#(?=话题|tag)/ig) || [])].join(' '),
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 =
|| (!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');
@@ -216,7 +218,7 @@ class Monitor extends Public {
if (only_followed && !isFollowed) return false;
/* 获取黑名单并去重合并 */
const { blacklist: remote_blacklist } = GlobalVar.get("remoteconfig")
const { blacklist: remote_blacklist } = global_var.get("remoteconfig")
, new_blacklist = remote_blacklist
? [...new Set([...blacklist.split(','), ...remote_blacklist.split(',')])].join()
: blacklist;
@@ -239,7 +241,7 @@ class Monitor extends Public {
let
/**转发评语 */
RandomStr = Util.getRandomOne(config.relay),
RandomStr = utils.getRandomOne(config.relay),
/**控制字段 */
new_ctrl = [];
@@ -325,12 +327,15 @@ class Monitor extends Public {
let status = 0;
const max_retry_times = 5;
for (let times = 0; times < max_retry_times; times++) {
status = await BiliAPI.sendChat(rid, Util.getRandomOne(config.chat), chat_type)
status = await bili.sendChat(rid, utils.getRandomOne(config.chat), chat_type)
if (status === -1) {
return 0
}
if (!status) {
break
}
log.info('自动评论', `将在 ${times + 1} 分钟后再次发送评论(${times + 1}/${max_retry_times})`)
await Util.delay(60 * 1000 * (times + 1))
await utils.delay(60 * 1000 * (times + 1))
}
if (status) return 11;
}
@@ -338,28 +343,28 @@ class Monitor extends Public {
/* 关注 */
const [u1, u2] = uid
if (u1) {
let status = await BiliAPI.autoAttention(u1)
let status = await bili.autoAttention(u1)
if (status) return 20 + status;
status = await BiliAPI.movePartition(u1, this.tagid)
status = await bili.movePartition(u1, this.tagid)
if (status) return 20 + status;
if (u2) {
Util.delay(5000)
status = await BiliAPI.autoAttention(u2)
utils.delay(5000)
status = await bili.autoAttention(u2)
if (status) return 20 + status;
status = await BiliAPI.movePartition(u2, this.tagid)
status = await bili.movePartition(u2, this.tagid)
if (status) return 20 + status;
}
}
/* 点赞 */
await BiliAPI.autolike(dyid)
await bili.autolike(dyid)
/* 转发 */
if (await BiliAPI.autoRelay(GlobalVar.get("myUID"), dyid, relay_chat, ctrl)) return 31;
if (await bili.autoRelay(global_var.get("myUID"), dyid, relay_chat, ctrl)) return 31;
return 0
}
}
module.exports = Monitor;
module.exports = { Monitor };
+28 -28
View File
@@ -1,9 +1,9 @@
const Util = require('./Util');
const BiliAPI = require('./BiliAPI');
const config = require("./config");
const MyStorage = require('./MyStorage');
const utils = require('../utils');
const bili = require('../net/bili');
const config = require("../data/config");
const d_storage = require('../helper/d_storage');
const { log } = Util
const { log } = utils
/**
* 解析dynamic_detail_card
@@ -31,7 +31,7 @@ const { log } = Util
* @return {UsefulDynamicInfo}
*/
function parseDynamicCard(dynamic_detail_card) {
const { strToJson } = Util;
const { strToJson } = utils;
/**临时储存单个动态中的信息 */
let obj = {};
const { desc, card, extension, extend_json } = dynamic_detail_card
@@ -86,8 +86,8 @@ function parseDynamicCard(dynamic_detail_card) {
*/
function modifyDynamicRes(res) {
const
{ data = {}, code } = Util.strToJson(res),
{ cards = [], has_more, offset } = data;
{ data, code } = utils.strToJson(res),
{ cards = [], has_more, offset } = data || {};
if (code !== 0) {
log.error('处理动态数据', '获取动态数据出错,可能是访问太频繁 \n' + res);
@@ -124,9 +124,9 @@ function modifyDynamicRes(res) {
}
/**
* 基础功能
* 基础搜索功能
*/
class Public {
class Searcher {
constructor() { }
/**
* 整理后的抽奖信息
@@ -149,14 +149,14 @@ class Public {
* @param {string} [offset] 默认'0'
* @returns {Promise<{allModifyDynamicResArray: UsefulDynamicInfo[], offset: string}>} 获取前 `pages*12` 个动态信息
*/
async checkAllDynamic(hostuid, pages, time = 0, offset = '0') {
static async checkAllDynamic(hostuid, pages, time = 0, offset = '0') {
log.info('检查所有动态', `准备读取${pages}页动态`);
const { getOneDynamicInfoByUID } = BiliAPI,
const { getOneDynamicInfoByUID } = bili,
/**
* 柯里化请求函数
*/
curriedGetOneDynamicInfoByUID = Util.curryify(getOneDynamicInfoByUID),
curriedGetOneDynamicInfoByUID = utils.curryify(getOneDynamicInfoByUID),
/**
* 储存了特定UID的请求函数
*/
@@ -196,7 +196,7 @@ class Public {
offset = nextinfo.next_offset;
}
await Util.delay(time);
await utils.delay(time);
}
log.info('检查所有动态', `${pages}页信息读取完成`)
@@ -211,7 +211,7 @@ class Public {
*/
async getLotteryInfoByUID(UID) {
log.info('获取动态', `开始获取用户${UID}的动态信息`);
const { allModifyDynamicResArray } = await this.checkAllDynamic(UID, config.uid_scan_page, config.search_wait);
const { allModifyDynamicResArray } = await Searcher.checkAllDynamic(UID, config.uid_scan_page, config.search_wait);
if (!allModifyDynamicResArray.length) return null;
@@ -240,8 +240,8 @@ class Public {
*/
async getLotteryInfoByTag(tag_name) {
const
tag_id = await BiliAPI.getTagIDByTagName(tag_name),
hotdy = await BiliAPI.getHotDynamicInfoByTagID(tag_id),
tag_id = await bili.getTagIDByTagName(tag_name),
hotdy = await bili.getHotDynamicInfoByTagID(tag_id),
modDR = modifyDynamicRes(hotdy);
if (modDR === null) return null;
@@ -258,7 +258,7 @@ class Public {
for (let index = 0; index < config.tag_scan_page; index++) {
log.info('获取动态', `读取第${index + 1}页动态`);
const
newdy = await BiliAPI.getOneDynamicInfoByTag(tag_name, next_offset),
newdy = await bili.getOneDynamicInfoByTag(tag_name, next_offset),
_modify = modifyDynamicRes(newdy);
if (_modify === null) return null;
@@ -266,7 +266,7 @@ class Public {
mDRdata.push.apply(mDRdata, _modify.modifyDynamicResArray);
next_offset = _modify.nextinfo.next_offset;
await Util.delay(config.search_wait);
await utils.delay(config.search_wait);
}
const fomatdata = mDRdata.map(o => {
return {
@@ -292,12 +292,12 @@ class Public {
*/
async getLotteryInfoByArticle(key_words) {
log.info('获取动态', `开始获取含关键词${key_words}的专栏信息`);
const cvs = (await BiliAPI.searchArticlesByKeyword(key_words)).slice(0, config.article_scan_page);
const cvs = (await bili.searchArticlesByKeyword(key_words)).slice(0, config.article_scan_page);
let dyinfos = [];
for (const cv of cvs) {
const
content = await BiliAPI.getOneArticleByCv(cv),
content = await bili.getOneArticleByCv(cv),
dyids = content.match(/(?<=t.bilibili.com\/)[0-9]+/g) || [],
dyids_set = [...new Set(dyids)],
/**判断此专栏是否查看过的权重 */
@@ -307,7 +307,7 @@ class Public {
_weight = 0;
log.info('获取动态', `提取专栏(${cv})中提及的dyid(${length})`)
for (const dyid of dyids_set) {
const isRelayed = await MyStorage.searchDyid(dyid);
const isRelayed = await d_storage.searchDyid(dyid);
if (isRelayed) {
_weight += 1;
}
@@ -316,19 +316,19 @@ class Public {
dyinfos = []
break
}
if (dyid.length === Util.dyid_length) {
if (dyid.length === utils.dyid_length) {
if (!isRelayed) {
log.info('获取动态', `查看动态(${dyid})的细节 (${length--})`)
const res = await BiliAPI.getOneDynamicByDyid(dyid)
, { code, data = {} } = Util.strToJson(res)
, { card } = data;
const res = await bili.getOneDynamicByDyid(dyid)
, { code, data } = utils.strToJson(res)
, { card } = data || {};
if (code !== 0) {
log.error('获取动态', '获取动态数据出错,可能是访问太频繁 \n' + res)
break
}
await Util.delay(2000)
await utils.delay(2000)
if (card) {
dyinfos.push(parseDynamicCard(card));
@@ -361,4 +361,4 @@ class Public {
}
module.exports = Public;
module.exports = { Searcher };
+3 -1
View File
@@ -1,4 +1,4 @@
const { config_file } = require('./Util');
const { config_file } = require('../utils');
const my_config = require(config_file);
const config = {
@@ -12,6 +12,8 @@ const config = {
Object.entries(new_config)
.forEach(([k, v]) => this[k] = v)
}
},
init () {
}
};
+46
View File
@@ -0,0 +1,46 @@
const { getRemoteConfig, createDir, createFile } = require("../utils");
const config = require("../data/config");
const key_map = new Map([['DedeUserID', 'myUID'], ['bili_jct', 'csrf']]);
let global_var = {
inner: {},
get(key) {
return this.inner[key]
},
set(key, value) {
this.inner[key] = value
},
/**
* 全局变量初始化
* 更新config
* @param {string} cookie
* @param {number} n
*/
async init(cookie, n) {
if (cookie) {
config.updata(process.env.NUMBER);
this.set('cookie', cookie);
cookie.split(/\s*;\s*/).forEach(item => {
const _item = item.split('=');
if (key_map.has(_item[0]))
this.set(key_map.get(_item[0]), _item[1]);
});
const { UIDs = [], TAGs = [], Articles = [] } = config;
this.set('Lottery', [
...UIDs.map(it => ['UIDs', it]),
...TAGs.map(it => ['TAGs', it]),
...Articles.map(it => ['Articles', it])
]);
this.set('remoteconfig', await getRemoteConfig());
}
await createDir('dyids');
await createFile(n < 2 ? 'dyid.txt' : `dyid${n}.txt`, '', 'a')
}
};
module.exports = global_var;
+6 -7
View File
@@ -1,7 +1,6 @@
const Util = require("./Util");
const { log } = Util;
const { log, readDyidFile, writeDyidFile, dyid_length } = require("../utils");
const MyStorage = {
const d_storage = {
/**
* 搜索dyid
* @param {string} dyid
@@ -10,7 +9,7 @@ const MyStorage = {
searchDyid: (dyid) => {
return new Promise((resolve) => {
const Rdyid = new RegExp(dyid);
const rs = Util.readDyidFile(Number(process.env.NUMBER));
const rs = readDyidFile(Number(process.env.NUMBER));
let status = false;
rs.on('data', chunk => {
if (Rdyid.test(chunk)) {
@@ -32,11 +31,11 @@ const MyStorage = {
*/
updateDyid: (dyid) => {
log.info('更新dyid', `写入${dyid}`);
if (dyid.length !== Util.dyid_length) {
if (dyid.length !== dyid_length) {
log.error('更新dyid', `dyid(${dyid})长度不为18 若出现此问题请即时通知开发者`)
}
return new Promise((resolve) => {
const ws = Util.writeDyidFile(Number(process.env.NUMBER));
const ws = writeDyidFile(Number(process.env.NUMBER));
ws.write(dyid + ',', () => {
ws.destroy();
resolve()
@@ -50,4 +49,4 @@ const MyStorage = {
}
module.exports = MyStorage;
module.exports = d_storage;
+2 -2
View File
@@ -3,7 +3,7 @@ const { EventEmitter } = require('events');
/**
* 事件总线
*/
const eventBus = {
const event_bus = {
ee: new EventEmitter(),
event_list: [],
on(event, fn) {
@@ -22,4 +22,4 @@ const eventBus = {
}
module.exports = eventBus;
module.exports = event_bus;
+69 -71
View File
@@ -1,5 +1,5 @@
const { log } = require("./Util");
const { HttpRequest } = require("./HttpRequest");
const { log } = require("../utils");
const { send } = require("../net/http");
const { createTransport } = require("nodemailer");
// =======================================微信server酱通知设置区域===========================================
@@ -185,7 +185,7 @@ async function sendNotify(text, desp, params = {}) {
function serverNotify(text, desp) {
return new Promise(resolve => {
if (SCKEY) {
HttpRequest({
send({
method: 'GET',
url: `https://sc.ftqq.com/${SCKEY}.send`,
query: {
@@ -202,26 +202,26 @@ function serverNotify(text, desp) {
try {
const data = JSON.parse(res.body);
if (data.errno === 0) {
log.info('发送通知','server酱发送通知消息成功\n')
log.info('发送通知', 'server酱发送通知消息成功')
} else if (data.errno === 1024) {
// 一分钟内发送相同的内容会触发
log.error('发送通知',`server酱发送通知消息异常: ${data.errmsg}\n`)
log.error('发送通知', `server酱发送通知消息异常: ${data.errmsg}`)
} else {
log.error('发送通知',`server酱发送通知消息异常\n${JSON.stringify(data)}`)
log.error('发送通知', `server酱发送通知消息异常\n${JSON.stringify(data)}`)
}
} catch (error) {
log.error('发送通知',error);
log.error('发送通知', error);
} finally {
resolve()
}
},
failure: err => {
log.error('发送通知','server酱 发送通知调用API失败!!\n')
log.error('发送通知', 'server酱 发送通知调用API失败!!')
throw new Error(err);
}
})
} else {
log.warn('发送通知','您未提供server酱的SCKEY,取消微信推送消息通知\n');
log.debug('发送通知', '您未提供server酱的SCKEY,取消微信推送消息通知');
resolve()
}
})
@@ -230,7 +230,7 @@ function serverNotify(text, desp) {
function serverNotifyTurbo(text, desp) {
return new Promise(resolve => {
if (SENDKEY) {
HttpRequest({
send({
method: 'POST',
url: `https://sctapi.ftqq.com/${SENDKEY}.send`,
contents: {
@@ -247,23 +247,23 @@ function serverNotifyTurbo(text, desp) {
try {
const data = JSON.parse(res.body);
if (data.code === 0) {
log.info('发送通知','server酱(Turbo版)发送通知消息成功\n')
log.info('发送通知', 'server酱(Turbo版)发送通知消息成功')
} else {
log.error('发送通知',`server酱(Turbo版)发送通知消息异常\n${JSON.stringify(data)}`)
log.error('发送通知', `server酱(Turbo版)发送通知消息异常\n${JSON.stringify(data)}`)
}
} catch (error) {
log.error('发送通知',error);
log.error('发送通知', error);
} finally {
resolve()
}
},
failure: err => {
log.error('发送通知','server酱(Turbo版) 发送通知调用API失败!!\n')
log.error('发送通知', 'server酱(Turbo版) 发送通知调用API失败!!')
throw new Error(err);
}
})
} else {
log.warn('发送通知','您未提供server酱(Turbo版)的SCKEY,取消微信推送消息通知\n');
log.debug('发送通知', '您未提供server酱(Turbo版)的SCKEY,取消微信推送消息通知');
resolve()
}
})
@@ -286,7 +286,7 @@ function coolPush(text, desp) {
return "未知方式"
}
}
HttpRequest({
send({
method: 'POST',
url: `https://push.xuthus.cc/${QQ_MODE}/${QQ_SKEY}`,
contents: `${text}\n${desp}`,
@@ -301,25 +301,25 @@ function coolPush(text, desp) {
try {
const data = JSON.parse(res.body);
if (data.code === 200) {
log.info('发送通知',`酷推发送${pushMode(QQ_MODE)}通知消息成功\n`)
log.info('发送通知', `酷推发送${pushMode(QQ_MODE)}通知消息成功`)
} else if (data.code === 400) {
log.error('发送通知',`QQ酷推(Cool Push)发送${pushMode(QQ_MODE)}推送失败:${data}\n`)
log.error('发送通知', `QQ酷推(Cool Push)发送${pushMode(QQ_MODE)}推送失败:${data}`)
} else {
log.error('发送通知',`酷推推送异常: ${data.msg}`);
log.error('发送通知', `酷推推送异常: ${data.msg}`);
}
} catch (error) {
log.error('发送通知',error);
log.error('发送通知', error);
} finally {
resolve()
}
},
failure: err => {
log.error('发送通知',`酷推 发送${pushMode(QQ_MODE)}通知调用API失败!!\n`)
log.error('发送通知', `酷推 发送${pushMode(QQ_MODE)}通知调用API失败!!`)
throw new Error(err);
}
})
} else {
log.warn('发送通知','您未提供酷推的SKEY,取消QQ推送消息通知\n');
log.debug('发送通知', '您未提供酷推的SKEY,取消QQ推送消息通知');
resolve()
}
})
@@ -328,7 +328,7 @@ function coolPush(text, desp) {
function barkNotify(text, desp, params = {}) {
return new Promise(resolve => {
if (BARK_PUSH) {
HttpRequest({
send({
method: 'GET',
url: `${BARK_PUSH}/${encodeURIComponent(text)}/${encodeURIComponent(desp)}`,
query: {
@@ -345,24 +345,24 @@ function barkNotify(text, desp, params = {}) {
try {
const data = JSON.parse(res.body);
if (data.code === 200) {
log.info('发送通知','Bark APP发送通知消息成功\n')
log.info('发送通知', 'Bark APP发送通知消息成功')
} else {
log.error('发送通知',`${data.message}\n`);
log.error('发送通知', `${data.message}`);
}
} catch (error) {
log.error('发送通知',error);
log.error('发送通知', error);
} finally {
resolve()
}
},
failure: err => {
log.error('发送通知','Bark APP发送通知调用API失败!!\n');
log.error('发送通知', 'Bark APP发送通知调用API失败!!');
resolve();
throw new Error(err)
}
})
} else {
log.warn('发送通知','您未提供Bark的APP推送BARK_PUSH,取消Bark推送消息通知\n');
log.debug('发送通知', '您未提供Bark的APP推送BARK_PUSH,取消Bark推送消息通知');
resolve()
}
})
@@ -391,20 +391,20 @@ function tgBotNotify(text, desp) {
try {
const data = JSON.parse(res.body);
if (data.ok) {
log.info('发送通知','Telegram发送通知消息完成。\n')
log.info('发送通知', 'Telegram发送通知消息完成。')
} else if (data.error_code === 400) {
log.error('发送通知','请主动给bot发送一条消息并检查接收用户ID是否正确。\n')
log.error('发送通知', '请主动给bot发送一条消息并检查接收用户ID是否正确。')
} else if (data.error_code === 401) {
log.error('发送通知','Telegram bot token 填写错误。\n')
log.error('发送通知', 'Telegram bot token 填写错误。')
}
} catch (error) {
log.error('发送通知',error);
log.error('发送通知', error);
} finally {
resolve()
}
},
failure: err => {
log.error('发送通知','telegram发送通知消息失败!!\n')
log.error('发送通知', 'telegram发送通知消息失败!!')
resolve()
throw new Error(err)
}
@@ -415,9 +415,9 @@ function tgBotNotify(text, desp) {
port: TG_PROXY_PORT * 1
}
}
HttpRequest(options)
send(options)
} else {
log.warn('发送通知','您未提供telegram机器人推送所需的TG_BOT_TOKEN和TG_USER_ID,取消telegram推送消息通知\n');
log.debug('发送通知', '您未提供telegram机器人推送所需的TG_BOT_TOKEN和TG_USER_ID,取消telegram推送消息通知');
resolve()
}
})
@@ -431,7 +431,7 @@ function ddBotNotify(text, desp) {
const hmac = crypto.createHmac('sha256', DD_BOT_SECRET);
hmac.update(`${dateNow}\n${DD_BOT_SECRET}`);
const result = encodeURIComponent(hmac.digest('Util64'));
HttpRequest({
send({
method: 'POST',
url: `https://oapi.dingtalk.com/robot/send`,
query: {
@@ -456,23 +456,23 @@ function ddBotNotify(text, desp) {
try {
const data = JSON.parse(res.body);
if (data.errcode === 0) {
log.info('发送通知','钉钉发送通知消息完成。\n')
log.info('发送通知', '钉钉发送通知消息完成。')
} else {
log.error('发送通知',`${data.errmsg}\n`)
log.error('发送通知', `${data.errmsg}`)
}
} catch (e) {
log.error('发送通知',e);
log.error('发送通知', e);
} finally {
resolve();
}
},
failure: err => {
log.error('发送通知','钉钉发送通知消息失败!!\n')
log.error('发送通知', '钉钉发送通知消息失败!!')
throw new Error(err);
}
})
} else if (DD_BOT_TOKEN) {
HttpRequest({
send({
method: 'POST',
url: `https://oapi.dingtalk.com/robot/send`,
query: {
@@ -495,24 +495,24 @@ function ddBotNotify(text, desp) {
try {
const data = JSON.parse(res.body);
if (data.errcode === 0) {
log.info('发送通知','钉钉发送通知消息完成。\n')
log.info('发送通知', '钉钉发送通知消息完成。')
} else {
log.error('发送通知',`${data.errmsg}\n`)
log.error('发送通知', `${data.errmsg}`)
}
} catch (e) {
log.error('发送通知',e);
log.error('发送通知', e);
} finally {
resolve();
}
},
failure: err => {
log.error('发送通知','钉钉发送通知消息失败!!\n');
log.error('发送通知', '钉钉发送通知消息失败!!');
resolve();
throw new Error(err)
}
})
} else {
log.warn('发送通知','您未提供钉钉机器人推送所需的DD_BOT_TOKEN或者DD_BOT_SECRET,取消钉钉推送消息通知\n');
log.debug('发送通知', '您未提供钉钉机器人推送所需的DD_BOT_TOKEN或者DD_BOT_SECRET,取消钉钉推送消息通知');
resolve()
}
})
@@ -521,7 +521,7 @@ function ddBotNotify(text, desp) {
function qywxBotNotify(text, desp) {
return new Promise(resolve => {
if (QYWX_KEY) {
HttpRequest({
send({
method: 'POST',
url: `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${QYWX_KEY}`,
contents: {
@@ -541,24 +541,24 @@ function qywxBotNotify(text, desp) {
try {
const data = JSON.parse(res.body);
if (data.errcode === 0) {
log.info('发送通知','企业微信发送通知消息完成。\n');
log.info('发送通知', '企业微信发送通知消息完成。');
} else {
log.error('发送通知',`${data.errmsg}\n`);
log.error('发送通知', `${data.errmsg}`);
}
} catch (e) {
log.error('发送通知',e);
log.error('发送通知', e);
} finally {
resolve();
}
},
failure: err => {
log.error('发送通知','企业微信发送通知消息失败!!\n');
log.error('发送通知', '企业微信发送通知消息失败!!');
resolve();
throw new Error(err)
}
})
} else {
log.warn('发送通知','您未提供企业微信机器人推送所需的QYWX_KEY,取消企业微信推送消息通知\n');
log.debug('发送通知', '您未提供企业微信机器人推送所需的QYWX_KEY,取消企业微信推送消息通知');
resolve();
}
});
@@ -570,11 +570,11 @@ function iGotNotify(text, desp, params = {}) {
// 校验传入的IGOT_PUSH_KEY是否有效
const IGOT_PUSH_KEY_REGX = new RegExp("^[a-zA-Z0-9]{24}$")
if (!IGOT_PUSH_KEY_REGX.test(IGOT_PUSH_KEY)) {
log.error('发送通知','您所提供的IGOT_PUSH_KEY无效\n')
log.error('发送通知', '您所提供的IGOT_PUSH_KEY无效')
resolve()
return
}
HttpRequest({
send({
method: 'POST',
url: `https://push.hellyw.com/${IGOT_PUSH_KEY.toLowerCase()}`,
contents: {
@@ -593,24 +593,24 @@ function iGotNotify(text, desp, params = {}) {
try {
const data = JSON.parse(res.body);
if (data.ret === 0) {
log.info('发送通知','iGot发送通知消息成功\n')
log.info('发送通知', 'iGot发送通知消息成功')
} else {
log.error('发送通知',`iGot发送通知消息失败:${data.errMsg}\n`)
log.error('发送通知', `iGot发送通知消息失败:${data.errMsg}`)
}
} catch (e) {
log.error('发送通知',e);
log.error('发送通知', e);
} finally {
resolve();
}
},
failure: err => {
log.error('发送通知','iGot 发送通知调用API失败!!\n')
log.error('发送通知', 'iGot 发送通知调用API失败!!')
resolve();
throw new Error(err)
}
})
} else {
log.warn('发送通知','您未提供iGot的推送IGOT_PUSH_KEY,取消iGot推送消息通知\n');
log.debug('发送通知', '您未提供iGot的推送IGOT_PUSH_KEY,取消iGot推送消息通知');
resolve()
}
})
@@ -619,7 +619,7 @@ function iGotNotify(text, desp, params = {}) {
function pushPlusNotify(text, desp) {
return new Promise(resolve => {
if (PUSH_PLUS_TOKEN) {
HttpRequest({
send({
method: 'POST',
url: 'https://pushplus.hxtrip.com/send',
contents: {
@@ -639,24 +639,24 @@ function pushPlusNotify(text, desp) {
try {
const data = JSON.parse(res.body);
if (data.code === 200) {
log.info('发送通知',`push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息完成。\n`)
log.info('发送通知', `push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息完成。`)
} else {
log.error('发送通知',`push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息失败:${data.msg}\n`)
log.error('发送通知', `push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息失败:${data.msg}`)
}
} catch (e) {
log.error('发送通知',e);
log.error('发送通知', e);
} finally {
resolve();
}
},
failure: err => {
log.error('发送通知',`push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息失败!!\n`)
log.error('发送通知', `push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息失败!!`)
resolve();
throw new Error(err)
}
})
} else {
log.warn('发送通知','您未提供push+推送所需的PUSH_PLUS_TOKEN,取消push+推送消息通知\n');
log.debug('发送通知', '您未提供push+推送所需的PUSH_PLUS_TOKEN,取消push+推送消息通知');
resolve()
}
})
@@ -679,15 +679,13 @@ async function email(text, desp) {
text: desp,
})
} catch (e) {
log.error('发送通知',`email发送失败 原因: ${e.message}`);
log.error('发送通知', `email发送失败 原因: ${e.message}`);
return
}
log.info('发送通知','email发送成功');
log.info('发送通知', 'email发送成功');
} else {
log.warn('发送通知','您未提供email推送所需的所有参数故取消email推送消息通知\n');
log.debug('发送通知', '您未提供email推送所需的所有参数故取消email推送消息通知');
}
}
module.exports = {
sendNotify
}
module.exports = { sendNotify }
+27
View File
@@ -0,0 +1,27 @@
const { isMe } = require('./check');
const { clear } = require('./clear');
const { start } = require('./lottery');
const { update } = require('./update');
const global_var = require('./data/global_var')
const bili = require('./net/bili')
const { log } = require('./utils')
const { sendNotify } = require('./helper/notify');
/**
* 检查cookie是否有效
* @param {string} num
*/
async function checkCookie(num) {
const My_UID = global_var.get("myUID");
if (await bili.getMyinfo()) {
log.info('Cookie有效性检测', `成功登录 UID:${My_UID}`);
return true;
} else {
log.error('Cookie有效性检测', `登录失败 COOKIE${num} 已失效 UID:${My_UID}`);
await sendNotify('动态抽奖出错-登录失败', `COOKIE${num} 已失效 UID:${My_UID}`)
return false;
}
}
module.exports = { start, isMe, clear, update, checkCookie }
-154
View File
@@ -1,154 +0,0 @@
const Util = require('./Util');
const BiliAPI = require('./BiliAPI');
const eventBus = require('./eventBus');
const GlobalVar = require('./GlobalVar');
const Public = require('./Public');
const Monitor = require('./Monitor');
const { sendNotify } = require('./sendNotify');
const config = require('./config');
const { log } = Util;
async function createRandomDynamic(num) {
if (config.create_dy) {
log.info('随机动态', `准备创建${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(Util.getRandomOne(config.dy_contents));
await Util.delay(2000);
}
} else {
log.info('随机动态', '已有非抽奖动态故无需创建');
}
}
}
/**
* 抽奖主函数
* @param {string} cookie
* @returns {Promise<void>}
*/
function start() {
return new Promise(resolve => {
let times = Util.counter();
/* 注册事件 */
eventBus.on('Turn_on_the_Monitor', async () => {
const lotterys = GlobalVar.get("Lottery");
if (lotterys.length === 0) {
log.info('抽奖', '抽奖信息为空');
resolve();
return;
}
if (times.value() === lotterys.length) {
await createRandomDynamic(config.create_dy_num);
log.info('抽奖', '所有动态转发完毕');
times.clear();
eventBus.emit('Turn_off_the_Monitor', '目前无抽奖信息,过一会儿再来看看吧')
return;
}
const lottery = lotterys[times.next()];
await (new Monitor(lottery)).init();
});
eventBus.on('Turn_off_the_Monitor', async (msg) => {
await createRandomDynamic(config.create_dy_num);
log.info('结束抽奖', '原因: ' + msg);
eventBus.flush();
resolve();
})
eventBus.emit('Turn_on_the_Monitor');
});
}
/**
* 是否中奖
*/
async function isMe() {
let desp = '';
const UnreadAtNum = await BiliAPI.getUnreadAtNum();
const UnreadSessionNum = await BiliAPI.getUnreadSessionNum();
const { follow_unread, unfollow_unread } = UnreadSessionNum || { unfollow_unread: 0, follow_unread: 0 };
if (UnreadAtNum > 0) {
log.info('中奖检测', '<-- 正在检查at');
const MyAtInfo = await BiliAPI.getMyAtInfo();
MyAtInfo.forEach(async AtInfo => {
const { at_time, up_uname, business, source_content, url } = AtInfo
desp += `发生时间: ${new Date(at_time * 1000).toLocaleString()} \n\n`
desp += `用户: ${up_uname} \n\n`
desp += `${business}中@了你(${GlobalVar.get("myUID")}) \n\n`
desp += `原内容为: ${source_content} \n\n`
desp += `[直达链接](${url}) \n\n`
desp += `\n\n`
});
log.info('中奖检测', '--> OK');
}
if (follow_unread + unfollow_unread > 0) {
const check = async (type) => {
let session_t = '';
let MySession = await BiliAPI.getSessionInfo(type)
for (const index of Util.infiniteNumber()) {
for (const Session of MySession.data) {
const { content, sender_uid, session_ts, timestamp, talker_id } = Session;
session_t = session_ts;
if (talker_id) {
BiliAPI.updateSessionStatus(talker_id);
await Util.delay(1000);
if (config.notice_key_words.some(it => new RegExp(it).test(content))) {
desp += `发生时间: ${new Date(timestamp * 1000).toLocaleString()} \n\n`
desp += `用户: ${sender_uid} \n\n`
desp += `私信你(${GlobalVar.get("myUID")})说: ${content} \n\n`
desp += `[直达链接](https://message.bilibili.com/#/whisper/mid${sender_uid}) \n\n`
desp += `\n\n`
}
}
}
if (MySession.has_more && index < 16) {
await Util.delay(3e3);
MySession = await BiliAPI.getSessionInfo(type, session_t)
} else {
break
}
}
}
if (follow_unread) {
log.info('中奖检测', '<-- 正在检查已关注者的私信')
await check(1)
}
if (unfollow_unread) {
log.info('中奖检测', '<-- 正在检查未关注者的私信')
await check(2)
}
log.info('中奖检测', '--> OK');
}
if (desp) {
desp += '中奖了别忘给脚本(https://github.com/shanmiteko/LotteryAutoScript)点一个Star哦, 赞助一两块也不是不可以‍_(:з」∠)_\n\n'
log.info(desp);
await sendNotify('可能中奖了', desp);
} else {
log.info('中奖检测', "未中奖");
}
return;
}
/**
* 检查cookie是否有效
* @param {string} num
*/
async function checkCookie(num) {
const My_UID = GlobalVar.get("myUID");
if (await BiliAPI.getMyinfo()) {
log.info('Cookie有效性检测', `成功登录 UID:${My_UID}`);
return true;
} else {
log.error('Cookie有效性检测', `登录失败 COOKIE${num} 已失效 UID:${My_UID}`);
await sendNotify('动态抽奖出错-登录失败', `COOKIE${num} 已失效 UID:${My_UID}`)
return false;
}
}
module.exports = {
start,
isMe,
checkCookie
}
+63
View File
@@ -0,0 +1,63 @@
const utils = require('./utils');
const bili = require('./net/bili');
const event_bus = require('./helper/event_bus');
const global_var = require('./data/global_var');
const { Searcher } = require('./core/searcher');
const { Monitor } = require('./core/monitor');
const config = require('./data/config');
const { log } = utils;
async function createRandomDynamic(num) {
if (config.create_dy) {
log.info('随机动态', `准备创建${num}条随机动态`);
const Dynamic = await Searcher.checkAllDynamic(global_var.get("myUID"), 1);
if ((Dynamic.allModifyDynamicResArray[0] || { type: 0 }).type === 1) {
for (let index = 0; index < num; index++) {
await bili.createDynamic(utils.getRandomOne(config.dy_contents));
await utils.delay(2000);
}
} else {
log.info('随机动态', '已有非抽奖动态故无需创建');
}
}
}
/**
* 抽奖主函数
* @param {string} cookie
* @returns {Promise<void>}
*/
function start() {
return new Promise(resolve => {
let times = utils.counter();
/* 注册事件 */
event_bus.on('Turn_on_the_Monitor', async () => {
const lotterys = global_var.get("Lottery");
if (lotterys.length === 0) {
log.info('抽奖', '抽奖信息为空');
resolve();
return;
}
if (times.value() === lotterys.length) {
await createRandomDynamic(config.create_dy_num);
log.info('抽奖', '所有动态转发完毕');
times.clear();
event_bus.emit('Turn_off_the_Monitor', '目前无抽奖信息,过一会儿再来看看吧')
return;
}
const lottery = lotterys[times.next()];
await (new Monitor(lottery)).init();
});
event_bus.on('Turn_off_the_Monitor', async (msg) => {
await createRandomDynamic(config.create_dy_num);
log.info('结束抽奖', '原因: ' + msg);
event_bus.flush();
resolve();
})
event_bus.emit('Turn_on_the_Monitor');
});
}
module.exports = { start }
+32
View File
@@ -0,0 +1,32 @@
module.exports = Object.freeze({
DYNAMIC_LIKE_THUMB: 'https://api.vc.bilibili.com/dynamic_like/v1/dynamic_like/thumb',
DYNAMIC_REPOST_REPOST: 'https://api.vc.bilibili.com/dynamic_repost/v1/dynamic_repost/repost',
DYNAMIC_SVR_CREATE_DRAW: 'https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/create_draw',
DYNAMIC_SVR_CREATE: 'https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/create',
DYNAMIC_SVR_GET_DYNAMIC_DETAIL: 'https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/get_dynamic_detail',
DYNAMIC_SVR_RM_DYNAMIC: 'https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/rm_dynamic',
DYNAMIC_SVR_SPACE_HISTORY: 'https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history',
FEED_GET_ATTENTION_LIST: 'https://api.vc.bilibili.com/feed/v1/feed/get_attention_list',
FEED_SETUSERFOLLOW: 'https://api.vc.bilibili.com/feed/v1/feed/SetUserFollow',
LOTTERY_SVR_LOTTERY_NOTICE: 'https://api.vc.bilibili.com/lottery_svr/v1/lottery_svr/lottery_notice',
MSGFEED_AT: 'https://api.bilibili.com/x/msgfeed/at',
MSGFEED_UNREAD: 'https://api.bilibili.com/x/msgfeed/unread',
READ_CV: 'https://www.bilibili.com/read/cv{{cv}}',
RELATION_BATCH_MODIFY: 'https://api.bilibili.com/x/relation/batch/modify',
RELATION_MODIFY: 'https://api.bilibili.com/x/relation/modify',
RELATION_STAT: 'https://api.bilibili.com/x/relation/stat',
RELATION_TAG_CREATE: 'https://api.bilibili.com/x/relation/tag/create',
RELATION_TAG: 'https://api.bilibili.com/x/relation/tag',
RELATION_TAGS_ADDUSERS: 'https://api.bilibili.com/x/relation/tags/addUsers',
RELATION_TAGS: 'https://api.bilibili.com/x/relation/tags',
REPLY_ADD: 'https://api.bilibili.com/x/v2/reply/add',
SESSION_SVR_GET_SESSIONS: 'https://api.vc.bilibili.com/session_svr/v1/session_svr/get_sessions',
SESSION_SVR_SINGLE_UNREAD: 'https://api.vc.bilibili.com/session_svr/v1/session_svr/single_unread',
SESSION_SVR_UPDATE_ACK: 'https://api.vc.bilibili.com/session_svr/v1/session_svr/update_ack',
SPACE_MYINFO: 'https://api.bilibili.com/x/space/myinfo',
TAG_INFO: 'https://api.bilibili.com/x/tag/info',
TOPIC_SVR_TOPIC_HISTORY: 'https://api.vc.bilibili.com/topic_svr/v1/topic_svr/topic_history',
TOPIC_SVR_TOPIC_NEW: 'https://api.vc.bilibili.com/topic_svr/v1/topic_svr/topic_new',
WEB_INTERFACE_CARD: 'https://api.bilibili.com/x/web-interface/card',
WEB_INTERFACE_SEARCH_TYPE: 'https://api.bilibili.com/x/web-interface/search/type',
})
+863
View File
@@ -0,0 +1,863 @@
const GlobalVar = require('../data/global_var');
const { strToJson, log } = require('../utils');
const { send } = require('./http');
const API = require('./api.bili');
/**
* GET请求
* @param {import('./http').RequestOptions} param0
* @returns {Promise<string>}
*/
function get({ url, config, contents, query }) {
return new Promise((resolve) => {
send({
url,
method: 'GET',
config,
headers: {
"accept": 'application/json, text/plain, */*',
"cookie": GlobalVar.get("cookie")
},
query,
contents,
success: res => resolve(res.body),
failure: err => resolve(err)
})
})
}
/**
* POST请求
* @param {import('./http').RequestOptions} param0
* @returns {Promise<string>}
*/
function post({ url, config, contents, query }) {
return new Promise((resolve) => {
send({
url,
method: 'POST',
config,
headers: {
"accept": 'application/json, text/plain, */*',
"content-type": 'application/x-www-form-urlencoded; charset=utf-8',
"cookie": GlobalVar.get("cookie")
},
query,
contents,
success: res => resolve(res.body),
failure: err => resolve(err)
})
})
}
/**
* 网络请求
*/
const bili_client = {
/**
* 判断是否成功登录
* @returns {Promise<boolean>}
*/
async getMyinfo() {
return get({
url: API.SPACE_MYINFO
}).then(responseText => {
let res = strToJson(responseText);
if (res.code === 0) {
return true;
} else {
return false;
}
})
},
/**
* 获取被at的信息
* @typedef AtInfo
* @property {number} at_time
* @property {string} up_uname
* @property {string} business
* @property {string} source_content
* @property {string} url
* @returns {Promise<AtInfo[]>}
*/
async getMyAtInfo() {
return get({
url: API.MSGFEED_AT
}).then(responseText => {
const res = strToJson(responseText);
const atInfo = [];
if (res.code === 0) {
const items = res.data.items;
if (items.length !== 0) {
items.forEach(i => {
const { at_time, item, user } = i
, { nickname: up_uname } = user
, { business, uri: url, source_content } = item;
atInfo.push({
at_time,
up_uname,
business,
source_content,
url
});
});
}
return atInfo;
} else {
return atInfo;
}
})
},
/**
* 获取未读@
* @returns {Promise<number>}
*/
async getUnreadAtNum() {
return get({
url: API.MSGFEED_UNREAD
}).then(responseText => {
let res = strToJson(responseText);
if (res.code === 0) {
const { at } = res.data;
log.info('获取未读@', `成功 数量: ${at}`)
return at
} else {
log.error('获取未读@', `失败\n${responseText}`)
return -1
}
})
},
/**
* 获取私信
* @typedef SessionData
* @property {string} session_ts
* @property {string} content
* @property {number} timestamp
* @property {number} unread_count
* @property {number} sender_uid
* @property {number} talker_id
* @property {number} msg_seqno
*
* @typedef SessionInfo
* @property {number} has_more
* @property {SessionData[]} data
*
* @param {number} session_type 1 已关注 2 未关注 3 应援团
* @param {string} [ts_16]
* @returns {Promise<SessionInfo>}
*/
async getSessionInfo(session_type, ts_16 = '') {
return get({
url: API.SESSION_SVR_GET_SESSIONS,
query: {
session_type,
end_ts: ts_16,
}
}).then(responseText => {
let res = strToJson(responseText);
if (res.code === 0) {
log.info('获取一页私信(20)', '成功 ' + (ts_16 ? 'end_ts->' + ts_16 : '第一页'));
/**@type {Array} */
const sessions = res.data.session_list || [];
const has_more = res.data.has_more;
const data = sessions.map(session => {
const { session_ts, last_msg, unread_count, talker_id } = session;
const { content = '', timestamp = 0, sender_uid = 0, msg_seqno } = last_msg || {};
return { session_ts, content, timestamp, sender_uid, unread_count, talker_id, msg_seqno }
})
return { has_more, data }
} else if (res.code === 2) {
log.error('获取私信', `API抽风...请再次尝试`);
return { has_more: 0, data: [] }
} else {
log.error('获取私信', `失败\n${responseText}`);
return { has_more: 0, data: [] }
}
})
},
/**
* 获取未读私信数量
* @returns {Promise<{ unfollow_unread: number, follow_unread: number }>}
*/
async getUnreadSessionNum() {
return get({
url: API.SESSION_SVR_SINGLE_UNREAD
}).then(responseText => {
let res = strToJson(responseText);
if (res.code === 0) {
const { unfollow_unread, follow_unread } = res.data;
log.info('获取未读私信', `成功 已关注未读数: ${follow_unread}, 未关注未读数 ${unfollow_unread}`);
return { unfollow_unread, follow_unread }
} else {
log.error('获取未读私信', `失败\n${responseText}`);
return null
}
})
},
/**
* 私信已读
* @param {number} talker_id
* @param {number} session_type
* @param {number} msg_seqno
*/
updateSessionStatus(talker_id, session_type, msg_seqno) {
return post({
url: API.SESSION_SVR_UPDATE_ACK,
config: {
retry: false
},
contents: {
talker_id,
session_type,
ack_seqno: msg_seqno,
csrf_token: GlobalVar.get("csrf"),
csrf: GlobalVar.get("csrf")
}
}).then(responseText => {
let res = strToJson(responseText);
if (res.code === 0) {
log.info('私信已读', `成功 -> talker_id: ${talker_id}`);
} else {
log.error('私信已读', `失败 -> talker_id: ${talker_id}\n${responseText}`);
}
})
},
/**
* 获取关注列表
* @param {number} uid
* @returns {Promise<string | null>}
*/
getAttentionList(uid) {
return get({
url: API.FEED_GET_ATTENTION_LIST,
query: {
uid
}
}).then(responseText => {
let res = strToJson(responseText);
if (res.code === 0) {
log.info('获取关注列表', '成功');
return res.data.list.toString()
} else {
log.error('获取关注列表', `失败\n${responseText}`);
return null
}
})
},
/**
* 获取一个动态的细节
* @param {string} dynamic_id
* @return {Promise<string>}
*/
getOneDynamicByDyid(dynamic_id) {
return get({
url: API.DYNAMIC_SVR_GET_DYNAMIC_DETAIL,
query: {
dynamic_id
}
})
},
/**
* 获取一组动态的信息
* @param {number} host_uid 被查看者的uid
* @param {string} offset_dynamic_id 此动态偏移量 初始为 0
* @returns {Promise<string>}
*/
getOneDynamicInfoByUID(host_uid, offset_dynamic_id) {
/* 鉴别工作交由modifyDynamicRes完成 */
return get({
url: API.DYNAMIC_SVR_SPACE_HISTORY,
query: {
visitor_uid: GlobalVar.get("myUID"),
host_uid,
offset_dynamic_id,
},
config: {
retry: false
}
})
},
/**
* 通过tag名获取tag的id
* @param {string} tag_name
* tag名
* @returns {Promise<number | -1>}
* 正确:tag_ID
* 错误:-1
*/
getTagIDByTagName(tag_name) {
return get({
url: API.TAG_INFO,
query: {
tag_name
}
}).then(responseText => {
const res = strToJson(responseText);
if (res.code !== 0) {
log.error('获取TagID', '失败');
return -1
} else {
return res.data.tag_id
}
})
},
/**
* 获取tag下的热门动态以及一条最新动态
* @param {number} tagid
* @returns {Promise<string>}
*/
getHotDynamicInfoByTagID(tagid) {
return get({
url: API.TOPIC_SVR_TOPIC_NEW,
query: {
topic_id: tagid
}
})
},
/**
* 获取tag下的最新动态
* @param {string} tagname
* @param {string} offset
* @returns {Promise<string>}
*/
getOneDynamicInfoByTag(tagname, offset) {
return get({
url: API.TOPIC_SVR_TOPIC_HISTORY,
query: {
topic_name: tagname,
offset_dynamic_id: offset
},
config: {
retry: false
}
})
},
/**
* 搜索专栏
* @param {string} keyword
* @return {Promise<Array<number>>}
*/
searchArticlesByKeyword(keyword) {
return get({
url: API.WEB_INTERFACE_SEARCH_TYPE,
query: {
keyword,
page: 1,
order: 'pubdate',
search_type: 'article'
}
}).then(responseText => {
const res = JSON.parse(responseText);
if (res.code === 0) {
log.info('搜索专栏', '成功 关键词: ' + keyword)
return res.data.result.map(it => it.id)
} else {
log.error('搜索专栏', '失败 原因:\n' + responseText)
return []
}
})
},
/**
* 获取专栏内容
* @param {number} cv
* @returns {Promise<string>}
*/
getOneArticleByCv(cv) {
return get({
url: API.READ_CV.replace('{{cv}}', cv)
})
},
/**
* 获取粉丝数
* @param {number} uid
* @returns {Promise<number | -1>}
*/
getUserInfo(uid) {
return get({
url: API.WEB_INTERFACE_CARD,
query: {
mid: uid,
photo: false
},
config: {
retry: false
}
}).then(responseText => {
const res = strToJson(responseText);
if (res.code === 0) {
return res.data.follower
} else {
log.warn('获取粉丝数', '尝试切换线路');
return get({
url: API.RELATION_STAT,
query: {
vmid: uid
}
}).then(responseText => {
const res = strToJson(responseText);
if (res.code === 0) {
log.info('获取粉丝数', 'ok');
return res.data.follower
} else {
log.error('获取粉丝数', `出错 可能是访问过频繁\n${responseText}`);
return -1
}
})
}
})
},
/**
* 获取开奖信息
* @param {string} dyid
* 动态id
* @typedef LotteryNotice
* @property {number | -1} ts
* @property {string | "获取开奖信息失败"} text
* @property {string | "null"} item
* @property {string | "未知"} isMe
* @returns {Promise<LotteryNotice>} 开奖时间
*/
getLotteryNotice(dyid) {
return get({
url: API.LOTTERY_SVR_LOTTERY_NOTICE,
query: {
dynamic_id: dyid
}
}).then(responseText => {
const res = strToJson(responseText);
/(?<=_prize_cmt":").*(?=")/.exec();
if (res.code === 0) {
const timestamp10 = res.data.lottery_time,
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;
})();
let isMeB = (new RegExp(GlobalVar.get("myUID"))).test(responseText);
const isMe = isMeB ? '中奖了!!!' : '未中奖';
const iteminfo = res.data.first_prize_cmt || '' + ' ' + res.data.second_prize_cmt || '' + ' ' + res.data.third_prize_cmt || '';
return {
ts: timestamp10,
text: `开奖时间: ${time.toLocaleString()} ${remain}`,
item: iteminfo,
isMe: isMe
};
} else {
log.error('获取开奖信息', `失败\n${responseText}`);
return {
ts: -1,
text: '获取开奖信息失败',
item: 'null',
isMe: '未知'
};
}
})
},
/**
* 之前不检查是否重复关注
* 自动关注
* 并转移分组
* @param {Number} uid
* 被关注者的UID
* @returns {Promise<number>}
* 0 - 成功
* 1 - 失败
* 2 - 异常
*/
autoAttention(uid) {
return post({
url: API.RELATION_MODIFY,
config: {
retry: false
},
contents: {
fid: uid,
act: 1,
re_src: 0,
csrf: GlobalVar.get("csrf")
}
}).then(responseText => {
let _responseText = ''
/* 重复关注code also equal 0 */
const res = strToJson(responseText)
_responseText += responseText
if (res.code === 0) {
log.info('自动关注', '关注+1');
return 0
} else if (res.code === 22002) {
log.error('自动关注', '您已被对方拉入黑名单');
return 1
} else {
log.warn('自动关注', `失败 尝试切换线路\n${responseText}`);
_responseText += responseText
return post({
url: API.FEED_SETUSERFOLLOW,
contents: {
type: 1,
follow: uid,
csrf: GlobalVar.get("csrf")
}
}).then(responseText => {
if (/^{"code":0/.test(responseText)) {
log.info('自动关注', '关注+1');
return 0
} else {
log.warn('自动关注', `失败 尝试切换另一条线路\n${responseText}`);
_responseText += responseText
return post({
url: API.RELATION_BATCH_MODIFY,
contents: {
fid: uid,
act: 1,
re_src: 0,
csrf: GlobalVar.get("csrf")
}
}).then(responseText => {
if (/^{"code":0/.test(responseText)) {
log.info('自动关注', '关注+1');
return 0
} else {
log.error('自动关注', `失败\n${responseText}`);
_responseText += responseText
if (_responseText.includes(22015)) {
return 2
}
return 1
}
})
}
})
}
})
},
/**
* 移动分区
* @param {number} uid
* @param {number} tagid 关注分区的ID
* @returns {Promise<number>}
* 0 - 成功
* 1 - 失败
*/
movePartition(uid, tagid) {
return post({
url: API.RELATION_TAGS_ADDUSERS,
contents: {
fids: uid,
tagids: tagid,
csrf: GlobalVar.get("csrf")
}
}).then(responseText => {
/* 重复移动code also equal 0 */
if (/^{"code":0/.test(responseText)) {
log.info('移动分区', 'up主分区移动成功');
return 0
} else {
log.error('移动分区', `up主分区移动失败\n${responseText}`);
return 1
}
})
},
/**
* 取消关注
* @param {number} uid
* @returns {Promise<boolean>}
*/
cancelAttention(uid) {
return post({
url: API.RELATION_MODIFY,
config: {
retry: false
},
contents: {
fid: uid,
act: 2,
re_src: 0,
csrf: GlobalVar.get("csrf")
}
}).then(responseText => {
const res = strToJson(responseText);
if (res.code === 0) {
log.info('自动取关', `取关成功(${uid})`);
return true
} else {
log.error('自动取关', `取关失败(${uid})\n${responseText}`);
return false
}
})
},
/**
* 动态自动点赞
* @param {string} dyid
* @returns {Promise<number>}
* 0 - 成功
* 1 - 失败
*/
autolike(dyid) {
return post({
url: API.DYNAMIC_LIKE_THUMB,
contents: {
uid: GlobalVar.get("myUID"),
dynamic_id: dyid,
up: 1,
csrf: GlobalVar.get("csrf")
}
}).then(responseText => {
if (/^{"code":0/.test(responseText)) {
log.info('自动点赞', '点赞成功');
return 0
} else {
log.error('自动点赞', `点赞失败\n${responseText}`);
return 1
}
})
},
/**
* 转发前应查看是否重复转发
* 自动转发
* @param {Number} uid
* 自己的UID
* @param {string} dyid
* @param {string} [msg]
* 动态的ID
* @returns {Promise<number>}
* 0 - 成功
* 1 - 失败
*/
autoRelay(uid, dyid, msg = '转发动态', ctrl = '[]') {
const len = msg.length;
if (len > 233) {
msg = msg.slice(0, 233 - len)
}
return post({
url: API.DYNAMIC_REPOST_REPOST,
config: {
retry: false
},
contents: {
uid: `${uid}`,
dynamic_id: dyid,
content: msg,
ctrl,
csrf: GlobalVar.get("csrf")
}
}).then(responseText => {
if (/^{"code":0/.test(responseText)) {
log.info('转发动态', '成功转发一条动态');
return 0
} else {
log.error('转发动态', `转发动态失败\n${responseText}`);
return 1
}
})
},
/**
* @typedef Picture
* @property {string} img_src
* @property {number} img_width
* @property {number} img_height
* 发布一条动态
* @param { string | Picture[] } content
* @return {Promise<void>}
*/
createDynamic(content) {
let contents = {
csrf: GlobalVar.get("csrf"),
extension: '{"emoji_type":1,"from":{"emoji_type":1},"flag_cfg":{}}'
}
let url = '';
if (content instanceof Array) {
url = API.DYNAMIC_SVR_CREATE_DRAW
contents = {
...contents,
biz: 3,
category: 3,
pictures: JSON.stringify(content)
}
} else {
url = API.DYNAMIC_SVR_CREATE
contents = {
...contents,
content,
}
}
return post({
url,
contents,
}).then(responseText => {
if (/^{"code":0/.test(responseText)) {
log.info('发布动态', '成功创建一条随机内容的动态');
} else {
log.error('发布动态', `发布动态失败\n${responseText}`);
}
})
},
/**
* 移除动态
* @param {string} dyid
* @returns {Promise<boolean>}
*/
rmDynamic(dyid) {
return post({
url: API.DYNAMIC_SVR_RM_DYNAMIC,
contents: {
dynamic_id: dyid,
csrf: GlobalVar.get("csrf")
},
config: {
retry: false
}
}).then(responseText => {
if (/^{"code":0/.test(responseText)) {
log.info('删除动态', `成功删除一条动态(${dyid})`);
return true
} else {
log.error('删除动态', `删除动态失败(${dyid})\n${responseText}`);
return false
}
})
},
/**
* 发送评论
* @param {string} rid
* cid_str
* @param {string} msg
* @param {number} type
* 1(视频)
* 11(有图)
* 17(无图)
* @returns {Promise<number>}
* - 成功 0
* - 失败 1
* - 黑名单 -1
*/
sendChat(rid, msg, type, show = true) {
return post({
url: API.REPLY_ADD,
contents: {
oid: rid,
type: type,
message: msg,
csrf: GlobalVar.get("csrf")
}
}).then(responseText => {
const res = strToJson(responseText);
if (res.code === 0) {
show && log.info('自动评论', '评论成功');
return 0
} else if (res.code === -404) {
show && log.error('自动评论', '原动态已删除');
return 0
} else if (res.code === 12002) {
show && log.error('自动评论', '评论区已关闭');
return 0
} else if (res.code === 12015) {
show && log.error('自动评论', '需要输入验证码');
return 1
} else if (res.code === 12053) {
show && log.error('自动评论', '黑名单用户无法互动');
return -1
} else {
show && log.error('自动评论', `评论失败\n${responseText}`);
return 1
}
})
},
/**
* 检查分区
* 不存在指定分区时创建
* 获取到tagid添加为对象的属性
* @param {string} [name]
* @returns {Promise<number>}
*/
checkMyPartition(name) {
if (!name) name = '此处存放因抽奖临时关注的up';
return get({
url: API.RELATION_TAGS
}).then(responseText => {
const res = strToJson(responseText);
let tagid = undefined;
if (res.code === 0) {
const data = res.data.filter((it) => it.name === name);
if (data.length) {
log.info('获取分区id', '成功');
tagid = data[0].tagid
} else {
log.warn('获取分区id', '失败 无指定分区');
}
if (name === '此处存放因抽奖临时关注的up') {
if (typeof tagid === 'undefined') {
return bili_client.createPartition(name)
} else {
return tagid
}
} else {
return tagid
}
} else {
log.error('获取分区id', `访问出错 可在my_config里手动填入\n${responseText}`)
return tagid
}
})
},
/**
* 创造分区
* @param {string} partition_name
* @returns {Promise<number>}
*/
createPartition(partition_name) {
return post({
url: API.RELATION_TAG_CREATE,
contents: {
tag: partition_name,
csrf: GlobalVar.get("csrf")
}
}).then(responseText => {
let obj = strToJson(responseText);
if (obj.code === 0) {
log.info('新建分区', '分区新建成功')
/* 获取tagid */
let { tagid } = obj.data
return tagid
} else {
log.error('新建分区', `分区新建失败\n${responseText}`);
return undefined
}
})
},
/**
* 获取一个分区中50个的id
* @param {number} tagid
* @param {number} n 1->
* @returns {Promise<number[]>}
*/
getPartitionUID(tagid, n) {
return get({
url: API.RELATION_TAG,
query: {
mid: GlobalVar.get("myUID"),
tagid: tagid,
pn: n,
ps: 50
}
}).then(responseText => {
const res = strToJson(responseText);
let uids = [];
if (res.code === 0) {
res.data.forEach(d => {
uids.push(d.mid);
})
log.info(`获取分组${tagid}`, `成功获取取关分区列表${n}`);
return uids
} else {
log.error(`获取分组${tagid}`, `获取取关分区列表失败\n${responseText}`);
return uids
}
})
}
};
module.exports = bili_client
+17 -18
View File
@@ -14,11 +14,6 @@
* @param {string} err
* @returns {void}
*
* @typedef Proxy
* @property {string} hostname
* @property {string} [host]
* @property {number} port
*
* @typedef RequestConfig
* @property {number} [timeout] 超时
* @property {number} [wait] 错误等待
@@ -27,16 +22,16 @@
* @property {number} [retry_times] 重试次数
*
* @typedef {object} RequestOptions Http请求选项
* @property {string} method 请求方法
* @property {string} [method] 请求方法
* @property {string} url 完整链接
* @property {boolean} stream 是否流式数据
* @property {boolean} [stream] 是否流式数据
* @property {RequestConfig} [config] 设置
* @property {Proxy} [proxy] 代理
* @property {string} [proxy] 代理 IP:PORT
* @property {Object.<string, string|number>} [query] 查询选项
* @property {Object.<string, string|number> | string} [contents] 内容
* @property {HttpHeaders} [headers] 请求头
* @property {SuccessCb} success 成功回调
* @property {FailureCb} failure 失败回调
* @property {SuccessCb} [success] 成功回调
* @property {FailureCb} [failure] 失败回调
*/
const { request: http_request } = require('http');
@@ -64,7 +59,7 @@ const DEFAULT_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=UTF-8';
* @param {RequestOptions} detail
* @returns {void}
*/
function HttpRequest(detail) {
function send(detail) {
detail = setDefault(detail);
const { method, url, stream, config, proxy, query, contents, headers, success, failure } = detail;
const { timeout, wait, retry, redirect, retry_times } = config;
@@ -86,9 +81,8 @@ function HttpRequest(detail) {
}
if (proxy) {
options.headers.host = thisURL.host;
[options.hostname, options.port] = proxy.host ?
proxy.host.split(':') : [proxy.hostname, proxy.port]
options.path = thisURL.href;
[options.hostname, options.port] = proxy.split(':');
}
const req = request(options, res => {
let protodata = '';
@@ -100,7 +94,7 @@ function HttpRequest(detail) {
detail.url = new URL(thisURL.origin + headers.location).href
}
console.log(`[重定向]状态码:${statusCode} location:${detail.url}`);
HttpRequest(detail)
send(detail)
return
}
if (stream) {
@@ -113,7 +107,7 @@ function HttpRequest(detail) {
console.log(`[不期待响应]原因:${err.message} 尝试重新请求中...`);
await delay(wait);
detail.config.retry_times = retry_times - 1;
HttpRequest(detail);
send(detail);
} else {
failure(`[响应错误]${err.message} 响应数据:\n${protodata}`)
}
@@ -132,7 +126,7 @@ function HttpRequest(detail) {
console.log(`[请求失败]原因:${err.message} 尝试重新连接中...`);
await delay(wait);
detail.config.retry_times = retry_times - 1;
HttpRequest(detail);
send(detail);
} else {
failure(`[请求失败]: ${err.message}`);
}
@@ -157,12 +151,17 @@ function formatContents(type, contents) {
/**
* 设置默认
* @param {RequestOptions} detail
* @param {RequestOptions} detail
* @returns {RequestOptions}
*/
function setDefault(detail) {
detail = {
method: 'GET',
stream: false,
proxy: '',
headers: {},
success: (res) => { console.log(res.headers) },
failure: (err) => { console.log(err) },
...detail
}
detail.config = {
@@ -190,4 +189,4 @@ function delay(time) {
}
module.exports = { HttpRequest }
module.exports = { send }
-40
View File
@@ -1,40 +0,0 @@
const Util = require("./Util");
const GlobalVar = require("./GlobalVar");
const config = require("./config");
const key_map = new Map([['DedeUserID', 'myUID'], ['bili_jct', 'csrf']]);
/**
* 生成全局变量文件
* 更新config
* @param {string} cookie
* @param {number} n
*/
async function setVariable(cookie, n) {
if (cookie) {
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]);
});
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 Util.createDir('dyids');
await Util.createFile(n < 2 ? 'dyid.txt' : `dyid${n}.txt`, '', 'a')
return
}
module.exports = { setVariable };
+75
View File
@@ -0,0 +1,75 @@
const { send } = require('./net/http')
const { strToJson, download } = require('./utils')
const { version, checkVersion, log } = require('./utils')
/**
* 获取下载链接
* @param {string} owner
* @param {string} repo
* @returns {Promise<{ download_url: string, text: string }>}
*/
function getLatestReleaseDownloadUrl(owner, repo) {
return new Promise((resolve, reject) => {
send({
url: `https://api.github.com/repos/${owner}/${repo}/releases/latest`,
headers: {
"accept": 'application/vnd.github.v3+json'
},
config: {
retry: false
},
success: ({ body }) => {
const { tag_name, assets, body: text } = strToJson(body)
if (tag_name) {
if (checkVersion(version) < checkVersion(tag_name)) {
const platform = new Map([
['win32', 'win'],
['linux', 'linux'],
['darwin', 'macos']
]).get(process.platform)
if (platform) {
try {
const download_url = assets
.filter(({ name }) => name.includes(platform))
.map(({ browser_download_url }) => browser_download_url)[0]
resolve({ download_url, text })
} catch (err) {
reject(err)
}
} else {
reject(`未找到能在此平台(${process.platform})上运行的版本`)
}
} else {
reject('当前已是最新版本')
}
} else {
reject(body)
}
},
failure: error => {
reject(error)
}
})
});
}
/**
* 半自动更新
*/
async function update() {
try {
const { download_url, text } = await getLatestReleaseDownloadUrl('shanmiteko', 'LotteryAutoScript')
let proxy_url = new URL(download_url)
proxy_url.host = 'download.fastgit.org'
await download(proxy_url.href, 'latest_version.zip')
log.info('更新说明', '\n' + text + '\n')
} catch (error) {
log.error('更新脚本', error)
}
}
module.exports = { update }
+81 -20
View File
@@ -1,18 +1,32 @@
const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
const { HttpRequest } = require("./HttpRequest");
const { send } = require("./net/http");
const { version } = require('../package.json');
/**
* 基础工具
*/
const Util = {
const utils = {
version,
/**环境变量设置文件 */
env_file: path.join(process.cwd(), "env.js"),
/**配置文件 */
config_file: path.join(process.cwd(), "my_config.js"),
/**dyid存储文件 */
dyids_dir: path.join(process.cwd(), "dyids"),
/**dyid长度 */
dyid_length: 18,
/**
* 将版本号转为数字
* @example
* 1.2.3 => 1.0203
* @param {string} version
* @returns {Number}
*/
checkVersion(version) {
return (version.match(/\d.*/)[0]).split('.').reduce((a, v, i) => a + (0.01 ** i) * Number(v), 0)
},
/**
* 安全的将JSON字符串转为对象
* 超出精度的数转为字符串
@@ -69,7 +83,7 @@ const Util = {
* @returns {Promise<void>}
*/
delay(time) {
Util.log.info('时延', `${~~time}ms`);
utils.log.info('时延', `${~~time}ms`);
return new Promise(resolve => {
setTimeout(() => {
resolve();
@@ -128,6 +142,20 @@ const Util = {
}
return array;
},
/**
* 关键词判断
* @param {string} text
* @param {string[]} key_words startwith '~' 表示黑名单
* @return {boolean}
*/
judge(text, key_words) {
return key_words.reduce((acc, word) => {
word.startsWith('~')
? RegExp(word.slice(1)).test(text) && (acc = false)
: RegExp(word).test(text) && (acc = true)
return acc
}, false)
},
/**
* 是否有指定环境变量
* @param {string} env_name
@@ -138,7 +166,7 @@ const Util = {
},
/**日志 */
log: {
level: 0,
level: 3,
/**
* 初始化默认level为3
*/
@@ -156,29 +184,66 @@ const Util = {
debug(context, msg) {
if (this.level > 3) {
if (msg instanceof Object) msg = JSON.stringify(msg, null, 4);
this.proPrint([chalk.hex('#64B3FF')(`[${Date()}]`), chalk.grey("[Debug]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#0070BB')(`[\n${msg}\n]`)])
this.proPrint([chalk.hex('#64B3FF')(`[${new Date(Date.now() + 288e5).toISOString()}]`), chalk.grey("[Debug]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#0070BB')(`[\n${msg}\n]`)])
}
},
info(context, msg) {
if (this.level > 2)
this.proPrint([chalk.hex('#64B3FF')(`[${Date()}]`), chalk.grey("[Info]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#48BB31')(`[${msg}]`)])
this.proPrint([chalk.hex('#64B3FF')(`[${new Date(Date.now() + 288e5).toISOString()}]`), chalk.grey("[Info]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#48BB31')(`[${msg}]`)])
},
warn(context, msg) {
if (this.level > 1)
this.proPrint([chalk.hex('#64B3FF')(`[${Date()}]`), chalk.grey("[Warn]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#BBBB23')(`[${msg}]`)])
this.proPrint([chalk.hex('#64B3FF')(`[${new Date(Date.now() + 288e5).toISOString()}]`), chalk.grey("[Warn]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#BBBB23')(`[\n${msg}\n]`)])
},
error(context, msg) {
if (this.level > 0)
this.proPrint([chalk.hex('#64B3FF')(`[${Date()}]`), chalk.grey("[Error]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#FF0006')(`[${msg}]`)])
this.proPrint([chalk.hex('#64B3FF')(`[${new Date(Date.now() + 288e5).toISOString()}]`), chalk.grey("[Error]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#FF0006')(`[\n${msg}\n]`)])
}
},
/**
* 下载文件
* @param {string} url
* @param {string} file_name
* @returns {Promise<void | string>}
*/
download(url, file_name) {
return new Promise((resolve, reject) => {
send({
url,
stream: true,
config: {
redirect: true,
retry: false
},
success: ({ resStream }) => {
let recv_length = 0;
const wtbs = fs.createWriteStream(file_name);
resStream.on('data', chuck => {
recv_length += chuck.length
utils.log.proPrint(`已收到:${recv_length} Bytes`)
})
resStream.pipe(wtbs)
wtbs.on('finish', () => {
utils.log.proPrint('下载完成')
resolve()
}).on('error', error => {
wtbs.destroy()
resolve(error)
})
},
failure: error => {
reject(error)
}
})
});
},
/**
* 获取远程设置
* @returns {Promise<JSON>}
*/
getRemoteConfig() {
return new Promise((resolve) => {
HttpRequest({
send({
method: 'GET',
url: 'https://gitee.com/shanmite/lottery-notice/raw/master/notice.json',
headers: {
@@ -189,14 +254,14 @@ const Util = {
success: res => {
try {
const body = JSON.parse(res.body);
if (body.node_msg) this.log.info('公告', '\n' + body.node_msg + '\n');
if (body.node_msg) utils.log.info('公告', '\n' + body.node_msg + '\n');
resolve(body.config)
} catch (error) {
resolve(JSON.parse('{}'))
}
},
failure: err => {
this.log.error('获取远程设置', '获取远程设置错误: ' + err);
utils.log.error('获取远程设置', '获取远程设置错误: ' + err);
resolve(JSON.parse('{}'));
}
})
@@ -238,7 +303,7 @@ const Util = {
* @returns {Promise<void>}
*/
createFile(filepath, defaultValue, flag) {
const fpath = path.join(this.dyids_dir, filepath);
const fpath = path.join(utils.dyids_dir, filepath);
const buffer = Buffer.from(defaultValue);
return new Promise((resolve, rejects) => {
fs.open(fpath, flag, (err, fd) => {
@@ -256,18 +321,14 @@ const Util = {
})
});
},
/**
* dyid长度
*/
dyid_length: 18,
/**
* 读取dyid文件
* @param {number} num
* @returns {fs.ReadStream}
*/
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: (this.dyid_length + 1) * 1000 })
const fpath = num < 2 ? path.join(utils.dyids_dir, 'dyid.txt') : path.join(utils.dyids_dir, `dyid${num}.txt`);
return fs.createReadStream(fpath, { encoding: 'utf8', highWaterMark: (utils.dyid_length + 1) * 1000 })
},
/**
* 追加dyid
@@ -275,10 +336,10 @@ const Util = {
* @returns {fs.WriteStream}
*/
writeDyidFile(num) {
const fpath = num < 2 ? path.join(this.dyids_dir, 'dyid.txt') : path.join(this.dyids_dir, `dyid${num}.txt`);
const fpath = num < 2 ? path.join(utils.dyids_dir, 'dyid.txt') : path.join(utils.dyids_dir, `dyid${num}.txt`);
return fs.createWriteStream(fpath, { flags: 'a' })
}
};
module.exports = Util;
module.exports = utils;
+26 -16
View File
@@ -1,4 +1,4 @@
const { env_file, config_file, log, delay, hasFileOrDir } = require("./lib/Util");
const { version: ve, env_file, config_file, log, hasEnv, delay, hasFileOrDir } = require("./lib/utils");
const metainfo = [
` _ _ _ _____ _ _ `,
@@ -10,7 +10,8 @@ const metainfo = [
` __/ | | | `,
` |___/ |_| `,
` `,
` v2.0.1 by shanmite`,
` Verison: v${ve}`,
` Written By shanmite`,
]
/**多账号存储 */
let multiple_account = [];
@@ -43,22 +44,19 @@ async function main() {
/**多账号状态还原 */
process.env.ENABLE_MULTIPLE_ACCOUNT = ENABLE_MULTIPLE_ACCOUNT;
} else {
if (!COOKIE) {
return '请查看README文件, 在env.js指定位置填入cookie'
}
const { setVariable } = require("./lib/setVariable");
await setVariable(COOKIE, Number(NUMBER));
} else if (COOKIE) {
const global_var = require("./lib/data/global_var");
await global_var.init(COOKIE, Number(NUMBER));
const { start, isMe, checkCookie } = require("./lib/lottery-in-nodejs");
const { clear } = require("./lib/clear");
/**引入基础功能 */
const { start, isMe, clear, update, checkCookie } = require("./lib/index");
log.info('main', '当前为第' + NUMBER + '个账号');
if (await checkCookie(NUMBER)) {
const mode = process.env.lottery_mode;
const help_msg = "用法: lottery [OPTIONS]\n\nOPTIONS:\n\tstart 启动抽奖\n\tcheck 中奖检查\n\tclear 清理动态和关注\n\thelp 帮助信息";
const { lottery_loop_wait, check_loop_wait, clear_loop_wait } = require("./lib/config");
const help_msg = "用法: lottery [OPTIONS]\n\nOPTIONS:\n\tstart 启动抽奖\n\tcheck 中奖检查\n\tclear 清理动态和关注\n\tupdate 检查更新\n\thelp 帮助信息";
const { lottery_loop_wait, check_loop_wait, clear_loop_wait, update_loop_wait } = require("./lib/data/config");
switch (mode) {
case 'start':
log.info('抽奖', '开始运行');
@@ -77,6 +75,11 @@ async function main() {
await clear();
}
break;
case 'update':
log.info('检查更新', '开始')
loop_wait = update_loop_wait;
await update()
break;
case 'help':
return help_msg
case undefined:
@@ -84,7 +87,11 @@ async function main() {
default:
return `提供了错误的[OPTIONS] -> ${mode}\n\n` + help_msg
}
} else {
return 'Cookie已失效, 切换账号时不要点击退出账号而应直接删除Cookie退出'
}
} else {
return '请查看README文件, 在env.js指定位置填入cookie'
}
}
@@ -99,14 +106,17 @@ async function main() {
initEnv();
log.init();
log.info('环境变量初始化', '成功加载env.js文件');
} else if (hasEnv('COOKIE') || hasEnv('MULTIPLE_ACCOUNT_PARM')) {
log.init();
log.info('环境变量初始化', '成功从环境变量中读取COOKIE设置');
} else {
log.init();
log.warn('环境变量初始化', '未在当前目录下找到env.js文件 也可在环境变量中设置所需参数');
log.error('环境变量初始化', '未在当前目录下找到env.js文件或者在环境变量中设置所需参数');
return
}
if (hasFileOrDir(config_file)) {
require("./lib/config");
require("./lib/data/config");
log.info('配置文件初始化', '成功加载my_config.js文件');
} else {
log.error('配置文件初始化', '未在当前目录下找到my_config.js文件');
@@ -118,7 +128,7 @@ async function main() {
const err_msg = await main();
if (err_msg) {
log.error('错误', '\n' + err_msg + '\n');
log.error('错误', err_msg);
log.warn('结束运行', '5秒后自动退出');
await delay(5 * 1000);
} else {
@@ -127,7 +137,7 @@ async function main() {
await delay(loop_wait)
await main()
}
log.info('结束运行', '未设置休眠时间')
log.info('结束运行', '未在config.js中设置休眠时间')
}
process.exit(0);
+17 -13
View File
@@ -87,6 +87,7 @@ module.exports = {
lottery_loop_wait: 0,
check_loop_wait: 0,
clear_loop_wait: 0,
update_loop_wait: 0,
/**
* - 转发间隔时间
@@ -140,7 +141,7 @@ 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: '',
@@ -178,11 +179,13 @@ module.exports = {
is_exception: false,
/**
* 中奖通知关键词(满足一个就推送)
* 符合js正则表达式的字符串
* - 中奖通知关键词(满足一个就推送)
* - 符合js正则表达式的字符串
* - 若以 ~ 开头则表示为黑名单规则
*/
notice_key_words: [
"中奖", "获得", "填写", "写上", "提供", "收货地址", "支付宝账号", "码", "大会员"
"中奖|获得|填写|写上|提供|收货地址|支付宝账号|码|大会员",
"~有奖预约通知"
],
/**
@@ -225,15 +228,16 @@ module.exports = {
/**
* 清除动态类型
| 动态类型 | type值 |
| ---------- | ------ |
| 无 | `0` |
| 转发 | `1` |
| 含图片 | `2` |
| 无图纯文字 | `4` |
| 视频 | `8` |
| 专栏 | `64` |
| 活动 | `2048` |
*
* | 动态类型 | type值 |
* | :------- |:----- |
* | 无 | `0` |
* | 转发 | `1` |
* | 含图片 | `2` |
* | 无图纯文字 | `4` |
* | 视频 | `8` |
* | 活动 | `2048` |
* | 专栏 | `64` |
*/
clear_dynamic_type: 1
},
+6 -6
View File
@@ -1,14 +1,14 @@
{
"name": "lottery-in-bili",
"version": "3.0.0",
"description": "自动抽奖",
"name": "lottery-auto-script",
"version": "2.0.9",
"description": "自动参与B站动态抽奖",
"main": "main.js",
"scripts": {
"start": "node main.js start",
"clear": "node main.js clear",
"check": "node main.js check",
"pkg_x86": "npx pkg . && PowerShell .\\script\\pkg\\pkg.ps1",
"pkg_clean_dist": "PowerShell -Command \"& {Remove-Item -Path .\\dist\\ -Recurse}\"",
"update": "node main.js update",
"pkg_x64": "PowerShell .\\script\\pkg\\pkg.ps1",
"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"
},
@@ -43,4 +43,4 @@
"chalk": "^4.1.1",
"nodemailer": "^6.5.0"
}
}
}
+12 -3
View File
@@ -7,12 +7,20 @@ $ENV_FILE = "env.js"
$TARGET_DIR = ".\dist"
$NAME = 'lottery-auto-script'
$TRIARR = @(
@("lottery-in-bili-win.exe", "lottery.exe", "nlts-win-x64"),
@("lottery-in-bili-linux", "lottery", "nlts-linux-x64"),
@("lottery-in-bili-macos", "lottery", "nlts-macos-x64")
@("$NAME-win.exe", "lottery.exe", "nlts-win-x64"),
@("$NAME-linux", "lottery", "nlts-linux-x64"),
@("$NAME-macos", "lottery", "nlts-macos-x64")
)
if((Test-Path $TARGET_DIR) -eq "True") {
Remove-Item -Path $TARGET_DIR -Recurse
}
npx pkg .
Copy-Item -Path $TEMPLATE_ENV_FILE -Destination $TARGET_DIR -Force
Copy-Item -Path $TEMPLATE_CONFIG_FILE -Destination $TARGET_DIR -Force
Copy-Item -Path $README -Destination $TARGET_DIR -Force
@@ -38,6 +46,7 @@ foreach ($TRI in $TRIARR) {
New-Item -Path $DIR -Name "start.bat" -ItemType File -Value "@echo off && lottery start && pause" -Force
New-Item -Path $DIR -Name "check.bat" -ItemType File -Value "@echo off && lottery check && pause" -Force
New-Item -Path $DIR -Name "clear.bat" -ItemType File -Value "@echo off && lottery clear && pause" -Force
New-Item -Path $DIR -Name "update.bat" -ItemType File -Value "@echo off && lottery update && pause" -Force
}
Compress-Archive -Path $DIR -DestinationPath "$($DIR)-$(Get-Date -Format "yyyyMMd")" -Force