Compare commits

...
32 Commits
Author SHA1 Message Date
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
shanmite d2d9d31ebf fix: 点赞失败(#7)
feat: 新增设置
2021-07-30 17:24:51 +08:00
shanmite fdee933ca4 pref: 对将要转发的动态洗牌乱序
防止被看出是抽奖号
2021-07-29 22:38:32 +08:00
shanmite 53ae976caf fix: 多账号出错回传错误 2021-07-29 20:18:00 +08:00
shanmite de88467c03 fix: 专栏验重 2021-07-29 13:47:11 +08:00
shanmite 6bbbfbb521 pref: 优化清理动态的使用体验 2021-07-29 12:57:14 +08:00
shanmite e7ab5790cd fix: 两级解构时第一级为undefined 2021-07-28 22:03:13 +08:00
shanmite 6c08cee944 fix: article模式下uid无法获取 2021-07-28 14:24:51 +08:00
shanmite 236fcb6284 pref: 去除对unzipper的依赖
feat: 专栏转发率达一半以上时跳过
2021-07-28 13:02:12 +08:00
shanmite 8bc053b352 fix: 增加dyid长度校验 2021-07-27 23:34:10 +08:00
shanmite f5a8ad75d2 feat: 判断专栏是否已查看 2021-07-27 22:10:26 +08:00
shanmite cbce4b113d feat: 增加从专栏获取抽奖的功能 2021-07-27 21:48:12 +08:00
shanmite a63456bd29 pref: 调整结构 2021-07-27 14:51:59 +08:00
shanmite 329e6931dd 更新readme 2021-07-18 23:55:49 +08:00
shanmite 309371fbd7 pref: 重构部分代码,优化提示 2021-07-18 23:37:27 +08:00
shanmite 6f81360d2a fix: 多账号状态清零 2021-07-18 22:27:48 +08:00
shanmite 4e377f1c41 cli: 更改颜色 2021-07-18 17:35:33 +08:00
shanmite 79c550db14 fix: 滤除过期官方抽奖 2021-07-18 17:24:11 +08:00
shanmite 28c2af93cf fix: 开奖时间过滤失效 2021-07-18 16:52:54 +08:00
shanmite 11aec87eed fix: 循环运行 2021-07-18 12:45:49 +08:00
43 changed files with 2048 additions and 2049 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}"
}
]
}
+27 -12
View File
@@ -17,12 +17,18 @@
[Github仓库链接](https://github.com/shanmiteko/LotteryAutoScript)
已实现功能:
> 点赞 评论 转发 @好友 带话题 随机动态 检测开奖 清理
已实现功能:
- 监控用户转发
- 监控话题页面
- 监控专栏合集
- 自动点赞、评论、乱序转发、@好友、带话题、可选随机动态
- 检测是否中奖
- 清理动态关注
- 更多功能设置请参考配置文件
声明: 此脚本仅用于学习和测试,作者本人并不对其负责,请于运行测试完成后自行删除,请勿滥用!
**声明**: 此脚本仅用于学习和测试,作者本人并不对其负责,请于运行测试完成后自行删除,请勿滥用!
----------------------------------------
---------------------------------
## 操作步骤
@@ -70,16 +76,25 @@ 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`中填入`COOKIE`和推送参数
3. `my_config.js`中自定义设置
4. 在当前目录下打开终端运行可执行文件`lottery`
5. 运行截图
2. 用记事本或其他编辑器修改`env.js`和`my_config.js`文件(右键选择用记事本打开)
3. `env.js`中填入`COOKIE`和推送参数
4. 在`my_config.js`中自定义设置
5. 在当前目录下**打开终端**运行可执行文件`lottery`(勿直接点击`lottery`)
6. 键入`lottery start`启动抽奖|`lottery check`检测中奖|`lottery clear`清理动态
> 或者新建文本文档写入`lottery start`然后更改扩展名为.bat点击运行
7. 运行截图
![lottery_start](doc/pic/lottery_start.png)
#### 以源码方式运行
Binary file not shown.

Before

Width:  |  Height:  |  Size: 210 KiB

After

Width:  |  Height:  |  Size: 123 KiB

+10 -6
View File
@@ -27,6 +27,16 @@ const account_parm = {
/**
* 为防止环境变量过长, 请将多账号填在此处
* @example
* ```js
* {
* COOKIE: "",
* NUMBER: 2,
* CLEAR: true,
* WAIT: 60 * 1000,
* },
* ```
* 请按照以上格式将参数依次填写在下方
*/
const multiple_account_parm = [
{
@@ -35,12 +45,6 @@ const multiple_account_parm = [
CLEAR: true,
WAIT: 60 * 1000,
},
// {
// COOKIE: "",
// NUMBER: 2,
// CLEAR: true,
// WAIT: 60 * 1000,
// },
]
/**
-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 };
})();
-826
View File
@@ -1,826 +0,0 @@
const Ajax = require('./Ajax');
const { strToJson, log } = require('./Base');
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',
hasCookies: true,
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',
hasCookies: true,
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 {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
},
hasCookies: false,
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 {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
},
hasCookies: false,
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('自动取关', '取关成功');
resolve(true)
} else {
log.error('自动取关', `取关失败\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('删除动态', '成功删除一条动态');
resolve(true);
} else {
log.error('删除动态', `删除动态失败\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;
-157
View File
@@ -1,157 +0,0 @@
const { createReadStream, createWriteStream } = require('fs')
const unzip = require('unzipper');
const { strToJson, tooltip } = require("./Base")
const { HttpRequest } = require("./HttpRequest")
const { GITHUB_REPOSITORY } = process.env;
const GihubAPI = {
/**
* 列出第一个构件
* @returns {Promise<{id: number, size_in_bytes: number}>}
*/
listArtifacts() {
return new Promise((resolve) => {
HttpRequest({
method: 'GET',
url: `https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/artifacts`,
config: {
retry: false
},
query: {
page: 1,
per_page: 5
},
headers: {
Accept: 'application/json, text/plain, */*',
},
success: res => {
const data = strToJson(res.body);
if (data.total_count) {
resolve(data.artifacts[0])
} else {
resolve({})
tooltip.log('之前无构件');
}
},
failure: err => {
tooltip.log(err);
resolve({})
}
})
});
},
/**
* 下载构件
* @param {number} id
* @returns {Promise<boolean>} success: true
*/
downloadArtifacts(id) {
return new Promise((resolve) => {
HttpRequest({
method: 'GET',
url: `https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/artifacts/${id}/zip`,
headers: {
accept: 'application/vnd.github.v3+json',
authorization: `token ${process.env.PAT}`
},
config: {
redirect: true,
},
stream: true,
success: res => {
let recv_length = 0;
const wtbs = createWriteStream('dyid.zip');
res.resStream.on('data', chuck => {
recv_length += chuck.length
tooltip.log(`已收到:${recv_length} Bytes`)
})
res.resStream.pipe(wtbs)
wtbs.on('finish', () => {
tooltip.log('下载完成开始解压')
createReadStream('dyid.zip').pipe(unzip.Extract({
path: 'lib',
}).on('close', () => {
tooltip.log('解压完成')
resolve(true)
}))
}).on('error', () => {
wtbs.destroy()
resolve(false)
})
},
failure: err => {
tooltip.log(err);
resolve(false)
}
})
});
},
/**
* 检查是否正在抽奖或取关
* @returns {Promise<boolean>}
*/
hasLotteryRun() {
return new Promise((resolve) => {
HttpRequest({
method: 'GET',
url: `https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/runs`,
query: {
status: "in_progress"
},
headers: {
accept: 'application/vnd.github.v3+json',
},
success: res => {
const { workflow_runs } = strToJson(res.body);
if (workflow_runs instanceof Array) {
workflow_runs.filter(wr => /sweepstakes|clear/.test(wr.name)).length > 1 ?
resolve(true) : resolve(false)
} else {
resolve(true)
}
},
failure: err => {
tooltip.log(err);
resolve(true)
}
})
});
},
/**
* 触发一个workflow
* @param {string} yaml_file
*/
trigger(yaml_file) {
return new Promise((resolve) => {
HttpRequest({
method: 'POST',
url: `https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/workflows/${yaml_file}/dispatches`,
contents: {
ref: 'main'
},
headers: {
accept: 'application/vnd.github.v3+json',
'content-type': 'application/json',
authorization: `token ${process.env.PAT}`
},
success: res => {
if (res.body === '') {
tooltip.log('成功触发'+yaml_file);
} else {
tooltip.log(`触发${yaml_file}失败 响应:\n${res.body}`);
}
resolve()
},
failure: err => {
tooltip.log(err);
resolve()
}
})
});
}
}
module.exports = GihubAPI;
-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;
-252
View File
@@ -1,252 +0,0 @@
const Base = require('./Base');
const BiliAPI = require('./BiliAPI');
const config = require("./config");
const { log } = Base
/**
* 基础功能
*/
class Public {
constructor() { }
/**
* 提取出的有用动态信息
* @typedef {object} UsefulDynamicInfo
* @property {number} uid
* @property {string} uname
* @property {number} createtime 10
* @property {string} rid_str
* @property {string} dynamic_id
* @property {number} type
* @property {string} description
* @property {boolean} hasOfficialLottery
* @property {Array<Object.<string,string|number>>} ctrl
*
* @property {number} origin_uid
* @property {string} origin_uname
* @property {string} origin_rid_str
* @property {string} origin_dynamic_id
* @property {number} orig_type
* @property {string} origin_description
* @property {boolean} origin_hasOfficialLottery
*/
/**
* 检查所有的动态信息
* @param {string} UID 指定的用户UID
* @param {number} pages 读取页数
* @param {number} time 时延
* @param {string} [_offset] 默认'0'
* @returns {Promise<{allModifyDynamicResArray: UsefulDynamicInfo[];offset: string}>} 获取前 `pages*12` 个动态信息
*/
async checkAllDynamic(hostuid, pages, time = 0, _offset = '0') {
log.info('检查所有动态', `准备读取${pages}页动态`);
const mDR = this.modifyDynamicRes,
getOneDynamicInfoByUID = BiliAPI.getOneDynamicInfoByUID,
curriedGetOneDynamicInfoByUID = Base.curryify(getOneDynamicInfoByUID); /* 柯里化的请求函数 */
/**
* 储存了特定UID的请求函数
*/
let hadUidGetOneDynamicInfoByUID = curriedGetOneDynamicInfoByUID(hostuid);
/**
* 储存所有经过整理后信息
* [{}{}...{}]
*/
let allModifyDynamicResArray = [];
let offset = _offset;
for (let i = 0; i < pages; i++) {
log.info('检查所有动态', `正在读取其中第${i + 1}页动态`);
let OneDynamicInfo = await hadUidGetOneDynamicInfoByUID(offset);
const mDRdata = mDR(OneDynamicInfo);
if (mDRdata === null) {
break;
}
/**
* 储存一片动态信息
* [{}{}...{}]
*/
const mDRArry = mDRdata.modifyDynamicResArray,
nextinfo = mDRdata.nextinfo;
if (nextinfo.has_more === 0) {
offset = nextinfo.next_offset;
log.info('检查所有动态', `成功读取${i + 1}页信息(已经是最后一页了故无法读取更多)`);
break;
} else {
allModifyDynamicResArray.push.apply(allModifyDynamicResArray, mDRArry);
i + 1 < pages
? log.info('检查所有动态', `开始读取第${i + 2}页动态信息`)
: log.info('检查所有动态', `${pages}页信息全部成功读取完成`);
offset = nextinfo.next_offset;
}
await Base.delay(time);
}
return ({ allModifyDynamicResArray, offset });
}
/**
* 互动抽奖
* 处理来自动态页面的数据
* @param {String} res
* @returns {{modifyDynamicResArray: UsefulDynamicInfo[];nextinfo: {has_more: number;next_offset: string;};} | null}
*/
modifyDynamicRes(res) {
const strToJson = Base.strToJson,
{ data, code } = strToJson(res);
if (code !== 0) {
log.error('处理动态数据', '获取动态数据出错,可能是访问太频繁 \n' + res);
return null;
}
/* 字符串offset防止损失精度 */
const offset = typeof data.offset === 'string' ? data.offset : /(?<=next_offset":)[0-9]*/.exec(res)[0]
, next = {
has_more: data.has_more,
next_offset: offset
};
/**
* 储存获取到的一组动态中的信息
*/
let array = [];
if (next.has_more === 0) {
log.info('处理动态数据', '动态数据读取完毕');
} else {
/**
* 空动态无cards
*/
const Cards = data.cards || [];
Cards.forEach(onecard => {
/**临时储存单个动态中的信息 */
let obj = {};
const { desc, card } = onecard
, { info } = desc.user_profile
, cardToJson = strToJson(card);
/* 转发者的UID */
obj.uid = info.uid;
/* 转发者的name */
obj.uname = info.uname;
/* 动态的ts10 */
obj.createtime = desc.timestamp
/* 动态类型 */
obj.type = desc.type
/* 用于发送评论 */
obj.rid_str = desc.rid_str.length > 12 ? desc.dynamic_id_str : desc.rid_str;
/* 源动态类型 */
obj.orig_type = desc.orig_type
/* 转发者的动态ID !!!!此为大数需使用字符串值,不然JSON.parse()会有丢失精度 */
obj.dynamic_id = desc.dynamic_id_str;
const { extension, extend_json } = onecard;
/* 定位@信息 */
obj.ctrl = (typeof extend_json === 'undefined') ? [] : strToJson(extend_json).ctrl || [];
/* 是否有官方抽奖 */
obj.hasOfficialLottery = (typeof extension === 'undefined') ? false : typeof extension.lott === 'undefined' ? false : true;
const { item = {} } = cardToJson;
/* 转发者的描述 后两个分别是视频动态的描述和视频本身的描述*/
obj.description = item.content || item.description || cardToJson.dynamic || cardToJson.desc || '';
if (obj.type === 1) {
/* 被转发者的UID */
obj.origin_uid = desc.origin.uid;
/* 被转发者的rid(用于发评论) */
obj.origin_rid_str = desc.origin.rid_str.length > 12 ? desc.origin.dynamic_id_str : desc.origin.rid_str;
/* 被转发者的动态的ID !!!!此为大数需使用字符串值,不然JSON.parse()会有丢失精度 */
obj.origin_dynamic_id = desc.orig_dy_id_str;
const { origin_extension } = cardToJson;
/* 是否有官方抽奖 */
obj.origin_hasOfficialLottery = typeof origin_extension === 'undefined' ?
false : typeof origin_extension.lott === 'undefined' ?
false : true;
const origin = cardToJson.origin || '{}';
const originToJson = strToJson(origin);
const { user, item } = originToJson;
/* 被转发者的name */
obj.origin_uname = typeof user === 'undefined'
? '' : user.name || user.uname || '';
/* 被转发者的描述 */
obj.origin_description = typeof item === 'undefined'
? '' : item.content || item.description || originToJson.dynamic || originToJson.desc || '';
}
array.push(obj);
});
}
return {
modifyDynamicResArray: array,
nextinfo: next
};
}
/**
* @typedef {object} LotteryInfo
* @property {string} lottery_info_type
* @property {number[]} uids `[uid,ouid]`
* @property {string} uname
* @property {Array<{}>} ctrl
* @property {string} dyid
* @property {string} rid
* @property {string} des
* @property {number} type
* @property {boolean} hasOfficialLottery 是否官方
*/
/**
* 获取tag下的抽奖信息(转发母动态)
* 并初步整理
* @param {string} tag_name
* @returns {Promise<LotteryInfo[] | null>}
*/
async getLotteryInfoByTag(tag_name) {
const self = this,
tag_id = await BiliAPI.getTagIDByTagName(tag_name),
hotdy = await BiliAPI.getHotDynamicInfoByTagID(tag_id),
modDR = self.modifyDynamicRes(hotdy);
if (modDR === null) return null;
log.info('获取动态', `开始获取带话题#${tag_name}#的动态信息`);
log.info('获取动态', '成功获取热门动态');
let mDRdata = modDR.modifyDynamicResArray; /* 热门动态 */
let next_offset = modDR.nextinfo.next_offset;
for (let index = 0; index < config.scan_page_num; index++) {
log.info('获取动态', `成功读取${index + 1}页动态`);
const newdy = await BiliAPI.getOneDynamicInfoByTag(tag_name, next_offset);
const _modify = self.modifyDynamicRes(newdy);
if (_modify === null) return null;
mDRdata.push.apply(mDRdata, _modify.modifyDynamicResArray);
next_offset = _modify.nextinfo.next_offset;
await Base.delay(config.search_wait);
}
const fomatdata = mDRdata.map(o => {
return {
lottery_info_type: 'tag',
uids: [o.uid, o.origin_uid],
uname: o.uname,
ctrl: o.ctrl,
dyid: o.dynamic_id,
rid: o.rid_str,
des: o.description,
type: o.type,
hasOfficialLottery: o.hasOfficialLottery
};
})
log.info('获取动态', `成功获取带话题#${tag_name}#的动态信息`);
return fomatdata
}
/**
* 获取最新动态信息(转发子动态)
* 并初步整理
* @param {string} UID
* @returns {Promise<LotteryInfo[] | null>}
*/
async getLotteryInfoByUID(UID) {
log.info('获取动态', `开始获取用户${UID}的动态信息`);
const { allModifyDynamicResArray: aMDRA } = await this.checkAllDynamic(UID, config.scan_page_num, config.search_wait);
if (!aMDRA.length) return null;
const fomatdata = aMDRA.map(o => {
return {
lottery_info_type: 'uid',
uids: [o.uid, o.origin_uid],
uname: o.origin_uname,
ctrl: [],
dyid: o.origin_dynamic_id,
rid: o.origin_rid_str,
des: o.origin_description,
type: o.orig_type,
hasOfficialLottery: o.origin_hasOfficialLottery
}
}).filter(a => a.type === 0 ? false : true)
log.info('获取动态', `成功获取用户${UID}的动态信息`);
return fomatdata;
}
}
module.exports = Public;
+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 };
+51 -35
View File
@@ -1,25 +1,22 @@
const { log, delay } = require("./Base");
const BiliAPI = require("./BiliAPI");
const Public = require("./Public");
const GlobalVar = require('./GlobalVar');
const config = require("./config");
/**动态偏移量 */
let offset = '0';
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)
@@ -33,39 +30,55 @@ async function getFollowList() {
* 清理动态和关注
*/
async function clear() {
const { clear_white_list, clear_max_day, clear_remove_dynamic, clear_remove_attention, clear_remove_delay, clear_dynamic_type } = config;
const { clear_white_list, clear_max_day, clear_quick_remove_attention, clear_remove_dynamic, clear_remove_attention, clear_remove_delay, clear_dynamic_type } = config;
let success = true;
const uid_list = await getFollowList();
if (!clear_remove_dynamic && clear_remove_attention) {
if (!uid_list.length) {
log.info('清理关注', `关注为空`)
} else {
log.info('清理关注', `共有${uid_list.length}个关注`)
}
if (clear_quick_remove_attention) {
log.info('清理关注', '进入只清理关注模式')
/* 专清关注 */
for (let index = 0; index < uid_list.length; index++) {
const uid = uid_list[index];
for (const [index, uid] of uid_list.entries()) {
log.info('清理关注', `(${index}) (${uid})`)
/* 取消关注 */
success = await BiliAPI.cancelAttention(uid);
if (await bili.cancelAttention(uid)) {
log.info('清理关注', '成功')
} else {
log.error('清理关注', '失败')
break
}
/* 延时 */
await delay(clear_remove_delay);
if (!success) break;
}
} else {
const now = Date.now() / 1000;
let before_separate = [];
const MY_UID = Number(GlobalVar.get('myUID'));
for (let index = 0; ; index++) {
const { allModifyDynamicResArray, offset: _offset } = await Public.prototype.checkAllDynamic(GlobalVar.get("myUID"), 1, 5 * 1000, offset);
offset = _offset;
log.info('清理动态', `开始读取第${index + 1}页(12条)`);
for (let index = 0; index < allModifyDynamicResArray.length; index++) {
const res = allModifyDynamicResArray[index];
const { type, dynamic_id, createtime } = res;
const
Now = Date.now() / 1000,
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 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}个动态`)
const { type, dynamic_id, createtime } = dyinfo || {};
if (type === clear_dynamic_type) {
const { origin_uid } = res;
if ((now - createtime) > 86400 * clear_max_day) {
const
{ origin_uid } = dyinfo,
days_ago = (Now - createtime) / 86400;
if (days_ago > clear_max_day) {
/* 移除动态 */
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)
}
/* 取消关注 */
@@ -74,20 +87,23 @@ 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;
/* 延时 */
await delay(clear_remove_delay);
if (!success) break;
} else {
log.info('清理动态', `已设置跳过${clear_max_day}天 当前动态发布时间: ${~~days_ago}天前`)
log.info('清理动态', `储存用户(${origin_uid})防止误删`)
before_separate.push(origin_uid)
}
} else {
log.info('清理动态', `此动态类型为${type} != 要清理的动态类型${clear_dynamic_type}`)
}
}
log.info('清理动态', `${index}中的转发动态与关注全部处理成功`)
if (offset === '0' || !success) break;
log.info('清理动态', `${page + 1}页(${allModifyDynamicResArray.length})中的转发动态与关注全部处理成功`)
if (next_offset === '0' || !success) break;
}
}
return
+101 -87
View File
@@ -1,74 +1,77 @@
const Base = require('./Base');
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 } = Base;
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 {number | string} param
* @param {[string, number | string]} lottery_param
*/
constructor(param) {
constructor(lottery_param) {
super();
typeof param === 'number' ? this.UID = param : this.tag_name = param;
this.lottery_param = lottery_param
this.tagid = config.partition_id; /* tagid初始化 */
this.attentionList = ''; /* 转为字符串的所有关注的up主uid */
this.LotteryInfoMap = new Map([
['UIDs', this.getLotteryInfoByUID.bind(this)],
['TAGs', this.getLotteryInfoByTag.bind(this)],
['Articles', this.getLotteryInfoByArticle.bind(this)],
]);
}
/**
* 初始化
*/
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:
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')
event_bus.emit('Turn_on_the_Monitor')
break
case 31:
eventBus.emit('Turn_on_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', '获取开奖时间失败')
break
case 61:
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;
}
}
@@ -83,26 +86,32 @@ class Monitor extends Public {
log.info('筛选动态', `筛选完毕(${len})`);
if (len) {
for (const Lottery of 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 51
return 41
}
if (ts > (Date.now() / 1000) + config.maxday * 864e5) {
log.info('过滤', '开奖时间晚于指定时间')
MyStorage.updateDyid(Lottery.dyid)
if (ts < ts_10) {
log.info('过滤', '已过开奖时间')
d_storage.updateDyid(Lottery.dyid)
continue
}
if (ts > ts_10 + config.maxday * 86400) {
log.info('过滤', '超过指定开奖时间')
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 61
return 51
}
if (followerNum < config.minfollower) {
log.info('过滤', `粉丝数(${followerNum})小于指定数量`)
MyStorage.updateDyid(Lottery.dyid)
d_storage.updateDyid(Lottery.dyid)
continue
}
}
@@ -110,7 +119,8 @@ class Monitor extends Public {
if (status % 2 !== 0) {
return status
}
MyStorage.updateDyid(Lottery.dyid);
d_storage.updateDyid(Lottery.dyid);
await utils.delay(config.wait * (Math.random() + 0.5));
}
log.info('抽奖', '开始转发下一组动态');
return 0
@@ -126,19 +136,17 @@ class Monitor extends Public {
* @property {number[]} uid 用户标识
* @property {string} dyid 动态标识
* @property {boolean} isOfficialLottery 是否官方抽奖
* @property {number} type 动态类型
* @property {string} relay_chat 动态类型
* @property {string} relay_chat 转发词
* @property {string} ctrl 定位@
* @property {string} rid 评论类型
* @property {string} rid 评论标识
* @property {number} chat_type 评论类型
*/
/**
* @returns {Promise<LotteryOptions[]>}
*/
async filterLotteryInfo() {
let self = this,
protoLotteryInfo = typeof self.UID === 'number'
? await self.getLotteryInfoByUID(self.UID)
: await self.getLotteryInfoByTag(self.tag_name);
const { lottery_param, LotteryInfoMap, attentionList } = this;
let protoLotteryInfo = await LotteryInfoMap.get(lottery_param[0])(lottery_param[1]);
if (protoLotteryInfo === null)
return [];
@@ -165,14 +173,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 Base.try_for_each(protoLotteryInfo, async function ({
await utils.try_for_each(protoLotteryInfo, async function ({
lottery_info_type, uids,
uname, dyid,
ctrl, rid, des, type,
@@ -181,18 +189,19 @@ class Monitor extends Public {
/* 遇到转发过就退出 */
if (dyids_map.get(dyid)) return false;
/**判断是转发源动态还是现动态 */
const uid = lottery_info_type === 'tag' ? uids[0] : uids[1]
, isFollowed = (new RegExp(uid)).test(self.attentionList)
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]
, needTopic = [...(new Set(description.match(/(?<=[带加上](?:话题|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 =
(lottery_info_type === 'uid' && is_imitator && model !== '00')
(is_imitator && lottery_info_type === 'uid' && model !== '00')
|| (hasOfficialLottery && model[0] === '1')
|| (!hasOfficialLottery && model[1] === '1' && !isTwoLevelDynamic && has_key_words)
, isSendChat =
@@ -207,7 +216,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;
@@ -230,7 +239,7 @@ class Monitor extends Public {
let
/**转发评语 */
RandomStr = Base.getRandomOne(config.relay),
RandomStr = utils.getRandomOne(config.relay),
/**控制字段 */
new_ctrl = [];
@@ -267,7 +276,7 @@ class Monitor extends Public {
item.location += addlength;
return item;
}).forEach(it => new_ctrl.push(it))
if (!(new RegExp(uids[1])).test(self.attentionList))
if (!(new RegExp(uids[1])).test(attentionList))
onelotteryinfo.uid.push(uids[1]);
} else {
onelotteryinfo.relay_chat = RandomStr;
@@ -276,10 +285,14 @@ class Monitor extends Public {
onelotteryinfo.ctrl = JSON.stringify(new_ctrl);
/* 根据动态的类型决定评论的类型 */
onelotteryinfo.type = type === 2 ?
11 : type === 4 || type === 1 ?
17 : type === 8 ?
1 : 0;
onelotteryinfo.chat_type =
type === 2
? 11
: type === 4 || type === 1
? 17
: type === 8
? 1
: 0;
/* 是否评论 */
if (isSendChat) onelotteryinfo.rid = rid;
@@ -298,8 +311,7 @@ class Monitor extends Public {
* 11 - 评论错误
* 21 - 关注错误
* 22 - 关注异常
* 31 - 点赞失败
* 41 - 转发失败
* 31 - 转发失败
*/
async go(option) {
log.debug('正在转发的动态信息', option);
@@ -307,48 +319,50 @@ class Monitor extends Public {
log.info('NOT_GO_LOTTERY', 'ON');
return 0
}
let status = 1;
const { uid, dyid, type, rid, relay_chat, ctrl } = option;
const { uid, dyid, chat_type, rid, relay_chat, ctrl } = option;
/* 评论 */
if (typeof rid === 'string' && type !== 0) {
const send = () => BiliAPI.sendChat(rid, Base.getRandomOne(config.chat) || relay_chat, type);
if (rid && chat_type) {
let status = 0;
const max_retry_times = 5;
for (let times = 0; times < max_retry_times && status; times++) {
status = await send();
if (status) {
log.info('自动评论', `将在 ${times + 1} 分钟后再次发送评论(${times + 1}/${max_retry_times})`)
await Base.delay(60 * 1000 * (times + 1))
for (let times = 0; times < max_retry_times; times++) {
status = await 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 utils.delay(60 * 1000 * (times + 1))
}
if (status) return 11;
}
/* 关注 */
if (uid.length) {
status = 0
for (let index = 0; index < uid.length && !status; index++) {
const one_uid = uid[index];
if (typeof one_uid === 'number') {
status = await BiliAPI.autoAttention(uid);
await Base.delay(5000);
if (!status) await BiliAPI.movePartition(uid, this.tagid);
}
}
const [u1, u2] = uid
if (u1) {
let status = await bili.autoAttention(u1)
if (status) return 20 + status;
status = await bili.movePartition(u1, this.tagid)
if (status) return 20 + status;
if (u2) {
utils.delay(5000)
status = await bili.autoAttention(u2)
if (status) return 20 + status;
status = await bili.movePartition(u2, this.tagid)
if (status) return 20 + status;
}
}
/* 点赞 */
if (await BiliAPI.autolike(dyid)) return 31;
await bili.autolike(dyid)
/* 转发 */
if (await BiliAPI.autoRelay(GlobalVar.get("myUID"), dyid, relay_chat, ctrl)) return 41;
/* 延时 */
await Base.delay(config.wait * (Math.random() + 0.5));
if (await bili.autoRelay(global_var.get("myUID"), dyid, relay_chat, ctrl)) return 31;
return 0
}
}
module.exports = Monitor;
module.exports = { Monitor };
+364
View File
@@ -0,0 +1,364 @@
const utils = require('../utils');
const bili = require('../net/bili');
const config = require("../data/config");
const d_storage = require('../helper/d_storage');
const { log } = utils
/**
* 解析dynamic_detail_card
* 提取出的有用动态信息
* @typedef {object} UsefulDynamicInfo
* @property {number} uid
* @property {string} uname
* @property {number} createtime 10
* @property {string} rid_str
* @property {string} dynamic_id
* @property {number} type
* @property {string} description
* @property {boolean} hasOfficialLottery
* @property {Array<Object.<string,string|number>>} ctrl
*
* @property {number} origin_uid
* @property {string} origin_uname
* @property {string} origin_rid_str
* @property {string} origin_dynamic_id
* @property {number} orig_type
* @property {string} origin_description
* @property {boolean} origin_hasOfficialLottery
*
* @param {object} dynamic_detail_card
* @return {UsefulDynamicInfo}
*/
function parseDynamicCard(dynamic_detail_card) {
const { strToJson } = utils;
/**临时储存单个动态中的信息 */
let obj = {};
const { desc, card, extension, extend_json } = dynamic_detail_card
, { info } = desc.user_profile
, cardToJson = strToJson(card)
, { item } = cardToJson;
/* 转发者的UID */
obj.uid = info.uid;
/* 转发者的name */
obj.uname = info.uname;
/* 动态的ts10 */
obj.createtime = desc.timestamp
/* 动态类型 */
obj.type = desc.type
/* 用于发送评论 */
obj.rid_str = desc.rid_str.length > 12 ? desc.dynamic_id_str : desc.rid_str;
/* 源动态类型 */
obj.orig_type = desc.orig_type
/* 转发者的动态ID !!!!此为大数需使用字符串值,不然JSON.parse()会有丢失精度 */
obj.dynamic_id = desc.dynamic_id_str;
/* 定位@信息 */
obj.ctrl = (extend_json && strToJson(extend_json).ctrl) || [];
/* 是否有官方抽奖 */
obj.hasOfficialLottery = extension && extension.lott && true;
/* 转发者的描述 后两个分别是视频动态的描述和视频本身的描述*/
obj.description = (item && (item.content || item.description || cardToJson.dynamic || cardToJson.desc)) || '';
if (obj.type === 1) {
const { origin_extension, origin } = cardToJson
, originToJson = strToJson(origin)
, { user, item } = originToJson;
/* 被转发者的UID */
obj.origin_uid = desc.origin.uid;
/* 被转发者的rid(用于发评论) */
obj.origin_rid_str = desc.origin.rid_str.length > 12 ? desc.origin.dynamic_id_str : desc.origin.rid_str;
/* 被转发者的动态的ID !!!!此为大数需使用字符串值,不然JSON.parse()会有丢失精度 */
obj.origin_dynamic_id = desc.orig_dy_id_str;
/* 是否有官方抽奖 */
obj.origin_hasOfficialLottery = origin_extension && origin_extension.lott;
/* 被转发者的name */
obj.origin_uname = (user && (user.name || user.uname)) || '';
/* 被转发者的描述 */
obj.origin_description = (item && (item.content || item.description || originToJson.dynamic || originToJson.desc)) || '';
}
return obj
}
/**
* 处理来自个人动态或话题页面的一组动态数据
* @param {String} res
* @returns {{modifyDynamicResArray: UsefulDynamicInfo[], nextinfo: {has_more: number, next_offset: string}} | UsefulDynamicInfo |null}
*/
function modifyDynamicRes(res) {
const
{ data = {}, code } = utils.strToJson(res),
{ cards = [], has_more, offset } = data;
if (code !== 0) {
log.error('处理动态数据', '获取动态数据出错,可能是访问太频繁 \n' + res);
return null;
}
if (!cards.length) {
log.warn('处理动态数据', '未找到任何动态信息')
}
const
/**
* 字符串offset防止损失精度
*/
next = {
has_more,
next_offset: typeof offset === 'string'
? offset
: /(?<=next_offset":)[0-9]+/.exec(res)[0]
},
/**
* 储存获取到的一组动态中的信息
*/
array = next.has_more === 0
? []
: cards.map(parseDynamicCard)
log.info('处理动态数据', `动态数据读取完毕(${cards.length})(${next.has_more})`);
return {
modifyDynamicResArray: array,
nextinfo: next
}
}
/**
* 基础搜索功能
*/
class Searcher {
constructor() { }
/**
* 整理后的抽奖信息
* @typedef {object} LotteryInfo
* @property {string} lottery_info_type
* @property {number[]} uids `[uid,ouid]`
* @property {string} uname
* @property {Array<{}>} ctrl
* @property {string} dyid
* @property {string} rid
* @property {string} des
* @property {number} type
* @property {boolean} hasOfficialLottery 是否官方
*/
/**
* 检查指定用户的所有的动态信息
* @param {number} hostuid 指定的用户UID
* @param {number} pages 读取页数
* @param {number} time 时延
* @param {string} [offset] 默认'0'
* @returns {Promise<{allModifyDynamicResArray: UsefulDynamicInfo[], offset: string}>} 获取前 `pages*12` 个动态信息
*/
static async checkAllDynamic(hostuid, pages, time = 0, offset = '0') {
log.info('检查所有动态', `准备读取${pages}页动态`);
const { getOneDynamicInfoByUID } = bili,
/**
* 柯里化请求函数
*/
curriedGetOneDynamicInfoByUID = utils.curryify(getOneDynamicInfoByUID),
/**
* 储存了特定UID的请求函数
*/
hadUidGetOneDynamicInfoByUID = curriedGetOneDynamicInfoByUID(hostuid);
/**
* 储存所有经过整理后信息
* @type { UsefulDynamicInfo[] }
*/
let allModifyDynamicResArray = [];
for (let i = 0; i < pages; i++) {
log.info('检查所有动态', `正在读取其中第${i + 1}页动态`);
const
OneDynamicInfo = await hadUidGetOneDynamicInfoByUID(offset),
mDRdata = modifyDynamicRes(OneDynamicInfo);
if (mDRdata === null) {
break;
}
const
/**
* 一片动态
*/
mDRArry = mDRdata.modifyDynamicResArray,
nextinfo = mDRdata.nextinfo;
if (nextinfo.has_more === 0) {
offset = nextinfo.next_offset;
log.info('检查所有动态', `已经是最后一页了故无法读取更多`);
break;
} else {
/**合并 */
allModifyDynamicResArray.push.apply(allModifyDynamicResArray, mDRArry);
offset = nextinfo.next_offset;
}
await utils.delay(time);
}
log.info('检查所有动态', `${pages}页信息读取完成`)
return ({ allModifyDynamicResArray, offset });
}
/**
* 获取最新动态信息(转发子动态)
* 并初步整理
* @param {string} UID
* @returns {Promise<LotteryInfo[] | null>}
*/
async getLotteryInfoByUID(UID) {
log.info('获取动态', `开始获取用户${UID}的动态信息`);
const { allModifyDynamicResArray } = await Searcher.checkAllDynamic(UID, config.uid_scan_page, config.search_wait);
if (!allModifyDynamicResArray.length) return null;
const fomatdata = allModifyDynamicResArray.map(o => {
return {
lottery_info_type: 'uid',
uids: [o.uid, o.origin_uid],
uname: o.origin_uname,
ctrl: [],
dyid: o.origin_dynamic_id,
rid: o.origin_rid_str,
des: o.origin_description,
type: o.orig_type,
hasOfficialLottery: o.origin_hasOfficialLottery
}
}).filter(a => a.type != 0)
log.info('获取动态', `成功获取用户${UID}的动态信息`);
return fomatdata;
}
/**
* 获取tag下的抽奖信息(转发母动态)
* 并初步整理
* @param {string} tag_name
* @returns {Promise<LotteryInfo[] | null>}
*/
async getLotteryInfoByTag(tag_name) {
const
tag_id = await bili.getTagIDByTagName(tag_name),
hotdy = await bili.getHotDynamicInfoByTagID(tag_id),
modDR = modifyDynamicRes(hotdy);
if (modDR === null) return null;
log.info('获取动态', `开始获取带话题#${tag_name}#的动态信息`);
log.info('获取动态', '成功获取热门动态');
/**
* 热门动态
*/
let mDRdata = modDR.modifyDynamicResArray;
let next_offset = modDR.nextinfo.next_offset;
for (let index = 0; index < config.tag_scan_page; index++) {
log.info('获取动态', `读取第${index + 1}页动态`);
const
newdy = await bili.getOneDynamicInfoByTag(tag_name, next_offset),
_modify = modifyDynamicRes(newdy);
if (_modify === null) return null;
mDRdata.push.apply(mDRdata, _modify.modifyDynamicResArray);
next_offset = _modify.nextinfo.next_offset;
await utils.delay(config.search_wait);
}
const fomatdata = mDRdata.map(o => {
return {
lottery_info_type: 'tag',
uids: [o.uid, o.origin_uid],
uname: o.uname,
ctrl: o.ctrl,
dyid: o.dynamic_id,
rid: o.rid_str,
des: o.description,
type: o.type,
hasOfficialLottery: o.hasOfficialLottery
};
})
log.info('获取动态', `成功获取带话题#${tag_name}#的动态信息`);
return fomatdata
}
/**
* 从专栏中获取抽奖信息
* @param {string} key_words
* @returns {Promise<LotteryInfo[] | null>}
*/
async getLotteryInfoByArticle(key_words) {
log.info('获取动态', `开始获取含关键词${key_words}的专栏信息`);
const cvs = (await bili.searchArticlesByKeyword(key_words)).slice(0, config.article_scan_page);
let dyinfos = [];
for (const cv of cvs) {
const
content = await bili.getOneArticleByCv(cv),
dyids = content.match(/(?<=t.bilibili.com\/)[0-9]+/g) || [],
dyids_set = [...new Set(dyids)],
/**判断此专栏是否查看过的权重 */
weight = dyids_set.length / 2;
let { length } = dyids_set,
_weight = 0;
log.info('获取动态', `提取专栏(${cv})中提及的dyid(${length})`)
for (const dyid of dyids_set) {
const isRelayed = await d_storage.searchDyid(dyid);
if (isRelayed) {
_weight += 1;
}
if (_weight >= weight) {
log.warn('获取动态', `1/2动态曾经转过,该专栏或已查看,故中止`)
dyinfos = []
break
}
if (dyid.length === utils.dyid_length) {
if (!isRelayed) {
log.info('获取动态', `查看动态(${dyid})的细节 (${length--})`)
const res = await bili.getOneDynamicByDyid(dyid)
, { code, data = {} } = utils.strToJson(res)
, { card } = data;
if (code !== 0) {
log.error('获取动态', '获取动态数据出错,可能是访问太频繁 \n' + res)
break
}
await utils.delay(2000)
if (card) {
dyinfos.push(parseDynamicCard(card));
}
} else {
log.info('获取动态', `动态(${dyid})已转发过 (${length--})`)
}
} else {
log.warn('获取动态', `动态(${dyid})无效 (${length--})`)
}
}
}
const fomatdata = dyinfos.map(o => {
return {
lottery_info_type: 'article',
uids: [o.uid, o.origin_uid],
uname: o.uname,
ctrl: o.ctrl,
dyid: o.dynamic_id,
rid: o.rid_str,
des: o.description,
type: o.type,
hasOfficialLottery: o.hasOfficialLottery
};
})
log.info('获取动态', `成功获取含关键词${key_words}的专栏信息`);
return fomatdata
}
}
module.exports = { Searcher };
+3 -1
View File
@@ -1,4 +1,4 @@
const { config_file } = require('./Base');
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;
+8 -6
View File
@@ -1,7 +1,6 @@
const Base = require("./Base");
const { log } = Base;
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 = Base.readDyidFile(Number(process.env.NUMBER));
const rs = readDyidFile(Number(process.env.NUMBER));
let status = false;
rs.on('data', chunk => {
if (Rdyid.test(chunk)) {
@@ -32,8 +31,11 @@ const MyStorage = {
*/
updateDyid: (dyid) => {
log.info('更新dyid', `写入${dyid}`);
if (dyid.length !== dyid_length) {
log.error('更新dyid', `dyid(${dyid})长度不为18 若出现此问题请即时通知开发者`)
}
return new Promise((resolve) => {
const ws = Base.writeDyidFile(Number(process.env.NUMBER));
const ws = writeDyidFile(Number(process.env.NUMBER));
ws.write(dyid + ',', () => {
ws.destroy();
resolve()
@@ -47,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;
+70 -72
View File
@@ -1,5 +1,5 @@
const { log } = require("./Base");
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酱发送通知消息成功\n')
} else if (data.errno === 1024) {
// 一分钟内发送相同的内容会触发
log.error('发送通知',`server酱发送通知消息异常: ${data.errmsg}\n`)
log.error('发送通知', `server酱发送通知消息异常: ${data.errmsg}\n`)
} 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失败!!\n')
throw new Error(err);
}
})
} else {
log.warn('发送通知','您未提供server酱的SCKEY,取消微信推送消息通知\n');
log.warn('发送通知', '您未提供server酱的SCKEY,取消微信推送消息通知\n');
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版)发送通知消息成功\n')
} 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失败!!\n')
throw new Error(err);
}
})
} else {
log.warn('发送通知','您未提供server酱(Turbo版)的SCKEY,取消微信推送消息通知\n');
log.warn('发送通知', '您未提供server酱(Turbo版)的SCKEY,取消微信推送消息通知\n');
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)}通知消息成功\n`)
} else if (data.code === 400) {
log.error('发送通知',`QQ酷推(Cool Push)发送${pushMode(QQ_MODE)}推送失败:${data}\n`)
log.error('发送通知', `QQ酷推(Cool Push)发送${pushMode(QQ_MODE)}推送失败:${data}\n`)
} 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失败!!\n`)
throw new Error(err);
}
})
} else {
log.warn('发送通知','您未提供酷推的SKEY,取消QQ推送消息通知\n');
log.warn('发送通知', '您未提供酷推的SKEY,取消QQ推送消息通知\n');
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发送通知消息成功\n')
} else {
log.error('发送通知',`${data.message}\n`);
log.error('发送通知', `${data.message}\n`);
}
} catch (error) {
log.error('发送通知',error);
log.error('发送通知', error);
} finally {
resolve()
}
},
failure: err => {
log.error('发送通知','Bark APP发送通知调用API失败!!\n');
log.error('发送通知', 'Bark APP发送通知调用API失败!!\n');
resolve();
throw new Error(err)
}
})
} else {
log.warn('发送通知','您未提供Bark的APP推送BARK_PUSH,取消Bark推送消息通知\n');
log.warn('发送通知', '您未提供Bark的APP推送BARK_PUSH,取消Bark推送消息通知\n');
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发送通知消息完成。\n')
} else if (data.error_code === 400) {
log.error('发送通知','请主动给bot发送一条消息并检查接收用户ID是否正确。\n')
log.error('发送通知', '请主动给bot发送一条消息并检查接收用户ID是否正确。\n')
} else if (data.error_code === 401) {
log.error('发送通知','Telegram bot token 填写错误。\n')
log.error('发送通知', 'Telegram bot token 填写错误。\n')
}
} catch (error) {
log.error('发送通知',error);
log.error('发送通知', error);
} finally {
resolve()
}
},
failure: err => {
log.error('发送通知','telegram发送通知消息失败!!\n')
log.error('发送通知', 'telegram发送通知消息失败!!\n')
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.warn('发送通知', '您未提供telegram机器人推送所需的TG_BOT_TOKEN和TG_USER_ID,取消telegram推送消息通知\n');
resolve()
}
})
@@ -430,8 +430,8 @@ function ddBotNotify(text, desp) {
const dateNow = Date.now();
const hmac = crypto.createHmac('sha256', DD_BOT_SECRET);
hmac.update(`${dateNow}\n${DD_BOT_SECRET}`);
const result = encodeURIComponent(hmac.digest('base64'));
HttpRequest({
const result = encodeURIComponent(hmac.digest('Util64'));
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('发送通知', '钉钉发送通知消息完成。\n')
} else {
log.error('发送通知',`${data.errmsg}\n`)
log.error('发送通知', `${data.errmsg}\n`)
}
} catch (e) {
log.error('发送通知',e);
log.error('发送通知', e);
} finally {
resolve();
}
},
failure: err => {
log.error('发送通知','钉钉发送通知消息失败!!\n')
log.error('发送通知', '钉钉发送通知消息失败!!\n')
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('发送通知', '钉钉发送通知消息完成。\n')
} else {
log.error('发送通知',`${data.errmsg}\n`)
log.error('发送通知', `${data.errmsg}\n`)
}
} catch (e) {
log.error('发送通知',e);
log.error('发送通知', e);
} finally {
resolve();
}
},
failure: err => {
log.error('发送通知','钉钉发送通知消息失败!!\n');
log.error('发送通知', '钉钉发送通知消息失败!!\n');
resolve();
throw new Error(err)
}
})
} else {
log.warn('发送通知','您未提供钉钉机器人推送所需的DD_BOT_TOKEN或者DD_BOT_SECRET,取消钉钉推送消息通知\n');
log.warn('发送通知', '您未提供钉钉机器人推送所需的DD_BOT_TOKEN或者DD_BOT_SECRET,取消钉钉推送消息通知\n');
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('发送通知', '企业微信发送通知消息完成。\n');
} else {
log.error('发送通知',`${data.errmsg}\n`);
log.error('发送通知', `${data.errmsg}\n`);
}
} catch (e) {
log.error('发送通知',e);
log.error('发送通知', e);
} finally {
resolve();
}
},
failure: err => {
log.error('发送通知','企业微信发送通知消息失败!!\n');
log.error('发送通知', '企业微信发送通知消息失败!!\n');
resolve();
throw new Error(err)
}
})
} else {
log.warn('发送通知','您未提供企业微信机器人推送所需的QYWX_KEY,取消企业微信推送消息通知\n');
log.warn('发送通知', '您未提供企业微信机器人推送所需的QYWX_KEY,取消企业微信推送消息通知\n');
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无效\n')
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发送通知消息成功\n')
} else {
log.error('发送通知',`iGot发送通知消息失败:${data.errMsg}\n`)
log.error('发送通知', `iGot发送通知消息失败:${data.errMsg}\n`)
}
} catch (e) {
log.error('发送通知',e);
log.error('发送通知', e);
} finally {
resolve();
}
},
failure: err => {
log.error('发送通知','iGot 发送通知调用API失败!!\n')
log.error('发送通知', 'iGot 发送通知调用API失败!!\n')
resolve();
throw new Error(err)
}
})
} else {
log.warn('发送通知','您未提供iGot的推送IGOT_PUSH_KEY,取消iGot推送消息通知\n');
log.warn('发送通知', '您未提供iGot的推送IGOT_PUSH_KEY,取消iGot推送消息通知\n');
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 ? '一对多' : '一对一'}通知消息完成。\n`)
} else {
log.error('发送通知',`push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息失败:${data.msg}\n`)
log.error('发送通知', `push+发送${PUSH_PLUS_USER ? '一对多' : '一对一'}通知消息失败:${data.msg}\n`)
}
} 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 ? '一对多' : '一对一'}通知消息失败!!\n`)
resolve();
throw new Error(err)
}
})
} else {
log.warn('发送通知','您未提供push+推送所需的PUSH_PLUS_TOKEN,取消push+推送消息通知\n');
log.warn('发送通知', '您未提供push+推送所需的PUSH_PLUS_TOKEN,取消push+推送消息通知\n');
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.warn('发送通知', '您未提供email推送所需的所有参数故取消email推送消息通知\n');
}
}
module.exports = {
sendNotify
}
module.exports = { sendNotify }
+26
View File
@@ -0,0 +1,26 @@
const { isMe } = require('./check');
const { clear } = require('./clear');
const { start } = require('./lottery');
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, checkCookie }
-152
View File
@@ -1,152 +0,0 @@
const Base = require('./Base');
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 } = Base;
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(Base.getRandomOne(config.dy_contents));
await Base.delay(2000);
}
} else {
log.info('随机动态', '已有非抽奖动态故无需创建');
}
}
}
/**
* 抽奖主函数
* @param {string} cookie
* @returns {Promise<void>}
*/
function start() {
return new Promise(resolve => {
let times = Base.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()];
const nlottery = Number(lottery);
await (new Monitor(isNaN(nlottery) ? lottery : nlottery)).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\n\n`
});
log.info('中奖检测', '--> OK');
}
if (follow_unread + unfollow_unread > 0) {
const check = async (type) => {
let session_t = '';
let max = 0;
let MySession = await BiliAPI.getSessionInfo(type)
do {
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 Base.delay(1000);
if (/中奖|获得|填写|写上|提供|地址|支付宝账号|码|大会员/.test(content)) {
desp += `发生时间: ${new Date(timestamp * 1000).toLocaleString()} \n\n`
desp += `用户: ${sender_uid} \n\n`
desp += `私信你(${GlobalVar.get("myUID")})说: ${content} \n\n`
desp += `[直达链接](https://message.bilibili.com/#/whisper/mid${sender_uid}) \n\n`
desp += `\n\n\n\n`
}
}
}
if (MySession.has_more) {
await Base.delay(3e3);
MySession = await BiliAPI.getSessionInfo(type, session_t)
}
max++
} while (MySession.has_more && max < 10);
}
if (follow_unread) {
log.info('中奖检测', '<-- 正在检查已关注者的私信')
await check(1)
}
if (unfollow_unread) {
log.info('中奖检测', '<-- 正在检查未关注者的私信')
await check(2)
}
log.info('中奖检测', '--> OK');
}
if (desp) {
log.info(desp);
await sendNotify('可能中奖了', desp);
} else {
log.info('中奖检测', "未中奖");
}
return;
}
/**
* 检查cookie是否有效
* @param {string} num
*/
async function checkCookie(num) {
if (await BiliAPI.getMyinfo()) {
log.info('Cookie有效性检测', '成功登录');
return true;
} else {
log.error('Cookie有效性检测', `登录失败 COOKIE${num} 已失效 UID:${GlobalVar.get("myUID")}`);
await sendNotify('动态抽奖出错-登录失败', `COOKIE${num} 已失效 UID:${GlobalVar.get("myUID")}`)
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 = {
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',
}
+858
View File
@@ -0,0 +1,858 @@
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: 11,
csrf: GlobalVar.get("csrf")
}
}).then(responseText => {
/* 重复关注code also equal 0 */
const res = strToJson(responseText)
if (res.code === 0) {
log.info('自动关注', '关注+1');
return 0
} else if (res.code === 22002) {
log.error('自动关注', '您已被对方拉入黑名单');
return 1
} else if (res.code === 22015) {
log.error('自动关注', '您的账号异常无法关注');
return 2
} else {
log.warn('自动关注', `失败 尝试切换线路\n${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}`);
return post({
url: API.RELATION_BATCH_MODIFY,
contents: {
fid: uid,
act: 1,
re_src: 11,
csrf: GlobalVar.get("csrf")
}
}).then(responseText => {
if (/^{"code":0/.test(responseText)) {
log.info('自动关注', '关注+1');
return 0
} else {
log.error('自动关注', `失败\n${responseText}`);
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: 11,
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 }
-32
View File
@@ -1,32 +0,0 @@
const Base = require("./Base");
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]);
});
GlobalVar.set('Lottery', [...config.UIDs, ...config.TAGs]);
GlobalVar.set('remoteconfig', await Base.getRemoteConfig());
}
await Base.createDir('dyids');
await Base.createFile(n < 2 ? 'dyid.txt' : `dyid${n}.txt`, '', 'a')
return
}
module.exports = { setVariable };
+66 -70
View File
@@ -1,24 +1,26 @@
const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
const { HttpRequest } = require("./HttpRequest");
const { send } = require("./net/http");
/**
* 基础工具
*/
const Base = {
const utils = {
/**环境变量设置文件 */
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,
/**
* 安全的将JSON字符串转为对象
* 超出精度的数转为字符串
* @param {string} params
* @return {object}
* 返回对象
* 返回对象 解析失败返回 `{}`
*/
strToJson(params) {
const isJSON = (str => {
@@ -47,9 +49,10 @@ const Base = {
},
/**
* 函数柯里化
* @param {function} func
* @template T
* @param {(arg, arg) => T} func
* 要被柯里化的函数
* @returns {function}
* @returns {(arg) => (arg) => T)}
* 一次接受一个参数并返回一个接受余下参数的函数
*/
curryify(func) {
@@ -68,7 +71,7 @@ const Base = {
* @returns {Promise<void>}
*/
delay(time) {
Base.log.info('时延', `${time}ms`);
utils.log.info('时延', `${~~time}ms`);
return new Promise(resolve => {
setTimeout(() => {
resolve();
@@ -92,18 +95,60 @@ const Base = {
}
return c
},
/**
* 无限序列
* `[0..]`
*/
*infiniteNumber() {
for (let index = 0; ; index++) {
yield index
}
},
/**
* 随机获取数组中的一个元素
* @param {any[]} arr
* @returns {any}
* @template T
* @param {T[]} arr
* @returns {T}
*/
getRandomOne(arr) {
let RandomOne = null;
if (arr instanceof Array && arr.length) {
if (Array.isArray(arr) && arr.length) {
RandomOne = arr[parseInt(Math.random() * arr.length)];
}
return RandomOne
},
/**
* FisherYates shuffle洗牌
* @template T
* @param {Array<T>} array
* @return {Array<T>}
*/
shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
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
* @returns
*/
hasEnv(env_name) {
return process.env[env_name] ? true : false;
},
@@ -127,78 +172,29 @@ const Base = {
debug(context, msg) {
if (this.level > 3) {
if (msg instanceof Object) msg = JSON.stringify(msg, null, 4);
this.proPrint([`[${Date()}]`, chalk.grey("[Debug]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#0070BB')(`[\n${msg}\n]`)])
this.proPrint([chalk.hex('#64B3FF')(`[${Date()}]`), chalk.grey("[Debug]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#0070BB')(`[\n${msg}\n]`)])
}
},
info(context, msg) {
if (this.level > 2)
this.proPrint([`[${Date()}]`, chalk.grey("[Info]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#48BB31')(`[${msg}]`)])
this.proPrint([chalk.hex('#64B3FF')(`[${Date()}]`), chalk.grey("[Info]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#48BB31')(`[${msg}]`)])
},
warn(context, msg) {
if (this.level > 1)
this.proPrint([`[${Date()}]`, chalk.grey("[Warn]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#BBBB23')(`[${msg}]`)])
this.proPrint([chalk.hex('#64B3FF')(`[${Date()}]`), chalk.grey("[Warn]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#BBBB23')(`[${msg}]`)])
},
error(context, msg) {
if (this.level > 0)
this.proPrint([`[${Date()}]`, chalk.grey("[Error]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#FF0006')(`[${msg}]`)])
this.proPrint([chalk.hex('#64B3FF')(`[${Date()}]`), chalk.grey("[Error]"), chalk.hex('#FFA500')(`[${context}]`), chalk.hex('#FF0006')(`[${msg}]`)])
}
},
/**
* 提取开奖信息
* @param {string} des 描述
* @returns {
{
ts: number|0;
text:string|'开奖时间: 未填写开奖时间';
item:string|'请自行查看';
isMe:string|'请自行查看';
}
* }
*/
getLotteryNotice(des) {
const r = /([\d零一二两三四五六七八九十]+)[.月]([\d零一二两三四五六七八九十]+)[日号]?/;
if (des === '') return {
ts: 0,
text: `开奖时间: 未填写开奖时间`,
item: '请自行查看',
isMe: '请自行查看'
}
const _date = r.exec(des) || [];
const timestamp10 = ((month, day) => {
if (month && day) {
let date = new Date(`${new Date(Date.now()).getFullYear()}-${month}-${day} 23:59:59`).getTime()
if (!isNaN(date)) return date / 1000;
}
return 0
})(_date[1], _date[2])
if (timestamp10 === 0) return {
ts: 0,
text: `开奖时间: 未填写开奖时间`,
item: '请自行查看',
isMe: '请自行查看'
}
const timestamp13 = timestamp10 * 1000,
time = new Date(timestamp13);
const remain = (() => {
const timestr = ((timestamp13 - Date.now()) / 86400000).toString()
, timearr = timestr.replace(/(\d+)\.(\d+)/, "$1,0.$2").split(',');
const text = timearr[0][0] === '-' ? `开奖时间已过${timearr[0].substring(1)}天余${parseInt(timearr[1] * 24)}小时` : `还有${timearr[0]}天余${parseInt(timearr[1] * 24)}小时`;
return text
})();
return {
ts: timestamp10,
text: `开奖时间: ${time.toLocaleString()} ${remain}`,
item: '请自行查看',
isMe: '请自行查看'
};
},
/**
* 获取远程设置
* @returns {Promise<JSON>}
*/
getRemoteConfig() {
return new Promise((resolve) => {
HttpRequest({
send({
method: 'GET',
url: 'https://gitee.com/shanmite/lottery-notice/raw/master/notice.json',
headers: {
@@ -209,14 +205,14 @@ const Base = {
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('{}'));
}
})
@@ -258,7 +254,7 @@ const Base = {
* @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) => {
@@ -282,8 +278,8 @@ const Base = {
* @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: 19 * 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
@@ -291,10 +287,10 @@ const Base = {
* @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 = Base;
module.exports = utils;
+32 -20
View File
@@ -1,4 +1,4 @@
const { env_file, config_file, log, delay, hasFileOrDir } = require("./lib/Base");
const { env_file, config_file, log, hasEnv, delay, hasFileOrDir } = require("./lib/utils");
const metainfo = [
` _ _ _ _____ _ _ `,
@@ -10,7 +10,8 @@ const metainfo = [
` __/ | | | `,
` |___/ |_| `,
` `,
` by shanmite `,
` Verison: v2.0.5`,
` Written By shanmite`,
]
/**多账号存储 */
let multiple_account = [];
@@ -33,25 +34,29 @@ async function main() {
process.env.COOKIE = acco.COOKIE;
process.env.NUMBER = acco.NUMBER;
process.env.CLEAR = acco.CLEAR;
await main();
await delay(acco.WAIT);
const err_msg = await main();
if (err_msg) {
return err_msg
} else {
await delay(acco.WAIT);
}
}
} else {
if (!COOKIE) {
return '请查看README文件, 在env.js指定位置填入cookie'
}
const { setVariable } = require("./lib/setVariable");
await setVariable(COOKIE, Number(NUMBER));
const { start, isMe, checkCookie } = require("./lib/lottery-in-nodejs");
const { clear } = require("./lib/clear");
/**多账号状态还原 */
process.env.ENABLE_MULTIPLE_ACCOUNT = ENABLE_MULTIPLE_ACCOUNT;
} else if (COOKIE) {
const global_var = require("./lib/data/global_var");
await global_var.init(COOKIE, Number(NUMBER));
/**引入基础功能 */
const { start, isMe, clear, 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 { lottery_loop_wait, check_loop_wait, clear_loop_wait } = require("./lib/data/config");
switch (mode) {
case 'start':
log.info('抽奖', '开始运行');
@@ -77,7 +82,11 @@ async function main() {
default:
return `提供了错误的[OPTIONS] -> ${mode}\n\n` + help_msg
}
} else {
return 'Cookie已失效, 切换账号时不要点击退出账号而应直接删除Cookie退出'
}
} else {
return '请查看README文件, 在env.js指定位置填入cookie'
}
}
@@ -92,14 +101,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文件');
@@ -110,18 +122,18 @@ async function main() {
process.env.lottery_mode = process.argv[2]
const err_msg = await main();
if (err_msg) {
log.error('错误', '\n' + err_msg + '\n');
log.warn('结束运行', '5秒后自动退出');
await delay(5 * 1000);
} else {
if (loop_wait > 0) {
while (loop_wait) {
log.info('程序休眠', `${loop_wait / 1000}秒后再次启动`)
await delay(loop_wait);
} else {
log.info('结束运行', '未设置休眠时间')
await delay(loop_wait)
await main()
}
log.info('结束运行', '未在config.js中设置休眠时间')
}
process.exit(0);
})()
+47 -13
View File
@@ -12,6 +12,13 @@ module.exports = {
241675899
],
/**
* 监视的专栏关键词
*/
Articles: [
'抽奖合集'
],
/**
* 监视的tag
*/
@@ -53,9 +60,19 @@ module.exports = {
is_imitator: false,
/**
* - 在uid或tag里检索的页数
* - 在uid里检索的页数
*/
scan_page_num: 3,
uid_scan_page: 3,
/**
* - 在tag里检索的页数
*/
tag_scan_page: 3,
/**
* - 获取专栏数量
*/
article_scan_page: 3,
/**
* - 开奖时间距离现在的最大天数
@@ -67,7 +84,7 @@ module.exports = {
* - 循环等待时间(指所有操作完毕后的休眠时间)
* - 单位毫秒
*/
lottery_loop_wait: 60 * 60 * 1000,
lottery_loop_wait: 0,
check_loop_wait: 0,
clear_loop_wait: 0,
@@ -123,7 +140,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: '',
@@ -160,6 +177,16 @@ module.exports = {
*/
is_exception: false,
/**
* - 中奖通知关键词(满足一个就推送)
* - 符合js正则表达式的字符串
* - 若以 ~ 开头则表示为黑名单规则
*/
notice_key_words: [
"中奖|获得|填写|写上|提供|收货地址|支付宝账号|码|大会员",
"~有奖预约通知"
],
/**
* - 清理白名单uid或dyid
* - 英文逗号分隔 如: 1,2,3
@@ -177,6 +204,12 @@ module.exports = {
*/
clear_max_day: 30,
/**
* - 快速移除关注
* - 不加判断只去除关注
*/
clear_quick_remove_attention: false,
/**
* 是否移除动态
*/
@@ -194,15 +227,16 @@ module.exports = {
/**
* 清除动态类型
| 动态类型 | type值 |
| ---------- | ------ |
| 无 | `0` |
| 转发 | `1` |
| 含图片 | `2` |
| 无图纯文字 | `4` |
| 视频 | `8` |
| 专栏 | `64` |
| 活动 | `2048` |
*
* | 动态类型 | type值 |
* | :------- |:----- |
* | 无 | `0` |
* | 转发 | `1` |
* | 含图片 | `2` |
* | 无图纯文字 | `4` |
* | 视频 | `8` |
* | 活动 | `2048` |
* | 专栏 | `64` |
*/
clear_dynamic_type: 1
},
+5 -6
View File
@@ -23,7 +23,7 @@
},
"repository": {
"type": "git",
"url": "https://github.com/shanmite/AutoScript.git"
"url": "https://github.com/shanmiteko/AutoScript.git"
},
"keywords": [
"auto",
@@ -32,16 +32,15 @@
"author": "shanmite",
"license": "GPL-3.0-or-later",
"bugs": {
"url": "https://github.com/shanmite/AutoScript/issues"
"url": "https://github.com/shanmiteko/AutoScript/issues"
},
"homepage": "https://github.com/shanmite/AutoScript#readme",
"homepage": "https://github.com/shanmiteko/AutoScript#readme",
"devDependencies": {
"eslint": "^7.17.0",
"pkg": "^5.2.1"
},
"dependencies": {
"chalk": "^4.1.1",
"nodemailer": "^6.5.0",
"unzipper": "^0.10.11"
"nodemailer": "^6.5.0"
}
}
}
+4 -3
View File
@@ -1,4 +1,5 @@
#!/bin/bash
set -e
# 脚本根目录
SCRIPT_FOLDER=lottery
@@ -61,7 +62,7 @@ docker run \
$DOCKER_REPO \
start" \
> start.sh
chmod 777 start.sh
chmod +x start.sh
echo "create check.sh"
echo -e "#!/bin/bash\n\
@@ -72,7 +73,7 @@ docker run \
$DOCKER_REPO \
check" \
> check.sh
chmod 777 check.sh
chmod +x check.sh
echo "create clear.sh"
echo -e "#!/bin/bash\n\
@@ -83,4 +84,4 @@ docker run \
$DOCKER_REPO \
clear" \
> clear.sh
chmod 777 clear.sh
chmod +x clear.sh
-5
View File
@@ -1,5 +0,0 @@
#!/bin/bash
cd ..
cd ..
npm i
npm run check
-5
View File
@@ -1,5 +0,0 @@
#!/bin/bash
cd ..
cd ..
npm i
npm run clear
-5
View File
@@ -1,5 +0,0 @@
#!/bin/bash
cd ..
cd ..
npm i
npm run start
+11 -2
View File
@@ -1,3 +1,4 @@
$README = "README.md"
$TEMPLATE_CONFIG_FILE = "my_config.example.js"
$TEMPLATE_ENV_FILE = "env.example.js"
@@ -14,10 +15,10 @@ $TRIARR = @(
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
Set-Location -Path $TARGET_DIR
# 重命名文件
Move-Item -Path $TEMPLATE_ENV_FILE -Destination $ENV_FILE -Force
Move-Item -Path $TEMPLATE_CONFIG_FILE -Destination $CONFIG_FILE -Force
@@ -31,9 +32,17 @@ foreach ($TRI in $TRIARR) {
Move-Item -Path $BIN -Destination $DIR -Force
Copy-Item -Path $ENV_FILE -Destination $DIR -Force
Copy-Item -Path $CONFIG_FILE -Destination $DIR -Force
Copy-Item -Path $README -Destination $DIR -Force
if ($DIR -eq "nlts-win-x64") {
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
}
Compress-Archive -Path $DIR -DestinationPath "$($DIR)-$(Get-Date -Format "yyyyMMd")" -Force
}
Remove-Item -Path $ENV_FILE
Remove-Item -Path $CONFIG_FILE
Remove-Item -Path $CONFIG_FILE
Remove-Item -Path $README
-9
View File
@@ -1,9 +0,0 @@
chcp 65001
cd ..
cd ..
npm i
npm run check
# 暂停
pause
-9
View File
@@ -1,9 +0,0 @@
chcp 65001
cd ..
cd ..
npm i
npm run clear
# 暂停
pause
-9
View File
@@ -1,9 +0,0 @@
chcp 65001
cd ..
cd ..
npm i
npm run start
# 暂停
pause