├── .dockerignore ├── .gitignore ├── ecosystem.config.js ├── test ├── bot │ └── api-demo.js └── dmsrc │ ├── douyu-client-demo.js │ ├── local-src-client-demo.js │ ├── bilibili-client-demo.js │ └── local-src-sender.js ├── Dockerfile ├── dmsrc ├── local-src │ └── index.js ├── README.md ├── common │ └── index.js ├── douyu │ └── index.js └── bilibili │ └── index.js ├── package.json ├── README.md ├── bot.config.js ├── bot ├── util │ ├── transfer-helper.js │ ├── rate-limiter.js │ ├── statistics.js │ ├── schedulers.js │ └── settings.js ├── api.js ├── app.js ├── bot-wrapper.js └── bot-core.js ├── dmsrc.config.js └── LICENSE /.dockerignore: -------------------------------------------------------------------------------- 1 | .git 2 | node_modules 3 | data 4 | npm-debug.log 5 | 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | /.vscode 3 | /node_modules 4 | /data 5 | /test/others 6 | *.iml 7 | config.js 8 | bot.config.js 9 | dmsrc.config.js 10 | 11 | -------------------------------------------------------------------------------- /ecosystem.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | apps : [{ 3 | name: 'danmaqua-bot', 4 | script: './bot/app.js' 5 | }, { 6 | name: 'dmsrc-bilibili', 7 | script: './dmsrc/bilibili/index.js' 8 | }, { 9 | name: 'dmsrc-douyu', 10 | script: './dmsrc/douyu/index.js' 11 | }] 12 | }; 13 | -------------------------------------------------------------------------------- /test/bot/api-demo.js: -------------------------------------------------------------------------------- 1 | const botConfig = require('../../bot.config'); 2 | const settings = require('../../bot/util/settings'); 3 | settings.init(botConfig, false); 4 | const api = require('../../bot/api'); 5 | 6 | const man = new api.DanmakuSourceManager(); 7 | man.on('danmaku', (danmaku) => console.log(danmaku)); 8 | man.joinRoom('bilibili', 14327465); 9 | -------------------------------------------------------------------------------- /test/dmsrc/douyu-client-demo.js: -------------------------------------------------------------------------------- 1 | const ioClient = require('socket.io-client'); 2 | const douyuConfig = require('../../dmsrc.config').douyu; 3 | 4 | const socket = ioClient('http://localhost:' + douyuConfig.port, { 5 | transportOptions: { 6 | polling: { 7 | extraHeaders: { 8 | 'Authorization': douyuConfig.basicAuth 9 | } 10 | } 11 | } 12 | }); 13 | 14 | socket.on('connect', () => { 15 | console.log('Connected!'); 16 | socket.emit('join', 1126960); 17 | }); 18 | 19 | socket.on('danmaku', (danmaku) => { 20 | console.log('Received danmaku: ', danmaku); 21 | }); 22 | -------------------------------------------------------------------------------- /test/dmsrc/local-src-client-demo.js: -------------------------------------------------------------------------------- 1 | const ioClient = require('socket.io-client'); 2 | const localConfig = require('../../dmsrc.config').local; 3 | 4 | const socket = ioClient('http://localhost:' + localConfig.port, { 5 | transportOptions: { 6 | polling: { 7 | extraHeaders: { 8 | 'Authorization': localConfig.basicAuth 9 | } 10 | } 11 | } 12 | }); 13 | 14 | socket.on('connect', () => { 15 | console.log('Connected!'); 16 | socket.emit('join', 114514); 17 | }); 18 | 19 | socket.on('danmaku', (danmaku) => { 20 | console.log('Received danmaku: ', danmaku); 21 | }); 22 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:14-alpine 2 | 3 | # Prepare package registry 4 | RUN npm config set registry http://mirrors.cloud.tencent.com/npm/ 5 | 6 | # Prepare working directory 7 | RUN mkdir -p /usr/src/dmq-bot 8 | 9 | # Set working directory 10 | WORKDIR /usr/src/dmq-bot 11 | 12 | # Install dependencies 13 | COPY package.json package-lock.json /usr/src/dmq-bot/ 14 | RUN cd /usr/src/dmq-bot 15 | RUN npm install 16 | RUN npm install -g pm2@latest 17 | 18 | # Copy programs 19 | COPY . /usr/src/dmq-bot 20 | 21 | # Start services 22 | CMD pm2 start /usr/src/dmq-bot/ecosystem.config.js \ 23 | && pm2 logs "/(danmaqua-bot|dmsrc-bilibili|dmsrc-douyu)/" 24 | 25 | -------------------------------------------------------------------------------- /test/dmsrc/bilibili-client-demo.js: -------------------------------------------------------------------------------- 1 | const ioClient = require('socket.io-client'); 2 | const bilibiliConfig = require('../../dmsrc.config').bilibili; 3 | 4 | const socket = ioClient('http://localhost:' + bilibiliConfig.port, { 5 | transportOptions: { 6 | polling: { 7 | extraHeaders: { 8 | 'Authorization': bilibiliConfig.basicAuth 9 | } 10 | } 11 | } 12 | }); 13 | 14 | socket.on('connect', () => { 15 | console.log('Connected!'); 16 | socket.emit('join', 6); 17 | socket.emit('leave', 6); 18 | socket.emit('join', 21545232); 19 | }); 20 | 21 | socket.on('danmaku', (danmaku) => { 22 | console.log('Received danmaku: ', danmaku); 23 | }); 24 | -------------------------------------------------------------------------------- /dmsrc/local-src/index.js: -------------------------------------------------------------------------------- 1 | const { BaseDanmakuWebSocketSource } = require('../common'); 2 | const localConfig = require('../../dmsrc.config').local; 3 | 4 | class LocalDanmakuSource extends BaseDanmakuWebSocketSource { 5 | constructor(config) { 6 | super(config); 7 | } 8 | 9 | onConnected(socket) { 10 | super.onConnected(socket); 11 | socket.on('send_danmaku', (danmaku) => { 12 | this.sendDanmaku(JSON.parse(danmaku)); 13 | }); 14 | } 15 | 16 | onJoin(roomId) { 17 | super.onJoin(roomId); 18 | } 19 | 20 | onLeave(roomId) { 21 | super.onLeave(roomId); 22 | } 23 | 24 | onDisconnect(reason) { 25 | super.onDisconnect(reason); 26 | } 27 | } 28 | 29 | const src = new LocalDanmakuSource(localConfig); 30 | src.listen(); 31 | src.logger.info('Local Danmaku Source Server is listening at port ' + src.port); 32 | -------------------------------------------------------------------------------- /test/dmsrc/local-src-sender.js: -------------------------------------------------------------------------------- 1 | const ioClient = require('socket.io-client'); 2 | const localConfig = require('../../dmsrc.config').local; 3 | 4 | const socket = ioClient('http://localhost:' + localConfig.port, { 5 | transportOptions: { 6 | polling: { 7 | extraHeaders: { 8 | 'Authorization': localConfig.basicAuth 9 | } 10 | } 11 | } 12 | }); 13 | 14 | socket.on('connect', () => { 15 | console.log('Connected!'); 16 | socket.emit('send_danmaku', JSON.stringify({ 17 | sender: { 18 | uid: 1, 19 | username: 'fython', 20 | url: 'http://localhost/fython' 21 | }, 22 | text: '【Test danmaku', 23 | timestamp: Date.now(), 24 | roomId: 114514 25 | })); 26 | }); 27 | 28 | socket.on('danmaku', () => socket.disconnect()); 29 | socket.on('disconnect', () => process.exit()); 30 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "danmaqua-tgbot", 3 | "version": "2.1.0-beta01", 4 | "description": "Danmaqua Telegram Bot", 5 | "scripts": { 6 | "bot": "node bot/app.js", 7 | "dmsrc:bilibili": "node dmsrc/bilibili/index.js", 8 | "dmsrc:douyu": "node dmsrc/douyu/index.js", 9 | "dmsrc:local": "node dmsrc/local-src/index.js", 10 | "transfer:from_v1": "node bot/util/transfer-helper.js" 11 | }, 12 | "keywords": [], 13 | "author": "fython", 14 | "repository": { 15 | "type": "git", 16 | "url": "https://github.com/danmaqua/danmaqua-telegrambot.git" 17 | }, 18 | "license": "GPL-3.0-only", 19 | "dependencies": { 20 | "async-ratelimiter": "^1.2.8", 21 | "bilibili-live-ws": "^5.0.0", 22 | "douyudm": "^1.3.2-beta.2", 23 | "https-proxy-agent": "^5.0.0", 24 | "ioredis": "^4.17.3", 25 | "log4js": "^6.3.0", 26 | "node-cron": "^2.0.3", 27 | "socket.io": "^2.4.1", 28 | "socket.io-client": "^2.3.0", 29 | "telegraf": "^3.38.0" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Danmaqua Telegram Bot 2 | ====== 3 | 4 | 将哔哩哔哩直播间的同传弹幕转发至 Telegram 聊天、频道以便阅读/存档。 5 | 6 | **版本 2.x 已经做了大量的改动,请仔细阅读配置文档,如有疑问也可直接联系作者咨询。** 7 | 8 | ## 已实现的功能 9 | 10 | - [x] 通过弹幕源 API 从多个直播平台中获取弹幕数据 11 | - [x] 支持 Bilibili 弹幕源(依赖 [simon300000/bilibili-live-ws](https://github.com/simon300000/bilibili-live-ws) ) 12 | - [x] 支持 Douyu 弹幕源(依赖 [flxxyz/douyudm](https://github.com/flxxyz/douyudm) ) 13 | - [x] 将同传弹幕转发到 Telegram 对话/频道 14 | - [x] 每个对话(含频道)配置独立分开,并允许每个对话单独设置管理员 15 | - [x] 使用正则表达式过滤并区分说话人和内容 16 | - [x] 提供黑名单功能屏蔽指定用户的弹幕 17 | - [x] 提供计划任务功能定期切换弹幕房间、定期发送消息到对话 18 | - [x] 访问日志记录 19 | - [x] 通过 HTTP 代理连接 Telegram Bot API 20 | - [x] 提供 Docker 封装镜像 21 | 22 | ## 如何使用 23 | 24 | ### 直接订阅已有的同传弹幕记录频道 25 | 26 | 订阅 Telegram 频道 [@danmaqua](https://t.me/danmaqua) 获取最新同传弹幕记录频道。 27 | 28 | 同传弹幕频道列表网页版(更新不如 Telegram 及时,但便于阅读): 29 | 30 | 如果你有自己搭建的弹幕记录频道,也欢迎提交到这里。 31 | 32 | ### 如何运行自己的机器人实例 33 | 34 | 请认真阅读 [Bot 快速搭建教程](https://danmaqua.github.io/bot/dev.html) 文档,其中包括了全新配置,以及从 Bot v1 版本迁移到 v2 版本的具体教程。 35 | 36 | ## Contact author 37 | 38 | Telegram: [@fython](https://t.me/fython) 39 | 40 | ## Licenses 41 | 42 | GPLv3 43 | -------------------------------------------------------------------------------- /dmsrc/README.md: -------------------------------------------------------------------------------- 1 | 弹幕源服务 2 | ====== 3 | 4 | danmaqua-telegrambot 2.x 已经开始将弹幕 API 的连接部分分离。 5 | 6 | 要为 Bot 提供直播弹幕数据,你需要建立一个 WebSocket 服务器,在你的服务器中实现对直播平台的弹幕连接,将直播平台返回的弹幕数据以统一的数据格式向客户端(Bot)提供。 7 | 8 | 要让 Bot 支持新的弹幕源,你需要修改项目目录的 `bot.config.js` 中的 `danmakuSources` 字段,提供新的弹幕源描述和连接地址。 9 | 10 | 目前我们已经实现了 Bilibili 和 Douyu 直播平台的弹幕源,并提供了默认配置,你可以开箱即用。 11 | 12 | ## Bilibili 弹幕源 13 | 14 | 协议实现依赖于 [simon300000/bilibili-live-ws](https://github.com/simon300000/bilibili-live-ws) 15 | 16 | ### 使用 17 | 18 | 你可以在项目目录中执行 `npm run dmsrc:bilibili` 启动。 19 | 20 | Bilibili 弹幕源服务器的默认 WebSocket 端口为 8001,要修改 Bilibili 直播弹幕源服务的配置可以打开 `dmsrc.config.js` 进行修改。 21 | 22 | 如果修改了 WebSocket 端口,你还需要在 `bot.config.js` 中修改客户端配置,Bot 并不会从 `dmsrc.config.js` 中获取服务器配置。 23 | 24 | ### 其他设置 25 | 26 | [simon300000/bilibili-live-ws](https://github.com/simon300000/bilibili-live-ws) 提供了 WebSocket 和 TCP 两种协议来连接到 Bilibili 官方服务器。 27 | 28 | 你可以根据自己的需求选择一个协议使用,要修改协议配置可以打开 `dmsrc.config.js` 修改 `bilibili.bilibiliProtocol` 字段。 29 | 30 | ## Douyu 弹幕源 31 | 32 | 协议实现依赖于 [flxxyz/douyudm](https://github.com/flxxyz/douyudm) 33 | 34 | ### 使用 35 | 36 | 你可以在项目目录中执行 `npm run dmsrc:douyu` 启动。 37 | 38 | 其余设置与 Bilibili 弹幕源服务器类似。 39 | -------------------------------------------------------------------------------- /bot.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | dataDir: './data', 3 | dataSaveInterval: 10000, 4 | logsDir: './data/logs/bot', 5 | botToken: '', 6 | botProxy: null, 7 | botAdmins: [], 8 | debugMode: false, 9 | rateLimit: { 10 | enabled: false, 11 | redisServer: '127.0.0.1:6379', 12 | selectDB: 1 13 | }, 14 | statistics: { 15 | enabled: false, 16 | redisServer: '127.0.0.1:6379', 17 | selectDB: 1 18 | }, 19 | danmakuSources: [ 20 | { 21 | id: 'bilibili', 22 | description: '哔哩哔哩直播弹幕', 23 | type: 'common-danmaku-ws', 24 | value: { 25 | url: 'localhost:8001', 26 | basicAuth: 'testPassword' 27 | } 28 | }, 29 | { 30 | id: 'douyu', 31 | description: '斗鱼直播弹幕', 32 | type: 'common-danmaku-ws', 33 | value: 'localhost:8002' 34 | }, 35 | { 36 | id: 'local', 37 | description: '本地测试弹幕服务器', 38 | type: 'common-danmaku-ws', 39 | value: 'localhost:8003', 40 | enabled: false 41 | } 42 | ] 43 | }; 44 | -------------------------------------------------------------------------------- /bot/util/transfer-helper.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const botConfig = require('../../bot.config'); 3 | const settingsV2 = require('./settings'); 4 | 5 | function transferDataFromV1() { 6 | if (!fs.existsSync('./data/db.json')) { 7 | console.error('Cannot find ./data/db.json database file! Transfer has been stopped.'); 8 | return; 9 | } 10 | const buf = fs.readFileSync('./data/db.json'); 11 | const oldData = JSON.parse(buf.toString('utf-8')); 12 | settingsV2.init(botConfig, false); 13 | console.log('Set global admin to: ' + oldData.admins); 14 | settingsV2.setGlobalAdmin(oldData.admins); 15 | for (let record of oldData.records) { 16 | const chatId = record.chatId; 17 | console.log('Found chat record: id=' + chatId); 18 | const blockedUsers = record.options.blockedUsers.map((value) => 'bilibili_' + value); 19 | settingsV2.setChatRoomId(chatId, record.roomId); 20 | settingsV2.setChatDanmakuSource(chatId, 'bilibili'); 21 | settingsV2.setChatBlockedUsers(chatId, blockedUsers); 22 | console.log('Saved chat config: id=' + chatId + ' value=' + JSON.stringify(settingsV2.chatsConfig[chatId])); 23 | } 24 | console.log('Transfer has been finished. Now saving...'); 25 | settingsV2.saveConfig(); 26 | console.log('Done!'); 27 | } 28 | 29 | transferDataFromV1(); 30 | -------------------------------------------------------------------------------- /dmsrc.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | bilibili: { 3 | /** 4 | * Bilibili 弹幕源 WebSocket 端口 5 | */ 6 | port: 8001, 7 | /** 8 | * 弹幕源 WebSocket 的 HTTP Basic Auth 认证,留空(null 或 undefined)可以关闭认证 9 | */ 10 | basicAuth: 'testPassword', 11 | /** 12 | * Bilibili 弹幕连接协议,ws 代表使用 WebSocket 协议,tcp 代表使用 TCP 协议。 13 | * 协议实现在 https://github.com/simon300000/bilibili-live-ws/blob/master/src/index.ts 14 | */ 15 | bilibiliProtocol: 'ws', 16 | /** 17 | * Bilibili 弹幕房间自动重连计划,使用 CRON 格式 18 | * 避免长时间弹幕连接没有正确返回数据 19 | * 留空(null)可以关闭自动重连 20 | */ 21 | reconnectCron: '0 0 3 * * *', 22 | logsDir: './data/logs/bilibili-dm' 23 | }, 24 | douyu: { 25 | /** 26 | * Douyu 弹幕源 WebSocket 端口 27 | */ 28 | port: 8002, 29 | /** 30 | * 弹幕源 WebSocket 的 HTTP Basic Auth 认证,留空(null 或 undefined)可以关闭认证 31 | */ 32 | basicAuth: null, 33 | /** 34 | * Douyu 弹幕房间自动重连计划,使用 CRON 格式 35 | * 避免长时间弹幕连接没有正确返回数据 36 | * 留空(null)可以关闭自动重连 37 | */ 38 | reconnectCron: '0 0 3 * * *', 39 | logsDir: './data/logs/douyu-dm' 40 | }, 41 | local: { 42 | port: 8003, 43 | basicAuth: null, 44 | logsDir: './data/logs/local-dm' 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /bot/util/rate-limiter.js: -------------------------------------------------------------------------------- 1 | const AsyncRateLimiter = require('async-ratelimiter'); 2 | const Redis = require('ioredis'); 3 | 4 | class RateLimiter { 5 | constructor(botConfig, logger) { 6 | this.enabled = botConfig.rateLimit.enabled; 7 | let redisServer = botConfig.rateLimit.redisServer; 8 | if (!redisServer.startsWith('redis://') && !redisServer.startsWith('rediss://')) { 9 | redisServer = 'redis://' + redisServer; 10 | } 11 | if (!this.enabled) return; 12 | this.client = new Redis(redisServer); 13 | this.logger = logger; 14 | this.selectDBIndex = botConfig.rateLimit.selectDB; 15 | 16 | logger.default.info('RateLimiter: RateLimiter is enabled. Redis server: ' + redisServer); 17 | logger.default.debug('RateLimiter: Since the function is incomplete, it will not affect the sending behavior.'); 18 | 19 | this._selectDanmaquaDB() 20 | .then(() => this.limiter = this._initAsyncRateLimiter()) 21 | .catch((e) => this.logger.default.error(e)); 22 | } 23 | 24 | _initAsyncRateLimiter() { 25 | return new AsyncRateLimiter({ db: this.client, namespace: 'rate_limit' }); 26 | } 27 | 28 | async _selectDanmaquaDB() { 29 | let dbIndex = this.selectDBIndex; 30 | if (isNaN(this.selectDBIndex)) { 31 | dbIndex = await this.client.get('danmaqua:db_index'); 32 | } 33 | if (dbIndex > 0) { 34 | await this.client.select(dbIndex); 35 | } 36 | } 37 | 38 | async getForGlobal() { 39 | return await this.limiter.get({ 40 | id: 'global', 41 | max: 30, 42 | duration: 1000 43 | }); 44 | } 45 | 46 | async getForChatOnly(chatId) { 47 | return await this.limiter.get({ 48 | id: 'chat_' + chatId, 49 | max: 20, 50 | duration: 1000 * 60 51 | }); 52 | } 53 | 54 | async get(chatId) { 55 | const globalRes = await this.getForGlobal(); 56 | const chatRes = await this.getForChatOnly(chatId); 57 | const reset = Math.max(globalRes.reset, chatRes.reset); 58 | if (globalRes.remaining <= 0 || chatRes.remaining <= 0) { 59 | return { 60 | available: false, 61 | reset: reset 62 | }; 63 | } else { 64 | return { 65 | available: true, 66 | reset: reset 67 | }; 68 | } 69 | } 70 | } 71 | 72 | module.exports = RateLimiter; 73 | -------------------------------------------------------------------------------- /bot/api.js: -------------------------------------------------------------------------------- 1 | const EventEmitter = require('events'); 2 | const { MSG_JOIN_ROOM, MSG_LEAVE_ROOM, MSG_RECONNECT_ROOM } = require('../dmsrc/common'); 3 | const ioClient = require('socket.io-client'); 4 | const settings = require('./util/settings'); 5 | 6 | class DanmakuWebSocketSource { 7 | constructor({id, type, socket}) { 8 | this.id = id; 9 | this.type = type; 10 | this.socket = socket; 11 | } 12 | 13 | join(roomId) { 14 | this.socket.emit(MSG_JOIN_ROOM, roomId); 15 | } 16 | 17 | leave(roomId) { 18 | this.socket.emit(MSG_LEAVE_ROOM, roomId); 19 | } 20 | 21 | reconnect(roomId) { 22 | this.socket.emit(MSG_RECONNECT_ROOM, roomId); 23 | } 24 | } 25 | 26 | class DanmakuSourceManager extends EventEmitter { 27 | constructor(logger) { 28 | super(); 29 | this.sourceInstance = {}; 30 | this.logger = logger; 31 | for (let source of settings.danmakuSources) { 32 | if (source.type === 'common-danmaku-ws') { 33 | this.initWebSocketSource(source); 34 | } else { 35 | throw new Error('Source type ' + source.type + ' isn\'t supported!'); 36 | } 37 | } 38 | } 39 | 40 | initWebSocketSource(source) { 41 | const value = source.value; 42 | let url = ''; 43 | let options = null; 44 | if (typeof value === 'string') { 45 | url = value; 46 | } else { 47 | url = value.url; 48 | if (value.basicAuth) { 49 | options = { 50 | transportOptions: { 51 | polling: { extraHeaders: { 'Authorization': value.basicAuth } } 52 | } 53 | } 54 | } 55 | } 56 | const socket = ioClient('http://' + url, options); 57 | socket.on('connect', () => { 58 | this.logger.default.debug(`Danmaku source is connected! [id=${source.id}, url=${url}]`); 59 | this.emit('connect', source); 60 | }); 61 | const instance = new DanmakuWebSocketSource({ 62 | id: source.id, 63 | type: source.type, 64 | socket: socket 65 | }); 66 | socket.on('danmaku', (json) => { 67 | const danmaku = JSON.parse(json); 68 | danmaku.sourceId = source.id; 69 | this.emit('danmaku', danmaku); 70 | }); 71 | this.sourceInstance[source.id] = instance; 72 | } 73 | 74 | joinRoom(sourceId, roomId) { 75 | this.sourceInstance[sourceId].join(roomId); 76 | } 77 | 78 | leaveRoom(sourceId, roomId) { 79 | this.sourceInstance[sourceId].leave(roomId); 80 | } 81 | 82 | reconnectRoom(sourceId, roomId) { 83 | this.sourceInstance[sourceId].reconnect(roomId); 84 | } 85 | 86 | onDanmaku(par1, par2) { 87 | this.on('danmaku', (danmaku) => { 88 | if (typeof par1 === 'string' && typeof par2 === 'function') { 89 | const sourceId = par1; 90 | const callback = par2; 91 | if (danmaku.sourceId === sourceId) { 92 | callback(danmaku); 93 | } 94 | } else if (typeof par1 === 'function') { 95 | const callback = par1; 96 | callback(danmaku); 97 | } else { 98 | throw new Error('par1 should be String or Function.'); 99 | } 100 | }); 101 | } 102 | } 103 | 104 | module.exports = { 105 | DanmakuSourceManager 106 | }; 107 | -------------------------------------------------------------------------------- /bot/util/statistics.js: -------------------------------------------------------------------------------- 1 | const Redis = require('ioredis'); 2 | 3 | class DanmakuStatistics { 4 | constructor(botConfig, logger) { 5 | this.enabled = botConfig.statistics.enabled; 6 | let redisServer = botConfig.statistics.redisServer; 7 | if (!redisServer.startsWith('redis://') && !redisServer.startsWith('rediss://')) { 8 | redisServer = 'redis://' + redisServer; 9 | } 10 | if (!this.enabled) return; 11 | this.client = new Redis(redisServer); 12 | this.logger = logger; 13 | this.selectDBIndex = botConfig.statistics.selectDB; 14 | 15 | logger.default.info('DanmakuStatistics: DanmakuStatistics is enabled. Redis server: ' + redisServer); 16 | 17 | this._selectDanmaquaDB().catch((e) => { 18 | this.logger.default.error(e); 19 | }); 20 | } 21 | 22 | async _selectDanmaquaDB() { 23 | let dbIndex = this.selectDBIndex; 24 | if (isNaN(this.selectDBIndex)) { 25 | dbIndex = await this.client.get('danmaqua:db_index'); 26 | } 27 | if (dbIndex > 0) { 28 | await this.client.select(dbIndex); 29 | } 30 | } 31 | 32 | async incrementSentences(userId, roomId) { 33 | if (!this.enabled) return; 34 | await this.client.sadd('users', userId); 35 | await this.client.sadd('rooms', roomId); 36 | return await this.client.incr(`sentences:${userId}:${roomId}`); 37 | } 38 | 39 | async incrementWordsBy(userId, roomId, count) { 40 | if (!this.enabled) return; 41 | await this.client.sadd('users', userId); 42 | await this.client.sadd('rooms', roomId); 43 | return await this.client.incrby(`words:${userId}:${roomId}`, count); 44 | } 45 | 46 | async getUsers() { 47 | if (!this.enabled) return []; 48 | return await this.client.smembers('users'); 49 | } 50 | 51 | async getRooms() { 52 | if (!this.enabled) return []; 53 | return await this.client.smembers('rooms'); 54 | } 55 | 56 | async getSentencesEntry(userId, roomId) { 57 | if (!this.enabled) return 0; 58 | return Number(await this.client.get(`sentences:${userId}:${roomId}`)); 59 | } 60 | 61 | async getWordsEntry(userId, roomId) { 62 | if (!this.enabled) return 0; 63 | return Number(await this.client.get(`words:${userId}:${roomId}`)); 64 | } 65 | 66 | async countSentencesByUserId(userId) { 67 | if (!this.enabled) return 0; 68 | const keys = await this.client.keys(`sentences:${userId}:*`); 69 | let sum = 0; 70 | for (let key of keys) { 71 | sum += Number(await this.client.get(key)); 72 | } 73 | return sum; 74 | } 75 | 76 | async countWordsByUserId(userId) { 77 | if (!this.enabled) return 0; 78 | const keys = await this.client.keys(`words:${userId}:*`); 79 | let sum = 0; 80 | for (let key of keys) { 81 | sum += Number(await this.client.get(key)); 82 | } 83 | return sum; 84 | } 85 | 86 | async countSentencesByRoomId(roomId) { 87 | if (!this.enabled) return 0; 88 | const keys = await this.client.keys(`sentences:*:${roomId}`); 89 | let sum = 0; 90 | for (let key of keys) { 91 | sum += Number(await this.client.get(key)); 92 | } 93 | return sum; 94 | } 95 | 96 | async countWordsByRoomId(roomId) { 97 | if (!this.enabled) return 0; 98 | const keys = await this.client.keys(`words:*:${roomId}`); 99 | let sum = 0; 100 | for (let key of keys) { 101 | sum += Number(await this.client.get(key)); 102 | } 103 | return sum; 104 | } 105 | } 106 | 107 | module.exports = { 108 | DanmakuStatistics, 109 | }; 110 | -------------------------------------------------------------------------------- /dmsrc/common/index.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | const ioServer = require('socket.io'); 3 | const log4js = require('log4js'); 4 | const path = require('path'); 5 | 6 | const MSG_JOIN_ROOM = 'join_room'; 7 | const MSG_LEAVE_ROOM = 'leave_room'; 8 | const MSG_RECONNECT_ROOM = 'reconnect_room'; 9 | 10 | class Danmaku { 11 | constructor({sender: {uid, username, url}, text, timestamp, roomId}) { 12 | this.sender = {uid, username, url}; 13 | this.text = text; 14 | this.timestamp = timestamp; 15 | this.roomId = roomId; 16 | } 17 | } 18 | 19 | class BaseDanmakuWebSocketSource { 20 | constructor(config) { 21 | log4js.configure({ 22 | appenders: { 23 | stdout: { type: 'stdout' }, 24 | outfile: { 25 | type: 'dateFile', 26 | filename: path.join(config.logsDir, 'access-log'), 27 | pattern: 'yyyy-MM-dd.log', 28 | alwaysIncludePattern: true, 29 | keepFileExt: false 30 | } 31 | }, 32 | categories: { 33 | default: { 34 | appenders: ['stdout', 'outfile'], 35 | level: 'debug' 36 | } 37 | } 38 | }); 39 | this.logger = log4js.getLogger('default'); 40 | this.port = config.port; 41 | this.basicAuth = config.basicAuth; 42 | this.server = http.createServer(); 43 | this.io = ioServer(this.server); 44 | 45 | this.io.use((socket, next) => { 46 | if (this.basicAuth) { 47 | const authHeader = socket.handshake.headers['authorization']; 48 | if (this.basicAuth !== authHeader) { 49 | this.logger.error('Remote address=' + socket.handshake.address + ' attempt to connect socket ' + 50 | 'with Authorization=' + authHeader + '. Refused due to incorrect auth.') 51 | return next(new Error('Authentication error.')); 52 | } 53 | } 54 | return next(); 55 | }); 56 | this.io.on('connection', (socket) => { 57 | this.onConnected(socket); 58 | const connectedRooms = []; 59 | socket.on(MSG_JOIN_ROOM, (roomId) => { 60 | this.onJoin(roomId); 61 | connectedRooms.push(roomId); 62 | }); 63 | socket.on(MSG_LEAVE_ROOM, (roomId) => { 64 | this.onLeave(roomId); 65 | const index = connectedRooms.indexOf(roomId); 66 | if (index >= 0) { 67 | connectedRooms.splice(index, 1); 68 | } 69 | }); 70 | socket.on(MSG_RECONNECT_ROOM, (roomId) => { 71 | this.onReconnect(roomId); 72 | }); 73 | socket.on('disconnect', (reason) => { 74 | this.onDisconnect(reason); 75 | for (let room of connectedRooms) { 76 | this.onLeave(room); 77 | } 78 | }); 79 | }); 80 | } 81 | 82 | onConnected(socket) { 83 | this.logger.debug('onConnected: socket address=' + socket.handshake.address + ' called.'); 84 | } 85 | 86 | onJoin(roomId) { 87 | this.logger.debug('onJoin: roomId=' + roomId + ' called.'); 88 | } 89 | 90 | onLeave(roomId) { 91 | this.logger.debug('onLeave: roomId=' + roomId + ' called.'); 92 | } 93 | 94 | onReconnect(roomId) { 95 | this.logger.debug('onReconnect: roomId=' + roomId + ' called.'); 96 | } 97 | 98 | onDisconnect(reason) { 99 | this.logger.debug('onDisconnect: reason=' + reason + ' called.') 100 | } 101 | 102 | sendDanmaku(danmaku) { 103 | this.io.sockets.emit('danmaku', JSON.stringify(danmaku)); 104 | } 105 | 106 | listen() { 107 | this.server.listen(this.port); 108 | } 109 | } 110 | 111 | module.exports = { Danmaku, BaseDanmakuWebSocketSource, MSG_JOIN_ROOM, MSG_LEAVE_ROOM, MSG_RECONNECT_ROOM }; 112 | -------------------------------------------------------------------------------- /dmsrc/douyu/index.js: -------------------------------------------------------------------------------- 1 | const { Danmaku, BaseDanmakuWebSocketSource } = require('../common'); 2 | const DouyuDM = require('douyudm'); 3 | const cron = require('node-cron'); 4 | const douyuConfig = require('../../dmsrc.config').douyu; 5 | 6 | const BATCH_RECONNECT_DELAY = 1000 * 10; 7 | 8 | function delay(ms) { 9 | return new Promise((resolve) => setTimeout(() => resolve(), ms)); 10 | } 11 | 12 | class DouyuDanmakuSource extends BaseDanmakuWebSocketSource { 13 | constructor(config) { 14 | super(config); 15 | this.liveList = {}; 16 | if (config.reconnectCron) { 17 | this.logger.info('Reconnect task schedule at "' + config.reconnectCron + '"'); 18 | cron.schedule(config.reconnectCron, () => this.batchReconnect()); 19 | } 20 | } 21 | 22 | isConnected(roomId) { 23 | const entity = this.liveList[roomId]; 24 | return entity && entity.live; 25 | } 26 | 27 | createLive(roomId) { 28 | const live = new DouyuDM(roomId, { debug: false }); 29 | live.on('connect', () => { 30 | this.logger.debug(`Connect to live room: ${roomId}`); 31 | }); 32 | live.on('chatmsg', (data) => { 33 | const dmSenderUid = data.uid; 34 | const dmSenderUsername = data.nn; 35 | const dmSenderUrl = 'https://yuba.douyu.com/wbapi/web/jumpusercenter?id=' + dmSenderUid + 36 | '&name=' + encodeURIComponent(dmSenderUsername); 37 | const dmText = data.txt; 38 | const dmTimestamp = data.cst; 39 | 40 | const danmaku = new Danmaku({ 41 | sender: { 42 | uid: dmSenderUid, 43 | username: dmSenderUsername, 44 | url: dmSenderUrl 45 | }, 46 | text: dmText, 47 | timestamp: dmTimestamp, 48 | roomId: roomId 49 | }); 50 | this.sendDanmaku(danmaku); 51 | }); 52 | live.on('error', (e) => { 53 | this.logger.error(`DouyuDanmakuSource roomId=${roomId} error:`, e); 54 | }); 55 | live.run(); 56 | return live; 57 | } 58 | 59 | onJoin(roomId) { 60 | super.onJoin(roomId); 61 | if (this.isConnected(roomId)) { 62 | this.liveList[roomId].counter++; 63 | return; 64 | } 65 | try { 66 | this.liveList[roomId] = { 67 | live: this.createLive(roomId), 68 | counter: 1 69 | }; 70 | } catch (e) { 71 | this.logger.error(e); 72 | } 73 | } 74 | 75 | onLeave(roomId) { 76 | super.onLeave(roomId); 77 | if (!this.isConnected(roomId)) { 78 | return; 79 | } 80 | try { 81 | const entity = this.liveList[roomId]; 82 | entity.counter--; 83 | if (entity.counter <= 0) { 84 | this.logger.debug(`Room ${roomId} is no longer used. Close now.`); 85 | entity.live.logout(); 86 | delete this.liveList[roomId]; 87 | } 88 | } catch (e) { 89 | this.logger.error(e); 90 | } 91 | } 92 | 93 | onReconnect(roomId) { 94 | super.onReconnect(roomId); 95 | if (!this.isConnected(roomId)) { 96 | return; 97 | } 98 | try { 99 | const entity = this.liveList[roomId]; 100 | entity.live.logout(); 101 | entity.live = this.createLive(roomId); 102 | } catch (e) { 103 | this.logger.error(e); 104 | } 105 | } 106 | 107 | batchReconnect = async () => { 108 | this.logger.debug('Start batch reconnect task'); 109 | for (let roomId of Object.keys(this.liveList)) { 110 | this.onReconnect(Number(roomId)); 111 | await delay(BATCH_RECONNECT_DELAY); 112 | } 113 | } 114 | } 115 | 116 | const src = new DouyuDanmakuSource(douyuConfig); 117 | src.listen(); 118 | src.logger.info('Douyu Danmaku Source Server is listening at port ' + src.port); 119 | -------------------------------------------------------------------------------- /dmsrc/bilibili/index.js: -------------------------------------------------------------------------------- 1 | const { Danmaku, BaseDanmakuWebSocketSource } = require('../common'); 2 | const { KeepLiveWS, KeepLiveTCP } = require('bilibili-live-ws'); 3 | const cron = require('node-cron'); 4 | const bilibiliConfig = require('../../dmsrc.config').bilibili; 5 | 6 | const BATCH_RECONNECT_DELAY = 1000 * 10; 7 | 8 | function delay(ms) { 9 | return new Promise((resolve) => setTimeout(() => resolve(), ms)); 10 | } 11 | 12 | class BilibiliDanmakuSource extends BaseDanmakuWebSocketSource { 13 | constructor(config) { 14 | super(config); 15 | this.liveList = {}; 16 | this.bilibiliProtocol = config.bilibiliProtocol; 17 | if (this.bilibiliProtocol !== 'ws' && this.bilibiliProtocol !== 'tcp') { 18 | this.logger.info('Bilibili Danmaku Source configuration didn\'t specify protocol type. Set to ws as default.'); 19 | this.bilibiliProtocol = 'ws'; 20 | } 21 | if (config.reconnectCron) { 22 | this.logger.info('Reconnect task schedule at "' + config.reconnectCron + '"'); 23 | cron.schedule(config.reconnectCron, () => this.batchReconnect()); 24 | } 25 | } 26 | 27 | isConnected(roomId) { 28 | const entity = this.liveList[roomId]; 29 | return entity && entity.live; 30 | } 31 | 32 | createLive(roomId) { 33 | const live = this.bilibiliProtocol === 'ws' ? new KeepLiveWS(roomId) : new KeepLiveTCP(roomId); 34 | live.on('live', () => { 35 | this.logger.debug(`Connected to live room: ${roomId}`); 36 | }); 37 | live.on('DANMU_MSG', (data) => { 38 | const dmInfo = data['info']; 39 | const dmSenderInfo = dmInfo[2]; 40 | const dmSenderUid = dmSenderInfo[0]; 41 | const dmSenderUsername = dmSenderInfo[1]; 42 | const dmSenderUrl = 'https://space.bilibili.com/' + dmSenderUid; 43 | const dmText = dmInfo[1]; 44 | const dmTimestamp = dmInfo[9]['ts']; 45 | 46 | const danmaku = new Danmaku({ 47 | sender: { 48 | uid: dmSenderUid, 49 | username: dmSenderUsername, 50 | url: dmSenderUrl 51 | }, 52 | text: dmText, 53 | timestamp: dmTimestamp, 54 | roomId: roomId 55 | }); 56 | this.sendDanmaku(danmaku); 57 | }); 58 | live.on('error', (e) => { 59 | this.logger.error(`BilibiliDanmakuSource roomId=${roomId} error:`, e); 60 | }); 61 | return live; 62 | } 63 | 64 | onJoin(roomId) { 65 | super.onJoin(roomId); 66 | if (this.isConnected(roomId)) { 67 | this.liveList[roomId].counter++; 68 | return; 69 | } 70 | try { 71 | this.liveList[roomId] = { 72 | live: this.createLive(roomId), 73 | counter: 1 74 | }; 75 | } catch (e) { 76 | this.logger.error(e); 77 | } 78 | } 79 | 80 | onLeave(roomId) { 81 | super.onLeave(roomId); 82 | if (!this.isConnected(roomId)) { 83 | return; 84 | } 85 | try { 86 | const entity = this.liveList[roomId]; 87 | entity.counter--; 88 | if (entity.counter <= 0) { 89 | this.logger.debug(`Room ${roomId} is no longer used. Close now.`); 90 | entity.live.close(); 91 | delete this.liveList[roomId]; 92 | } 93 | } catch (e) { 94 | this.logger.error(e); 95 | } 96 | } 97 | 98 | onReconnect(roomId) { 99 | super.onReconnect(roomId); 100 | if (!this.isConnected(roomId)) { 101 | return; 102 | } 103 | try { 104 | const entity = this.liveList[roomId]; 105 | entity.live.close(); 106 | entity.live = this.createLive(roomId); 107 | } catch (e) { 108 | this.logger.error(e); 109 | } 110 | } 111 | 112 | batchReconnect = async () => { 113 | this.logger.debug('Start batch reconnect task'); 114 | for (let roomId of Object.keys(this.liveList)) { 115 | this.onReconnect(Number(roomId)); 116 | await delay(BATCH_RECONNECT_DELAY); 117 | } 118 | } 119 | } 120 | 121 | const src = new BilibiliDanmakuSource(bilibiliConfig); 122 | src.listen(); 123 | src.logger.info('Bilibili Danmaku Source Server is listening at port ' + src.port); 124 | -------------------------------------------------------------------------------- /bot/util/schedulers.js: -------------------------------------------------------------------------------- 1 | const cron = require('node-cron'); 2 | 3 | class ChatsScheduler { 4 | static OP_SET_ROOM = 'set_room'; 5 | static OP_SEND_TEXT = 'send_text'; 6 | static OP_SEND_HTML = 'send_html'; 7 | 8 | constructor({ bot, settings, logger }) { 9 | this.chatSchedulers = {}; 10 | this.timezone = 'Asia/Shanghai'; 11 | this.bot = bot; 12 | this.settings = settings; 13 | this.logger = logger; 14 | 15 | const configs = settings.getChatConfigs(); 16 | for (let chatId of Object.keys(configs)) { 17 | const chatConfig = configs[chatId]; 18 | const schedules = chatConfig.schedules || []; 19 | for (let s of schedules) { 20 | this.addScheduler(chatId, s.expression, s.action); 21 | } 22 | } 23 | } 24 | 25 | validateExpression(expression) { 26 | return cron.validate(expression); 27 | } 28 | 29 | validateAction(action) { 30 | const [op, ...args] = action.split(' '); 31 | if (op === ChatsScheduler.OP_SET_ROOM) { 32 | if (args.length !== 1 && args.length !== 2) { 33 | return false; 34 | } 35 | if (args.length === 2) { 36 | const src = this.settings.getDanmakuSource(args[1]); 37 | if (!src) { 38 | return false; 39 | } 40 | } 41 | if (isNaN(Number(args[0]))) { 42 | return false; 43 | } 44 | return true; 45 | } else if (op === ChatsScheduler.OP_SEND_TEXT) { 46 | return args.length > 0; 47 | } else if (op === ChatsScheduler.OP_SEND_HTML) { 48 | return args.length > 0; 49 | } 50 | return false; 51 | } 52 | 53 | addScheduler(chatId, expression, action) { 54 | const s = this._ensureChatSchedulers(chatId); 55 | const obj = { 56 | expression, 57 | action 58 | }; 59 | obj.instance = cron.schedule( 60 | expression, 61 | () => this.resolveAction(chatId, action), 62 | { timezone: this.timezone } 63 | ); 64 | s.push(obj); 65 | } 66 | 67 | removeScheduler(chatId, expression) { 68 | const index = this.indexOfScheduler(chatId, expression); 69 | if (index >= 0) { 70 | const s = this._ensureChatSchedulers(chatId)[index]; 71 | s.instance.destroy(); 72 | this._ensureChatSchedulers(chatId).splice(index, 1); 73 | } 74 | } 75 | 76 | clearSchedulersForChat(chatId) { 77 | const schedulers = this._ensureChatSchedulers(chatId); 78 | for (let s of schedulers) { 79 | s.instance.destroy(); 80 | } 81 | this.chatSchedulers[chatId] = []; 82 | } 83 | 84 | findScheduler(chatId, expression) { 85 | return this._ensureChatSchedulers(chatId).find((s) => s.expression === expression); 86 | } 87 | 88 | indexOfScheduler(chatId, expression) { 89 | return this._ensureChatSchedulers(chatId).findIndex((s) => s.expression === expression); 90 | } 91 | 92 | async resolveAction(chatId, action) { 93 | this.logger.default.info(`Resolve action: chatId=${chatId} action=${action}`); 94 | const [op, ...args] = action.split(' '); 95 | try { 96 | if (op === ChatsScheduler.OP_SET_ROOM) { 97 | let [roomId, src] = args; 98 | roomId = Number(roomId); 99 | this.bot.doRegisterChat(chatId, roomId, src); 100 | } else if (op === ChatsScheduler.OP_SEND_TEXT) { 101 | const msg = args.reduce((a, b) => `${a} ${b}`); 102 | await this.bot.sendPlainText(chatId, msg); 103 | } else if (op === ChatsScheduler.OP_SEND_HTML) { 104 | const msg = args.reduce((a, b) => `${a} ${b}`); 105 | await this.bot.sendHtml(chatId, msg); 106 | } 107 | this.bot.notifyActionDone(chatId, action); 108 | } catch (e) { 109 | this.logger.default.error(e); 110 | this.bot.notifyActionError(chatId, action, e); 111 | } 112 | } 113 | 114 | _ensureChatSchedulers(chatId) { 115 | if (!Object.keys(this.chatSchedulers).find(value => value == chatId)) { 116 | this.chatSchedulers[chatId] = []; 117 | } 118 | return this.chatSchedulers[chatId]; 119 | } 120 | } 121 | 122 | module.exports = { 123 | ChatsScheduler, 124 | }; -------------------------------------------------------------------------------- /bot/app.js: -------------------------------------------------------------------------------- 1 | const botConfig = require('../bot.config'); 2 | const settings = require('./util/settings'); 3 | const RateLimiter = require('./util/rate-limiter'); 4 | const { ChatsScheduler } = require('./util/schedulers'); 5 | const { DanmakuStatistics } = require('./util/statistics'); 6 | 7 | const HttpsProxyAgent = require('https-proxy-agent'); 8 | const { DanmakuSourceManager } = require('./api'); 9 | const log4js = require('log4js'); 10 | const path = require('path'); 11 | 12 | const DanmaquaBot = require('./bot-core'); 13 | 14 | class Application { 15 | constructor(botConfig) { 16 | // 初始化日志 17 | log4js.configure({ 18 | appenders: { 19 | stdout: { 20 | type: 'stdout' 21 | }, 22 | outfile: { 23 | type: 'dateFile', 24 | filename: path.join(botConfig.logsDir, 'access-log'), 25 | pattern: 'yyyy-MM-dd.log', 26 | alwaysIncludePattern: true, 27 | keepFileExt: false 28 | } 29 | }, 30 | categories: { 31 | default: { 32 | appenders: ['stdout', 'outfile'], 33 | level: 'debug' 34 | }, 35 | access: { 36 | appenders: ['outfile'], 37 | level: 'debug' 38 | } 39 | } 40 | }); 41 | this.logger = { 42 | default: log4js.getLogger('default'), 43 | access: log4js.getLogger('access') 44 | }; 45 | // 初始化 Bot 数据库 46 | settings.init(botConfig, true); 47 | // 初始化弹幕源连接管理器 48 | this.dmSrc = new DanmakuSourceManager(this.logger); 49 | // 设定代理 50 | this.agent = null; 51 | if (botConfig.botProxy) { 52 | this.agent = new HttpsProxyAgent(botConfig.botProxy); 53 | this.logger.default.info('Launcher: Bot is using proxy ', botConfig.botProxy); 54 | } 55 | // 初始化 Bot 核心 56 | this.bot = new DanmaquaBot({ 57 | botConfig: botConfig, 58 | dmSrc: this.dmSrc, 59 | botToken: botConfig.botToken, 60 | agent: this.agent, 61 | logger: this.logger, 62 | debugMode: botConfig.debugMode || false, 63 | // 初始化计划任务管理器 64 | chatsScheduler: new ChatsScheduler({ 65 | bot: this.bot, 66 | settings: settings, 67 | logger: this.logger, 68 | }), 69 | // 初始化统计器 70 | statistics: new DanmakuStatistics(botConfig, this.logger), 71 | // 初始化限流器 72 | rateLimiter: new RateLimiter(botConfig, this.logger), 73 | }); 74 | // 设置弹幕源事件回调 75 | this.dmSrc.on('danmaku', (danmaku) => { 76 | try { 77 | if (botConfig.debugMode) { 78 | this.logger.default.debug('onReceiveDanmaku: ', danmaku); 79 | } 80 | this.onReceiveDanmaku(danmaku); 81 | } catch (e) { 82 | this.logger.default.error(e); 83 | } 84 | }); 85 | this.dmSrc.on('connect', (source) => { 86 | try { 87 | this.onConnectDMSource(source); 88 | } catch (e) { 89 | this.logger.default.error(e); 90 | } 91 | }); 92 | } 93 | 94 | onReceiveDanmaku(danmaku) { 95 | if (!this.bot.botUser) { 96 | return; 97 | } 98 | for (let chatId of Object.keys(settings.chatsConfig)) { 99 | let chatConfig = settings.chatsConfig[chatId]; 100 | if (chatConfig.roomId) { 101 | chatConfig = settings.getChatConfig(chatId); 102 | if (chatConfig.blockedUsers && 103 | chatConfig.blockedUsers.indexOf(danmaku.sourceId + '_' + danmaku.sender.uid) >= 0) { 104 | return; 105 | } 106 | if (danmaku.sourceId === chatConfig.danmakuSource && danmaku.roomId === chatConfig.roomId) { 107 | const reg = new RegExp(chatConfig.pattern); 108 | if (reg.test(danmaku.text)) { 109 | const opts = { hideUsername: chatConfig.hideUsername }; 110 | this.bot.notifyDanmaku(chatId, danmaku, opts).catch((e) => { 111 | this.logger.access.error(`Failed to notify ${chatId}: `, e); 112 | }); 113 | } 114 | } 115 | } 116 | } 117 | } 118 | 119 | onConnectDMSource(source) { 120 | for (let chatId of Object.keys(settings.chatsConfig)) { 121 | let chatConfig = settings.chatsConfig[chatId]; 122 | if (chatConfig.roomId) { 123 | chatConfig = settings.getChatConfig(chatId); 124 | if (source.id === chatConfig.danmakuSource) { 125 | this.dmSrc.joinRoom(chatConfig.danmakuSource, chatConfig.roomId); 126 | } 127 | } 128 | } 129 | } 130 | 131 | startBot() { 132 | this.bot.start().then(() => { 133 | this.logger.default.info('Launcher: Bot is launched. Username: @' + this.bot.botUser.username); 134 | }).catch((err) => { 135 | this.logger.default.error(err); 136 | }); 137 | } 138 | } 139 | 140 | if (!botConfig.botToken || botConfig.botToken.length === 0) { 141 | if (process.env.DMQ_BOT_TOKEN) { 142 | botConfig.botToken = process.env.DMQ_BOT_TOKEN; 143 | } 144 | } 145 | if (!botConfig.botProxy) { 146 | if (process.env.DMQ_BOT_PROXY) { 147 | botConfig.botProxy = process.env.DMQ_BOT_PROXY; 148 | } 149 | } 150 | if (!botConfig.botAdmins || botConfig.botAdmins.length === 0) { 151 | if (process.env.DMQ_BOT_ADMINS) { 152 | botConfig.botAdmins = process.env.DMQ_BOT_ADMINS.split(',').map(Number); 153 | } 154 | } 155 | new Application(botConfig).startBot(); 156 | -------------------------------------------------------------------------------- /bot/bot-wrapper.js: -------------------------------------------------------------------------------- 1 | const settings = require('./util/settings'); 2 | const Telegraf = require('telegraf'); 3 | const Extra = require('telegraf/extra'); 4 | 5 | class BotWrapper { 6 | constructor({ botConfig, botToken, agent, logger }) { 7 | this.botConfig = botConfig; 8 | this.bot = new Telegraf(botToken, { telegram: { agent } }); 9 | this.botUser = null; 10 | this.logger = logger; 11 | this.commandRecords = []; 12 | this.startCommandSimpleMessage = ''; 13 | this.helpCommandMessageHeader = ''; 14 | 15 | this.bot.catch((e) => { 16 | this.logger.default.error(e); 17 | }); 18 | this.bot.start(this.onCommandStart); 19 | this.bot.command('help', this.onCommandHelp); 20 | } 21 | 22 | user_access_log(userId, out) { 23 | this.logger.access.debug(`UserId=${userId} ${out}`); 24 | } 25 | 26 | start = async () => { 27 | this.logger.default.info('Launcher: Bot is launching...'); 28 | while (!this.botUser) { 29 | try { 30 | this.botUser = await this.bot.telegram.getMe(); 31 | } catch (e) { 32 | console.error(e); 33 | } 34 | } 35 | return await this.bot.launch(); 36 | }; 37 | 38 | getChat = async (chatId) => { 39 | try { 40 | return await this.bot.telegram.getChat(chatId); 41 | } catch (e) { 42 | return null; 43 | } 44 | }; 45 | 46 | hasUserPermissionForBot = (id) => { 47 | return this.botConfig.botAdmins.indexOf(id) !== -1; 48 | }; 49 | 50 | hasPermissionForChat = (id, chatId) => { 51 | return this.hasUserPermissionForBot(id) || settings.getChatConfig(chatId).admin.indexOf(id) !== -1; 52 | }; 53 | 54 | canSendMessageToChat = async (chatId) => { 55 | try { 56 | let member = await this.bot.telegram.getChatMember(chatId, this.botUser.id); 57 | return member.status === 'member' || member.status === 'administrator' || member.status === 'creator'; 58 | } catch (ignored) { 59 | } 60 | return false; 61 | }; 62 | 63 | checkUserPermissionForBot = async (ctx, next) => { 64 | if (!this.hasUserPermissionForBot(ctx.message.from.id)) { 65 | ctx.reply('你不是这个 Bot 的管理员。'); 66 | return; 67 | } 68 | await next(); 69 | }; 70 | 71 | checkUserPermissionForChat = (chatId) => { 72 | return async (ctx, next) => { 73 | if (!this.hasPermissionForChat(ctx.message.from.id, chatId)) { 74 | ctx.reply('你不是这个对话的管理员。'); 75 | return; 76 | } 77 | await next(); 78 | }; 79 | }; 80 | 81 | addCommand({ 82 | command, 83 | title, 84 | description, 85 | help, 86 | botAdminOnly = false, 87 | callback 88 | }) { 89 | if (!command) { 90 | throw new Error('command cannot be empty'); 91 | } 92 | if (!title) { 93 | throw new Error('title cannot be empty'); 94 | } 95 | if (!description) { 96 | throw new Error('description cannot be empty'); 97 | } 98 | if (!help) { 99 | throw new Error('help cannot be empty'); 100 | } 101 | if (this.commandRecords.find((record) => record.command === command)) { 102 | throw new Error(`command "${command}" has been added`); 103 | } 104 | this.commandRecords.push({ 105 | command, 106 | title, 107 | description, 108 | help, 109 | botAdminOnly, 110 | }); 111 | if (botAdminOnly) { 112 | this.bot.command(command, this.checkUserPermissionForBot, (ctx) => { 113 | try { 114 | callback(ctx); 115 | } catch (e) { 116 | this.logger.default.error(e); 117 | } 118 | }); 119 | } else { 120 | this.bot.command(command, (ctx) => { 121 | try { 122 | callback(ctx); 123 | } catch (e) { 124 | this.logger.default.error(e); 125 | } 126 | }); 127 | } 128 | } 129 | 130 | addCommands(commands) { 131 | commands.forEach((item) => this.addCommand(item)); 132 | } 133 | 134 | addActions(actions) { 135 | for (let [triggers, callback] of actions) { 136 | this.bot.action(triggers, async (ctx) => { 137 | try { 138 | await callback(ctx); 139 | } catch (e) { 140 | this.logger.default.error(e); 141 | } 142 | }); 143 | } 144 | } 145 | 146 | onCommandStart = async (ctx) => { 147 | return ctx.reply(this.startCommandSimpleMessage); 148 | }; 149 | 150 | onCommandHelp = async (ctx) => { 151 | let [_, commandName] = ctx.message.text.split(' '); 152 | if (commandName) { 153 | const rec = this.commandRecords.find((record) => record.command === commandName); 154 | if (!rec) { 155 | return ctx.reply(`无法找到命令:${commandName}`); 156 | } else { 157 | let res = '命令 /' + rec.command.replace(/_/g, '\\_'); 158 | res += ' 的帮助说明:\n' + rec.help; 159 | return ctx.reply(res, Extra.markdown()); 160 | } 161 | } 162 | let res = this.helpCommandMessageHeader + '\n'; 163 | res += '支持的命令:\n'; 164 | for (let command of this.commandRecords) { 165 | res += '/' + command.command.replace(/_/g, '\\_') + 166 | ' : **' + command.title + '**' + 167 | ' - ' + command.description + '\n'; 168 | } 169 | if (this.commandRecords.length < 1) { 170 | res += '没有公开的命令。\n'; 171 | } 172 | res += '\n输入 `/help [command]` 可以查询你想了解的命令的使用方法和参数。'; 173 | return ctx.reply(res, Extra.markdown()); 174 | } 175 | } 176 | 177 | module.exports = BotWrapper; 178 | -------------------------------------------------------------------------------- /bot/util/settings.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | 4 | const DEFAULT_PATTERN = '(?^[^〈{〖[〔【]{0,5})([〈{〖[〔【])(?[^〈{〖[〔【〉}〗]〕】]+)([$〉}〗]〕】]?)'; 5 | const DEFAULT_DANMAKU_SOURCE = 'bilibili'; 6 | 7 | class Settings { 8 | dataDir = ''; 9 | dataSaveInterval = 1000; 10 | botToken = ''; 11 | botProxy = ''; 12 | botAdmins = []; 13 | danmakuSources = []; 14 | 15 | globalConfig = {}; 16 | chatsConfig = {}; 17 | 18 | globalConfigPath = ''; 19 | chatsConfigDir = ''; 20 | userStatesPath = ''; 21 | 22 | _saveCallback = null; 23 | 24 | init(botConfig, autoSave) { 25 | if (this._saveCallback) { 26 | clearInterval(this._saveCallback); 27 | } 28 | 29 | // Read bot configuration 30 | this.dataDir = botConfig.dataDir; 31 | this.dataSaveInterval = botConfig.dataSaveInterval; 32 | this.botToken = botConfig.botToken; 33 | this.botProxy = botConfig.botProxy; 34 | this.botAdmins = botConfig.botAdmins; 35 | this.danmakuSources = botConfig.danmakuSources.filter(src => src.enabled !== false); 36 | if (!fs.existsSync(this.dataDir)) { 37 | fs.mkdirSync(path.resolve(this.dataDir)); 38 | } 39 | this.globalConfigPath = path.join(this.dataDir, 'global.json'); 40 | this.chatsConfigDir = path.join(this.dataDir, 'chats'); 41 | this.userStatesPath = path.join(this.dataDir, 'user_states.json'); 42 | 43 | // Read global chat default configuration 44 | let globalConfig = {}; 45 | if (fs.existsSync(this.globalConfigPath)) { 46 | const buf = fs.readFileSync(this.globalConfigPath); 47 | globalConfig = JSON.parse(buf.toString('utf-8')); 48 | } 49 | if (!globalConfig.pattern) { 50 | globalConfig.pattern = DEFAULT_PATTERN; 51 | } 52 | if (!globalConfig.admin) { 53 | globalConfig.admin = []; 54 | } 55 | if (!globalConfig.danmakuSource) { 56 | globalConfig.danmakuSource = DEFAULT_DANMAKU_SOURCE; 57 | } 58 | this.globalConfig = globalConfig; 59 | 60 | // Read chats configuration 61 | let chatsConfig = {}; 62 | if (!fs.existsSync(this.chatsConfigDir)) { 63 | fs.mkdirSync(this.chatsConfigDir); 64 | } 65 | for (let filename of fs.readdirSync(this.chatsConfigDir)) { 66 | if (!filename.endsWith('.json') || filename.indexOf('.') !== filename.lastIndexOf('.')) { 67 | continue; 68 | } 69 | const [chatId] = filename.split('.'); 70 | if (isNaN(chatId)) { 71 | continue; 72 | } 73 | const buf = fs.readFileSync(path.join(this.chatsConfigDir, filename)); 74 | chatsConfig[chatId] = JSON.parse(buf.toString('utf-8')); 75 | } 76 | this.chatsConfig = chatsConfig; 77 | 78 | // Read user states configuration 79 | let userStates = {}; 80 | if (fs.existsSync(this.userStatesPath)) { 81 | const buf = fs.readFileSync(this.userStatesPath); 82 | userStates = JSON.parse(buf.toString('utf-8')); 83 | } 84 | this.userStates = userStates; 85 | 86 | if (autoSave) { 87 | this._saveCallback = setInterval(() => this.saveConfig(), this.dataSaveInterval); 88 | } 89 | } 90 | 91 | saveConfig() { 92 | const globalConfigJson = JSON.stringify(this.globalConfig, null, 4); 93 | fs.writeFileSync(this.globalConfigPath, globalConfigJson); 94 | 95 | for (let chatId of Object.keys(this.chatsConfig)) { 96 | const chatConfigJson = JSON.stringify(this.chatsConfig[chatId], null, 4); 97 | fs.writeFileSync(path.join(this.chatsConfigDir, `${chatId}.json`), chatConfigJson); 98 | } 99 | 100 | const userStatesJson = JSON.stringify(this.userStates, null, 4); 101 | fs.writeFileSync(this.userStatesPath, userStatesJson); 102 | } 103 | 104 | getChatConfig(chatId) { 105 | const result = Object.assign({}, this.globalConfig, this.chatsConfig[chatId]); 106 | if (!result.danmakuSource) { 107 | result.danmakuSource = this.globalConfig.danmakuSource; 108 | } 109 | return result; 110 | } 111 | 112 | getChatConfigs() { 113 | const result = {}; 114 | for (let chatId of Object.keys(this.chatsConfig)) { 115 | result[chatId] = this.getChatConfig(chatId); 116 | } 117 | return result; 118 | } 119 | 120 | getDanmakuSource(id) { 121 | for (let item of this.danmakuSources) { 122 | if (item.id === id) { 123 | return item; 124 | } 125 | } 126 | return null; 127 | } 128 | 129 | unsetChatRoomId(chatId) { 130 | const c = this._ensureChatConfig(chatId); 131 | c.roomId = undefined; 132 | } 133 | 134 | setChatRoomId(chatId, roomId) { 135 | const c = this._ensureChatConfig(chatId); 136 | c.roomId = roomId; 137 | } 138 | 139 | setChatDanmakuSource(chatId, id) { 140 | const c = this._ensureChatConfig(chatId); 141 | if (id && !this.getDanmakuSource(id)) { 142 | throw new Error('Cannot find danmaku source by id: ' + id); 143 | } 144 | c.danmakuSource = id; 145 | } 146 | 147 | setChatPattern(chatId, pattern) { 148 | const c = this._ensureChatConfig(chatId); 149 | new RegExp(pattern); 150 | c.pattern = pattern; 151 | } 152 | 153 | setChatAdmin(chatId, admin) { 154 | const c = this._ensureChatConfig(chatId); 155 | if (admin instanceof Array) { 156 | c.admin = admin; 157 | } else { 158 | c.admin = []; 159 | } 160 | } 161 | 162 | setChatBlockedUsers(chatId, users) { 163 | const c = this._ensureChatConfig(chatId); 164 | c.blockedUsers = users || []; 165 | } 166 | 167 | addChatBlockedUsers(chatId, userId) { 168 | if (userId.indexOf('_') < 0) { 169 | console.error('Cannot add user id=' + userId + ' to block list. Please check id format.'); 170 | return; 171 | } 172 | const c = this._ensureChatConfig(chatId); 173 | if (!c.blockedUsers) { 174 | c.blockedUsers = []; 175 | } 176 | const index = c.blockedUsers.indexOf(userId); 177 | if (index < 0) { 178 | c.blockedUsers.push(userId); 179 | return true; 180 | } 181 | return false; 182 | } 183 | 184 | removeChatBlockedUsers(chatId, userId) { 185 | if (userId.indexOf('_') < 0) { 186 | console.error('Cannot add user id=' + userId + ' to block list. Please check id format.'); 187 | return; 188 | } 189 | const c = this._ensureChatConfig(chatId); 190 | if (!c.blockedUsers) { 191 | c.blockedUsers = []; 192 | } 193 | const index = c.blockedUsers.indexOf(userId); 194 | if (index >= 0) { 195 | c.blockedUsers.splice(userId, 1); 196 | return true; 197 | } 198 | return false; 199 | } 200 | 201 | containsChatBlockedUser(chatId, userId, source) { 202 | if (source) { 203 | userId = source + '_' + userId; 204 | } 205 | if (userId.indexOf('_') < 0) { 206 | console.error('Cannot add user id=' + userId + ' to block list. Please check id format.'); 207 | return; 208 | } 209 | const c = this._ensureChatConfig(chatId); 210 | if (!c.blockedUsers) { 211 | c.blockedUsers = []; 212 | } 213 | return c.blockedUsers.indexOf(userId) >= 0; 214 | } 215 | 216 | getChatBlockedUsers(chatId) { 217 | const blockedUsers = this.getChatConfig(chatId).blockedUsers || []; 218 | return blockedUsers.map((value) => { 219 | const [dmSrc, userId] = value.split('_'); 220 | return { src: dmSrc, uid: userId }; 221 | }); 222 | } 223 | 224 | setChatSchedules(chatId, schedules) { 225 | const c = this._ensureChatConfig(chatId); 226 | c.schedules = schedules || []; 227 | } 228 | 229 | addChatSchedule(chatId, expression, action) { 230 | const c = this._ensureChatConfig(chatId); 231 | if (!c.schedules) { 232 | c.schedules = []; 233 | } 234 | const index = c.schedules.findIndex(s => s.expression === expression); 235 | if (index < 0) { 236 | c.schedules.push({ expression, action }); 237 | return true; 238 | } 239 | return false; 240 | } 241 | 242 | removeChatSchedule(chatId, expression) { 243 | const c = this._ensureChatConfig(chatId); 244 | if (!c.schedules) { 245 | c.schedules = []; 246 | } 247 | const index = c.schedules.findIndex(s => s.expression === expression); 248 | if (index >= 0) { 249 | c.schedules.splice(index, 1); 250 | return true; 251 | } 252 | return false; 253 | } 254 | 255 | containsChatSchedule(chatId, expression) { 256 | const c = this._ensureChatConfig(chatId); 257 | if (!c.schedules) { 258 | c.schedules = []; 259 | } 260 | return c.schedules.findIndex(s => s.expression === expression) >= 0; 261 | } 262 | 263 | getChatSchedules(chatId) { 264 | const c = this._ensureChatConfig(chatId); 265 | return c.schedules || []; 266 | } 267 | 268 | deleteChatConfig(chatId) { 269 | delete this.chatsConfig[chatId]; 270 | fs.unlinkSync(path.join(this.chatsConfigDir, `${chatId}.json`)); 271 | } 272 | 273 | setGlobalPattern(pattern) { 274 | new RegExp(pattern); 275 | this.globalConfig.pattern = pattern; 276 | } 277 | 278 | setGlobalAdmin(admin) { 279 | if (admin instanceof Array) { 280 | this.globalConfig.admin = admin; 281 | } else { 282 | this.globalConfig.admin = []; 283 | } 284 | } 285 | 286 | setGlobalDanmakuSource(id) { 287 | if (id && !this.getDanmakuSource(id)) { 288 | throw new Error('Cannot find danmaku source by id: ' + id); 289 | } 290 | this.globalConfig.danmakuSource = id; 291 | } 292 | 293 | getUserStateCode(userId) { 294 | const state = this.userStates[userId]; 295 | if (state) { 296 | return state.code; 297 | } else { 298 | return -1; 299 | } 300 | } 301 | 302 | getUserStateData(userId) { 303 | const state = this.userStates[userId]; 304 | if (state) { 305 | return state.data; 306 | } else { 307 | return null; 308 | } 309 | } 310 | 311 | setUserState(userId, code, data) { 312 | if (!Object.keys(this.userStates).find(v => v === userId)) { 313 | this.userStates[userId] = { code, data: data || null }; 314 | } else { 315 | this.userStates[userId].code = code; 316 | if (data !== undefined) { 317 | this.userStates[userId].data = data; 318 | } 319 | } 320 | } 321 | 322 | clearUserState(userId) { 323 | delete this.userStates[userId]; 324 | } 325 | 326 | _ensureChatConfig(chatId) { 327 | if (!Object.keys(this.chatsConfig).find(value => value == chatId)) { 328 | this.chatsConfig[chatId] = {}; 329 | } 330 | return this.chatsConfig[chatId]; 331 | } 332 | 333 | _printConfig() { 334 | console.log('Data dir: ', this.dataDir); 335 | console.log('Global config: ', this.globalConfig); 336 | console.log('Chats config: ', this.chatsConfig); 337 | console.log('User states: ', this.userStates); 338 | } 339 | } 340 | 341 | module.exports = new Settings(); 342 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /bot/bot-core.js: -------------------------------------------------------------------------------- 1 | const settings = require('./util/settings'); 2 | const BotWrapper = require('./bot-wrapper'); 3 | const Extra = require('telegraf/extra'); 4 | const Markup = require('telegraf/markup'); 5 | 6 | const MANAGE_PAGE_MAX_ITEMS = 4; 7 | const USER_STATE_CODE_CHAT_CHANGE_DANMAKU_SRC = 1; 8 | const USER_STATE_CODE_CHAT_CHANGE_PATTERN = 2; 9 | const USER_STATE_CODE_CHAT_CHANGE_ADMIN = 3; 10 | const USER_STATE_CODE_CHAT_CHANGE_BLOCK_USERS = 4; 11 | const USER_STATE_CODE_CHAT_MANAGE_SCHEDULES = 5; 12 | 13 | class DanmaquaBot extends BotWrapper { 14 | constructor({ botConfig, dmSrc, botToken, agent, logger, chatsScheduler, statistics, rateLimiter }) { 15 | super({ botConfig, botToken, agent, logger }); 16 | this.settings = settings; 17 | this.startCommandSimpleMessage = '欢迎使用 Danmaqua Bot!'; 18 | this.dmSrc = dmSrc; 19 | this.chatsScheduler = chatsScheduler; 20 | this.statistics = statistics; 21 | this.rateLimiter = rateLimiter; 22 | 23 | this.addCommands([ 24 | { 25 | command: 'list_dm_src', 26 | title: '查询支持的弹幕源', 27 | description: '查看 Bot 支持哪些直播平台的弹幕源', 28 | help: '使用方法: /list\\_dm\\_src', 29 | botAdminOnly: false, 30 | callback: this.onCommandListDMSrc 31 | }, 32 | { 33 | command: 'register_chat', 34 | title: '注册频道', 35 | description: '让 Bot 将指定直播间的弹幕转发到频道中', 36 | help: '使用方法:/register\\_chat \\[频道ID] \\[直播间号] \\[弹幕源(可选)]', 37 | botAdminOnly: true, 38 | callback: this.onCommandRegisterChat 39 | }, 40 | { 41 | command: 'unregister_chat', 42 | title: '取消注册频道', 43 | description: '对频道取消绑定弹幕转发', 44 | help: '使用方法:/unregister\\_chat \\[频道ID]', 45 | botAdminOnly: true, 46 | callback: this.onCommandUnregisterChat 47 | }, 48 | { 49 | command: 'manage_chats', 50 | title: '管理频道', 51 | description: '列出已经绑定了弹幕转发的频道,并进行选择管理', 52 | help: '使用方法:/manage\\_chats', 53 | botAdminOnly: false, 54 | callback: this.onCommandManageChats 55 | }, 56 | { 57 | command: 'manage_chat', 58 | title: '管理指定的频道', 59 | description: '管理指定的已绑定弹幕转发的频道', 60 | help: '使用方法:/manage\\_chat \\[频道ID]', 61 | botAdminOnly: false, 62 | callback: this.onCommandManageChat 63 | }, 64 | { 65 | command: 'set_default_admins', 66 | title: '设置默认管理员', 67 | description: '设置各个频道的默认管理员(并非 Bot 管理员)', 68 | help: '使用方法:/set\\_default\\_admins \\[第一个管理员ID] \\[第二个管理员ID] ...', 69 | botAdminOnly: true, 70 | callback: this.onCommandSetDefaultAdmins 71 | }, 72 | { 73 | command: 'set_default_pattern', 74 | title: '设置默认过滤规则', 75 | description: '设置各个频道的默认过滤规则', 76 | help: '使用方法:/set\\_default\\_pattern \\[正则表达式]', 77 | botAdminOnly: true, 78 | callback: this.onCommandSetDefaultPattern 79 | }, 80 | { 81 | command: 'set_default_source', 82 | title: '设置默认弹幕源', 83 | description: '设置各个频道的默认弹幕源', 84 | help: '使用方法:/set\\_default\\_source \\[弹幕源 ID]', 85 | botAdminOnly: true, 86 | callback: this.onCommandSetDefaultSource 87 | }, 88 | { 89 | command: 'stat_users', 90 | title: '查看参与同传的用户统计列表', 91 | description: 'Bot 启用弹幕统计时,可以通过这个命令查看曾经发送同传弹幕的用户列表', 92 | help: '使用方法:/stat\\_users', 93 | botAdminOnly: false, 94 | callback: this.onCommandStatUsers 95 | }, 96 | { 97 | command: 'stat_user_query', 98 | title: '查询指定 ID 的用户统计', 99 | description: 'Bot 启用弹幕统计时,可以通过这个命令查看指定 ID 曾经发送的同传弹幕统计信息', 100 | help: '使用方法:/stat\\_user_query [统计用户 ID]', 101 | botAdminOnly: false, 102 | callback: this.onCommandStatUserQuery 103 | }, 104 | ]); 105 | this.addActions([ 106 | [/^manage_chat:([-\d]+)/, this.onActionManageChat], 107 | [/^manage_chats_pages:(\d+)/, this.onActionManageChatsPages], 108 | [/^change_danmaku_src:([-\d]+)/, this.onActionChangeDanmakuSrc], 109 | [/^change_pattern:([-\d]+)/, this.onActionChangePattern], 110 | [/^change_admin:([-\d]+)/, this.onActionChangeAdmin], 111 | [/^change_blocked_users:([-\d]+)/, this.onActionChangeBlockedUsers], 112 | [/^unregister_chat:([-\d]+)/, this.onActionUnregisterChat], 113 | [/^confirm_unregister_chat:([-\d]+)/, this.onActionConfirmUnregisterChat], 114 | [/^reconnect_room:([a-zA-Z\d]+)_([-\d]+)/, this.onActionReconnectRoom], 115 | [/^block_user:([-\d]+):([-_a-zA-Z\d]+)/, this.onActionBlockUser], 116 | [/^manage_schedules:([-\d]+)/, this.onActionManageSchedules], 117 | [/^stat_by_chat:([-\d]+)/, this.onActionStatisticsByChat], 118 | ]); 119 | 120 | this.bot.command('cancel', this.onCommandCancel); 121 | this.bot.on('message', this.onMessage); 122 | } 123 | 124 | notifyDanmaku = async (chatId, data, { hideUsername = false }) => { 125 | const userIdWithSrc = data.sourceId + '_' + data.sender.uid; 126 | if (this.statistics.enabled) { 127 | const roomIdWithSrc = data.sourceId + '_' + data.roomId; 128 | this.statistics.incrementSentences(userIdWithSrc, roomIdWithSrc); 129 | this.statistics.incrementWordsBy(userIdWithSrc, roomIdWithSrc, data.text.length); 130 | } 131 | let msg = ''; 132 | if (!hideUsername) { 133 | const url = data.sender.url + '#' + userIdWithSrc; 134 | msg += `${data.sender.username}:`; 135 | } 136 | msg += data.text; 137 | if (this.rateLimiter.enabled) { 138 | const res = await this.rateLimiter.get(chatId); 139 | if (!res.available) { 140 | this.logger.default.debug('Sending messages rate limit exceeded.'); 141 | // TODO 超过频率限制采取不同的行为 142 | } 143 | } 144 | const extras = Extra.HTML().webPreview(false).notifications(false); 145 | const sent = await this.bot.telegram.sendMessage(chatId, msg, extras); 146 | return sent; 147 | }; 148 | 149 | notifyActionDone = (chatId, action) => { 150 | const msgText = 'Bot 已成功于 `' + new Date(Date.now()) + '` 执行操作 `' + action + '`'; 151 | const extras = Extra.markdown(); 152 | for (let admin of settings.getChatConfig(chatId).admin) { 153 | this.bot.telegram.sendMessage(admin, msgText, extras).catch((e) => { 154 | this.logger.default.error(e); 155 | }); 156 | } 157 | }; 158 | 159 | notifyActionError = (chatId, action, e) => { 160 | const msgText = 'Bot 在 `' + new Date(Date.now()) + '` 执行操作 `' + action + 161 | '` 时遭遇错误:\n```' + e + '\n```\n'; 162 | const extras = Extra.markdown(); 163 | for (let admin of settings.getChatConfig(chatId).admin) { 164 | this.bot.telegram.sendMessage(admin, msgText, extras).catch((e) => { 165 | this.logger.default.error(e); 166 | }); 167 | } 168 | }; 169 | 170 | sendPlainText = async (chatId, text) => { 171 | return await this.bot.telegram.sendMessage(chatId, text); 172 | }; 173 | 174 | sendHtml = async (chatId, htmlText) => { 175 | return await this.bot.telegram.sendMessage(chatId, htmlText, Extra.HTML()); 176 | } 177 | 178 | getManagedChatsConfig = (userId) => { 179 | const result = []; 180 | const chatConfigs = settings.getChatConfigs(); 181 | for (let chatId of Object.keys(chatConfigs)) { 182 | const chatConfig = Object.assign({}, chatConfigs[chatId], { chatId }); 183 | if (this.hasUserPermissionForBot(userId) || chatConfig.admin.indexOf(userId) !== -1) { 184 | result.push(chatConfig); 185 | } 186 | } 187 | return result; 188 | }; 189 | 190 | getManagedChatsCount = (userId) => { 191 | let count = 0; 192 | const chatConfigs = settings.getChatConfigs(); 193 | for (let chatId of Object.keys(chatConfigs)) { 194 | const chatConfig = Object.assign({}, chatConfigs[chatId], { chatId }); 195 | if (this.hasUserPermissionForBot(userId) || chatConfig.admin.indexOf(userId) !== -1) { 196 | count++; 197 | } 198 | } 199 | return count; 200 | } 201 | 202 | getManagedChatsPageCount = (userId) => { 203 | return Math.ceil(this.getManagedChatsCount(userId) / MANAGE_PAGE_MAX_ITEMS); 204 | } 205 | 206 | getManagedChatsConfigByPage = (userId, page) => { 207 | const chatConfigs = this.getManagedChatsConfig(userId); 208 | const minIndex = page * MANAGE_PAGE_MAX_ITEMS; 209 | const maxIndex = minIndex + MANAGE_PAGE_MAX_ITEMS; 210 | return chatConfigs.filter((v, index) => index >= minIndex && index < maxIndex); 211 | }; 212 | 213 | onMessage = async (ctx) => { 214 | if (ctx.message.forward_from_chat) { 215 | if (await this.onForwardMessageFromChat(ctx)) { 216 | return; 217 | } 218 | } 219 | const userId = ctx.message.from.id; 220 | const stateCode = settings.getUserStateCode(userId); 221 | const stateData = settings.getUserStateData(userId); 222 | if (stateCode === USER_STATE_CODE_CHAT_CHANGE_DANMAKU_SRC) { 223 | this.onAnswerChangeDanmakuSrc(ctx, stateData); 224 | } else if (stateCode === USER_STATE_CODE_CHAT_CHANGE_PATTERN) { 225 | this.onAnswerChangePattern(ctx, stateData); 226 | } else if (stateCode === USER_STATE_CODE_CHAT_CHANGE_ADMIN) { 227 | this.onAnswerChangeAdmin(ctx, stateData); 228 | } else if (stateCode === USER_STATE_CODE_CHAT_CHANGE_BLOCK_USERS) { 229 | this.onAnswerChangeBlockedUsers(ctx, stateData); 230 | } else if (stateCode === USER_STATE_CODE_CHAT_MANAGE_SCHEDULES) { 231 | this.onAnswerManageSchedules(ctx, stateData); 232 | } 233 | }; 234 | 235 | onForwardMessageFromChat = async (ctx) => { 236 | const chatId = ctx.message.forward_from_chat.id; 237 | if (!ctx.message.text || ctx.message.chat.type !== 'private') { 238 | return; 239 | } 240 | if (!this.hasPermissionForChat(ctx.message.from.id, chatId)) { 241 | ctx.reply('你没有这个对话的管理权限。'); 242 | return; 243 | } 244 | if (!settings.getChatConfig(chatId)) { 245 | ctx.reply('这个对话没有在 Bot 注册。'); 246 | return; 247 | } 248 | // 提取弹幕中的用户信息,如果没有则提示错误 249 | let username = null; 250 | let uid = 0; 251 | if (ctx.message.entities.length === 1) { 252 | const firstEntity = ctx.message.entities[0]; 253 | if (firstEntity.type === 'text_link') { 254 | const [_, result] = firstEntity.url.split('#'); 255 | if (result && result.indexOf('_') >= 0) { 256 | uid = result; 257 | username = ctx.message.text.substr(firstEntity.offset, firstEntity.length); 258 | } 259 | } 260 | } 261 | if (!username) { 262 | ctx.reply('这条消息无法寻找到弹幕用户信息。'); 263 | return; 264 | } 265 | ctx.reply('你要对这条弹幕进行什么操作:', Extra.inReplyTo(ctx.message.message_id) 266 | .markup(Markup.inlineKeyboard([ 267 | Markup.callbackButton( 268 | `屏蔽用户:${username}(${uid})`, 269 | `block_user:${chatId}:${uid}` 270 | ) 271 | ]))); 272 | }; 273 | 274 | onActionBlockUser = async (ctx) => { 275 | const actionUser = ctx.update.callback_query.from; 276 | const chatId = ctx.match[1]; 277 | const uid = ctx.match[2]; 278 | if (!this.hasPermissionForChat(actionUser.id, chatId)) { 279 | return await ctx.answerCbQuery('你没有权限设置这个对话。', true); 280 | } 281 | if (!settings.getChatConfig(chatId)) { 282 | return await ctx.answerCbQuery('这个对话没有在 Bot 中注册。', true); 283 | } 284 | const isBlocked = settings.containsChatBlockedUser(chatId, uid); 285 | if (isBlocked) { 286 | settings.removeChatBlockedUsers(chatId, uid); 287 | } else { 288 | settings.addChatBlockedUsers(chatId, uid); 289 | } 290 | return await ctx.answerCbQuery( 291 | '用户 ' + uid + ' 已在对话 ' + chatId + ' 中被' + (isBlocked ? '解除屏蔽' : '屏蔽'), 292 | true 293 | ); 294 | }; 295 | 296 | onCommandRegisterChat = async (ctx) => { 297 | let [_, chatId, roomId, source] = ctx.message.text.split(' '); 298 | if (!chatId) { 299 | ctx.reply('注册命令使用方法:/register\_chat `chatId` `roomId` `\\[source]`', Extra.markdown()); 300 | return; 301 | } 302 | if (!roomId) { 303 | ctx.reply('请输入房间号!'); 304 | return; 305 | } 306 | if (isNaN(Number(roomId))) { 307 | ctx.reply('房间号必须是数字。'); 308 | return; 309 | } 310 | if (source && !settings.danmakuSources.find((value) => value.id === source)) { 311 | ctx.reply(`弹幕源 ${source} 不受支持。`); 312 | return; 313 | } 314 | const targetChat = await this.getChat(chatId); 315 | const canSend = targetChat != null && await this.canSendMessageToChat(targetChat.id); 316 | if (!canSend) { 317 | ctx.reply('Bot 不被允许发送消息到对话 ' + (targetChat ? ('id=' + targetChat.id) : chatId)); 318 | return; 319 | } 320 | chatId = targetChat.id; 321 | roomId = Number(roomId); 322 | this.doRegisterChat(chatId, roomId, source); 323 | const curDanmakuSource = settings.getChatConfig(chatId).danmakuSource; 324 | this.user_access_log(ctx.message.from.id, 'Registered chat id=' + chatId + 325 | ' to room: ' + curDanmakuSource + ' ' + roomId); 326 | ctx.reply( 327 | `对话 id=${targetChat.id} 已被注册到弹幕源 ` + 328 | `${curDanmakuSource}:${roomId}` 329 | ); 330 | }; 331 | 332 | doRegisterChat = (chatId, roomId, source) => { 333 | const curRoomId = settings.getChatConfig(chatId).roomId; 334 | let curDanmakuSource = settings.getChatConfig(chatId).danmakuSource; 335 | if (curRoomId !== roomId || curDanmakuSource !== source) { 336 | if (curRoomId) { 337 | this.dmSrc.leaveRoom(curDanmakuSource, curRoomId); 338 | } 339 | settings.setChatRoomId(chatId, roomId); 340 | settings.setChatDanmakuSource(chatId, source); 341 | curDanmakuSource = settings.getChatConfig(chatId).danmakuSource; 342 | this.dmSrc.joinRoom(curDanmakuSource, roomId); 343 | } 344 | }; 345 | 346 | onCommandUnregisterChat = async (ctx) => { 347 | let [_, chatId] = ctx.message.text.split(' '); 348 | if (!chatId) { 349 | ctx.reply('取消注册命令使用方法:/unregister\_chat `chatId`', Extra.markdown()); 350 | return; 351 | } 352 | const targetChat = await this.getChat(chatId || ctx.chat.id); 353 | if (!targetChat) { 354 | ctx.reply('无法找到这个对话。'); 355 | return; 356 | } 357 | chatId = targetChat.id; 358 | this.requestUnregisterChat(ctx, chatId); 359 | }; 360 | 361 | createManageChatsMessageKeyboard = async (userId, page) => { 362 | const buttons = []; 363 | for (let cfg of this.getManagedChatsConfigByPage(userId, page)) { 364 | const chat = await this.getChat(cfg.chatId); 365 | let displayName = '' + cfg.chatId; 366 | if (chat) { 367 | if (chat.title && !chat.username) { 368 | displayName = chat.title; 369 | } else if (!chat.title && chat.username) { 370 | displayName = '@' + chat.username; 371 | } else if (chat.title && chat.username) { 372 | displayName = chat.title + ' (@' + chat.username + ')'; 373 | } 374 | } 375 | buttons.push([Markup.callbackButton(displayName, 'manage_chat:' + cfg.chatId)]); 376 | } 377 | const pageButtons = []; 378 | const pageCount = this.getManagedChatsPageCount(userId); 379 | pageButtons.push(Markup.callbackButton('第' + (page+1) + '/' + pageCount + '页', 'noop')); 380 | if (page > 0) { 381 | pageButtons.push(Markup.callbackButton('上一页', 'manage_chats_pages:' + (page - 1))); 382 | } 383 | if (page < pageCount - 1) { 384 | pageButtons.push(Markup.callbackButton('下一页', 'manage_chats_pages:' + (page + 1))) 385 | } 386 | if (pageButtons.length > 1) { 387 | buttons.push(pageButtons); 388 | } 389 | return Markup.inlineKeyboard(buttons); 390 | }; 391 | 392 | onCommandManageChats = async (ctx) => { 393 | const userId = ctx.message.from.id; 394 | ctx.reply( 395 | '请选择你要管理的频道:\n如果你要找的频道没有显示,可能是你的账号没有权限。', 396 | Extra.markup(await this.createManageChatsMessageKeyboard(userId, 0)) 397 | ); 398 | }; 399 | 400 | onActionManageChatsPages = async (ctx) => { 401 | const userId = ctx.update.callback_query.from.id; 402 | const targetPage = parseInt(ctx.match[1]); 403 | if (targetPage >= 0 && targetPage < this.getManagedChatsPageCount(userId)) { 404 | await ctx.editMessageReplyMarkup(await this.createManageChatsMessageKeyboard(userId, targetPage)); 405 | return await ctx.answerCbQuery(); 406 | } else { 407 | return await ctx.answerCbQuery('你选择的页数 ' + targetPage + ' 不存在。', true); 408 | } 409 | }; 410 | 411 | onActionManageChat = async (ctx) => { 412 | const targetChatId = parseInt(ctx.match[1]); 413 | if (!await this.canSendMessageToChat(targetChatId)) { 414 | return await ctx.answerCbQuery( 415 | '这个机器人无法发送消息给对话:' + targetChatId + '。请检查权限配置是否正确。', true); 416 | } 417 | this.requestManageChat(ctx, targetChatId); 418 | return await ctx.answerCbQuery(); 419 | }; 420 | 421 | requestManageChat = async (ctx, chatId) => { 422 | const chat = await this.getChat(chatId); 423 | let displayName = '' + chat.id; 424 | if (chat.title && !chat.username) { 425 | displayName = chat.title; 426 | } else if (!chat.title && chat.username) { 427 | displayName = '@' + chat.username; 428 | } else if (chat.title && chat.username) { 429 | displayName = chat.title + ' (@' + chat.username + ')'; 430 | } 431 | const config = settings.getChatConfig(chatId); 432 | const dmSrc = config.danmakuSource; 433 | const roomId = config.roomId; 434 | let msgText = `你想要修改频道 “${displayName}” (id: ${chat.id}) 的什么设置?\n`; 435 | msgText += `房间号/弹幕源:${roomId} ${dmSrc}\n`; 436 | msgText += '过滤规则:' + config.pattern; 437 | ctx.reply(msgText, Extra.markup(Markup.inlineKeyboard([ 438 | [ 439 | Markup.callbackButton('房间号/弹幕源', 'change_danmaku_src:' + chat.id), 440 | Markup.callbackButton('过滤规则', 'change_pattern:' + chat.id), 441 | Markup.callbackButton('管理员', 'change_admin:' + chat.id) 442 | ], 443 | [ 444 | Markup.callbackButton('屏蔽用户', 'change_blocked_users:' + chat.id), 445 | Markup.callbackButton('重连房间', `reconnect_room:${dmSrc}_${roomId}`), 446 | Markup.callbackButton('查看统计', `stat_by_chat:` + chat.id) 447 | ], 448 | [ 449 | Markup.callbackButton('计划任务', 'manage_schedules:' + chat.id), 450 | Markup.callbackButton('取消注册', 'unregister_chat:' + chat.id) 451 | ] 452 | ]))); 453 | }; 454 | 455 | onActionReconnectRoom = async (ctx) => { 456 | const dmSrc = ctx.match[1]; 457 | const roomId = parseInt(ctx.match[2]); 458 | this.dmSrc.reconnectRoom(dmSrc, roomId); 459 | ctx.reply(`已经对直播房间 ${dmSrc} ${roomId} 重新连接中。` + 460 | `(由于目前是相同直播房间的所有对话共用一个弹幕连接,可能会影响到其它频道的弹幕转发)`); 461 | this.user_access_log(ctx.update.callback_query.from.id, 'Reconnect room: ' + dmSrc + ' ' + roomId); 462 | return await ctx.answerCbQuery(); 463 | }; 464 | 465 | onActionUnregisterChat = async (ctx) => { 466 | const targetChatId = parseInt(ctx.match[1]); 467 | this.requestUnregisterChat(ctx, targetChatId); 468 | return await ctx.answerCbQuery(); 469 | }; 470 | 471 | onActionConfirmUnregisterChat = async (ctx) => { 472 | const chatId = parseInt(ctx.match[1]); 473 | const regRoomId = settings.getChatConfig(chatId).roomId; 474 | const regSource = settings.getChatConfig(chatId).danmakuSource; 475 | if (!regRoomId) { 476 | return await ctx.answerCbQuery('这个对话未注册任何弹幕源。', true); 477 | } 478 | settings.deleteChatConfig(chatId); 479 | this.dmSrc.leaveRoom(regSource, regRoomId); 480 | ctx.reply(`对话 id=${chatId} 已成功取消注册。`); 481 | this.user_access_log(ctx.update.callback_query.from.id, 'Unregistered chat id=' + chatId); 482 | return await ctx.answerCbQuery(); 483 | }; 484 | 485 | requestUnregisterChat = async (ctx, chatId) => { 486 | ctx.reply('你确定要取消注册对话 id=' + chatId + ' 吗?所有该对话的设置都会被清除且无法恢复。', 487 | Extra.markup(Markup.inlineKeyboard([ 488 | Markup.callbackButton('是的,我不后悔', 'confirm_unregister_chat:' + chatId) 489 | ]))); 490 | }; 491 | 492 | onActionChangeDanmakuSrc = async (ctx) => { 493 | const targetChatId = parseInt(ctx.match[1]); 494 | settings.setUserState(ctx.update.callback_query.from.id, 495 | USER_STATE_CODE_CHAT_CHANGE_DANMAKU_SRC, 496 | targetChatId); 497 | ctx.reply('你正在编辑 id=' + targetChatId + ' 的弹幕房间号/弹幕源,' + 498 | '如果你只需要修改房间号,回复房间号即可。\n' + 499 | '如果你需要修改弹幕源,请按格式回复:`[房间号] [弹幕源]` 。' + 500 | '例如需要使用斗鱼 10 号房间弹幕,则回复:`10 douyu`\n\n' + 501 | '当前设置:房间号=`' + settings.getChatConfig(targetChatId).roomId + 502 | '`, 弹幕源=`' + settings.getChatConfig(targetChatId).danmakuSource + '`\n' + 503 | '回复 /cancel 退出互动式对话。', Extra.markdown()); 504 | return await ctx.answerCbQuery(); 505 | }; 506 | 507 | onActionChangePattern = async (ctx) => { 508 | const targetChatId = parseInt(ctx.match[1]); 509 | settings.setUserState(ctx.update.callback_query.from.id, 510 | USER_STATE_CODE_CHAT_CHANGE_PATTERN, 511 | targetChatId); 512 | ctx.reply('你正在编辑 id=' + targetChatId + ' 的过滤规则,' + 513 | '符合过滤规则正则表达式的弹幕内容将会被转发到指定 id 的对话/频道中。\n\n' + 514 | '当前设置:`' + settings.getChatConfig(targetChatId).pattern + '`\n' + 515 | '回复 /cancel 退出互动式对话。', Extra.markdown()); 516 | return await ctx.answerCbQuery(); 517 | }; 518 | 519 | onActionChangeAdmin = async (ctx) => { 520 | if (!this.hasUserPermissionForBot(ctx.update.callback_query.from.id)) { 521 | return await ctx.answerCbQuery('很抱歉,这项操作只有 Bot 管理员可以使用。', true); 522 | } 523 | const targetChatId = parseInt(ctx.match[1]); 524 | settings.setUserState(ctx.update.callback_query.from.id, 525 | USER_STATE_CODE_CHAT_CHANGE_ADMIN, 526 | targetChatId); 527 | ctx.reply('你正在编辑 id=' + targetChatId + ' 的管理员列表,' + 528 | '管理员可以对该频道修改\n\n' + 529 | '当前设置:`' + settings.getChatConfig(targetChatId).admin + '`\n' + 530 | '回复 /cancel 退出互动式对话。', Extra.markdown()); 531 | return await ctx.answerCbQuery(); 532 | }; 533 | 534 | onActionChangeBlockedUsers = async (ctx) => { 535 | const targetChatId = parseInt(ctx.match[1]); 536 | const message = await ctx.reply(this.getChangeBlockedUsersMessageText(targetChatId), Extra.markdown()); 537 | 538 | settings.setUserState(ctx.update.callback_query.from.id, 539 | USER_STATE_CODE_CHAT_CHANGE_BLOCK_USERS, 540 | { 541 | targetChatId, 542 | chatId: message.chat.id, 543 | messageId: message.message_id 544 | }); 545 | }; 546 | 547 | onActionManageSchedules = async (ctx) => { 548 | const targetChatId = parseInt(ctx.match[1]); 549 | const message = await ctx.reply(this.getManageSchedulesMessageText(targetChatId), Extra.markdown()); 550 | 551 | settings.setUserState(ctx.update.callback_query.from.id, 552 | USER_STATE_CODE_CHAT_MANAGE_SCHEDULES, 553 | { 554 | targetChatId, 555 | chatId: message.chat.id, 556 | messageId: message.message_id 557 | }) 558 | }; 559 | 560 | onActionStatisticsByChat = async (ctx) => { 561 | const targetChatId = parseInt(ctx.match[1]); 562 | const config = settings.getChatConfig(targetChatId); 563 | const roomId = config.roomId; 564 | const src = config.danmakuSource; 565 | const roomIdWithSrc = src + '_' + roomId; 566 | 567 | const sentences = await this.statistics.countSentencesByRoomId(roomIdWithSrc); 568 | const words = await this.statistics.countWordsByRoomId(roomIdWithSrc); 569 | 570 | ctx.reply('对话 ID=' + targetChatId + ' 的统计信息(目前仅支持统计实际连接的房间,不区分对话):\n' + 571 | '连接的弹幕源与房间 ID:`' + roomIdWithSrc + '`\n' + 572 | '已同传的弹幕数:' + sentences + '\n' + 573 | '已同传的字数:' + words, Extra.markdown()); 574 | 575 | return await ctx.answerCbQuery(); 576 | }; 577 | 578 | getChangeBlockedUsersMessageText = (chatId) => { 579 | let blockedUsers = settings.getChatBlockedUsers(chatId) 580 | .map(({src, uid}) => src + '_' + uid); 581 | if (blockedUsers.length > 0) { 582 | blockedUsers = blockedUsers.reduce((t, next) => t + ', ' + next); 583 | } else { 584 | blockedUsers = '空'; 585 | } 586 | return '你正在编辑 id=' + chatId + ' 的屏蔽用户列表,' + 587 | '被屏蔽的用户弹幕不会被转发到对话中。\n' + 588 | '输入 `add [弹幕源] [用户id]` 可以添加屏蔽用户,输入 `del [弹幕源] [用户id]` 可以解除屏蔽用户。' + 589 | '例如:输入 `add bilibili 100` 可以屏蔽 bilibili 弹幕源 id 为 100 的用户。\n\n' + 590 | '当前已被屏蔽的用户:\n`' + blockedUsers + '`\n' + 591 | '回复 /cancel 完成屏蔽修改并退出互动式对话。'; 592 | }; 593 | 594 | getManageSchedulesMessageText = (chatId) => { 595 | let schedules = settings.getChatSchedules(chatId) 596 | .map(({expression, action}) => '`' + expression + ' ' + action + '`'); 597 | if (schedules.length > 0) { 598 | schedules = schedules.reduce((t, next) => t + '\n' + next); 599 | } else { 600 | schedules = '空'; 601 | } 602 | return '你正在编辑 id=' + chatId + ' 的计划任务列表,' + 603 | '计划任务的时间格式使用 cron 时间表达式,同一个 cron 时间表达式只能设置一个任务,' + 604 | '你可以相隔一秒设置不同的任务。任务命令可以参考:https://danmaqua.github.io/bot/scheduler\\_usage.html\n' + 605 | '输入 `add [cron 时间表达式] [任务命令]` 可以添加计划任务\n' + 606 | '输入 `del [cron 时间表达式]` 可以删除对应时间的任务。\n' + 607 | '输入 `clear` 可以清除所有计划任务且不可恢复。\n' + 608 | '当前已安排的任务计划:\n' + schedules + '\n' + 609 | '回复 /cancel 完成修改并退出互动式对话。'; 610 | }; 611 | 612 | onAnswerChangeDanmakuSrc = async (ctx, chatId) => { 613 | let [roomId, srcId] = ctx.message.text.split(' '); 614 | if (isNaN(roomId)) { 615 | ctx.reply('你输入的房间号不是合法的数字。', Extra.inReplyTo(ctx.message.message_id)); 616 | return; 617 | } 618 | roomId = Number(roomId); 619 | if (srcId) { 620 | const src = settings.getDanmakuSource(srcId); 621 | if (!src) { 622 | ctx.reply('你输入的弹幕源不是合法的弹幕源,你可以输入 /list_dm_src 进行查询。', 623 | Extra.inReplyTo(ctx.message.message_id)); 624 | return; 625 | } 626 | } 627 | const curRoomId = settings.getChatConfig(chatId).roomId; 628 | const curDanmakuSource = settings.getChatConfig(chatId).danmakuSource; 629 | if (curRoomId !== roomId || curDanmakuSource !== srcId) { 630 | if (curRoomId) { 631 | this.dmSrc.leaveRoom(curDanmakuSource, curRoomId); 632 | } 633 | settings.setChatRoomId(chatId, roomId); 634 | settings.setChatDanmakuSource(chatId, srcId); 635 | this.dmSrc.joinRoom(settings.getChatConfig(chatId).danmakuSource, roomId); 636 | } 637 | const newDanmakuSource = settings.getChatConfig(chatId).danmakuSource; 638 | ctx.reply(`已成功为 id=${chatId} 频道注册了 ${newDanmakuSource}:${roomId} 房间弹幕转发。`); 639 | this.user_access_log(ctx.message.from.id, `Set chat id=${chatId} danmaku source to` + 640 | ` ${newDanmakuSource}:${roomId}`) 641 | settings.clearUserState(ctx.message.from.id); 642 | }; 643 | 644 | onAnswerChangePattern = async (ctx, chatId) => { 645 | let pattern = ctx.message.text; 646 | if (!pattern) { 647 | ctx.reply('请输入过滤规则正则表达式。', Extra.markdown()); 648 | return; 649 | } 650 | try { 651 | new RegExp(pattern); 652 | settings.setChatPattern(chatId, pattern); 653 | ctx.reply(`已成功为 id=${chatId} 频道设置了过滤规则:\`${pattern}\``, Extra.markdown()); 654 | this.user_access_log(ctx.message.from.id, `Set chat id=${chatId} pattern to ${pattern}`); 655 | settings.clearUserState(ctx.message.from.id); 656 | } catch (e) { 657 | ctx.reply('设置失败,你输入的不是合法的正则表达式,错误:' + e); 658 | } 659 | }; 660 | 661 | onAnswerChangeAdmin = async (ctx, chatId) => { 662 | const admins = ctx.message.text.split(' ') 663 | .map((value) => Number(value)) 664 | .filter((value) => Number.isNaN(value)); 665 | settings.setChatAdmin(chatId, admins); 666 | ctx.reply(`已成功为 id=${chatId} 频道设置了管理员:\`${admins}\``, Extra.markdown()); 667 | this.user_access_log(ctx.message.from.id, `Set chat id=${chatId} admin to ${admins}`); 668 | settings.clearUserState(ctx.message.from.id); 669 | }; 670 | 671 | onAnswerChangeBlockedUsers = async (ctx, { targetChatId, chatId, messageId }) => { 672 | const [operation, src, uid] = ctx.message.text.split(' '); 673 | if (operation !== 'add' && operation !== 'del') { 674 | ctx.reply('不支持的屏蔽用户操作,如果你要进行其他操作请回复 /cancel'); 675 | return; 676 | } 677 | if (!src || !uid) { 678 | ctx.reply('格式错误,请认真阅读修改说明。'); 679 | return; 680 | } 681 | if (operation === 'add') { 682 | settings.addChatBlockedUsers(targetChatId, src + '_' + uid); 683 | ctx.reply('已成功添加屏蔽用户:' + src + '_' + uid); 684 | this.user_access_log(ctx.message.from.id, 'Blocked danmaku user: ' + src + '_' + uid); 685 | } else if (operation === 'del') { 686 | settings.removeChatBlockedUsers(targetChatId, src + '_' + uid); 687 | ctx.reply('已成功取消屏蔽用户:' + src + '_' + uid); 688 | this.user_access_log(ctx.message.from.id, 'Unblocked danmaku user: ' + src + '_' + uid); 689 | } 690 | await this.bot.telegram.editMessageText( 691 | chatId, messageId, undefined, 692 | this.getChangeBlockedUsersMessageText(targetChatId), 693 | { 694 | chat_id: chatId, 695 | message_id: messageId, 696 | parse_mode: 'Markdown' 697 | }); 698 | }; 699 | 700 | onAnswerManageSchedules = async (ctx, { targetChatId, chatId, messageId }) => { 701 | const [operation, ...args] = ctx.message.text.split(' '); 702 | if (operation !== 'add' && operation !== 'del' && operation !== 'clear') { 703 | ctx.reply('不支持的计划任务管理操作,如果你要进行其他操作请回复 /cancel'); 704 | return; 705 | } 706 | const cronArgs = args.slice(0, 6); 707 | const expression = cronArgs.length === 0 ? '' : cronArgs.reduce((a, b) => `${a} ${b}`); 708 | if (operation === 'add') { 709 | if (cronArgs.length !== 6 || !this.chatsScheduler.validateExpression(expression)) { 710 | ctx.reply('这不是正确的 cron 时间表达式。', Extra.inReplyTo(ctx.message.message_id)); 711 | return; 712 | } 713 | const actions = args.slice(6); 714 | if (actions.length <= 0) { 715 | ctx.reply('请输入计划任务要执行的操作。', Extra.inReplyTo(ctx.message.message_id)); 716 | return; 717 | } 718 | const action = actions.reduce((a, b) => `${a} ${b}`); 719 | if (!this.chatsScheduler.validateAction(action)) { 720 | ctx.reply('这不是正确的操作,请检查语法是否正确。', Extra.inReplyTo(ctx.message.message_id)); 721 | return; 722 | } 723 | if (!settings.addChatSchedule(targetChatId, expression, action)) { 724 | ctx.reply('添加计划任务失败,请检查是否有相同的 cron 时间表达式。', 725 | Extra.inReplyTo(ctx.message.message_id)); 726 | return; 727 | } 728 | this.chatsScheduler.addScheduler(targetChatId, expression, action); 729 | ctx.reply('添加计划任务 `' + expression + '` 成功。', 730 | Extra.markdown().inReplyTo(ctx.message.message_id)); 731 | this.user_access_log(ctx.message.from.id, 732 | `Add schedule: chatId=${chatId} expression=${expression} action=${action}`); 733 | } else if (operation === 'del') { 734 | if (cronArgs.length !== 6 || !this.chatsScheduler.validateExpression(expression)) { 735 | ctx.reply('这不是正确的 cron 时间表达式。', Extra.inReplyTo(ctx.message.message_id)); 736 | return; 737 | } 738 | if (!settings.removeChatSchedule(targetChatId, expression)) { 739 | ctx.reply('移除计划任务失败,请检查是否已添加这个 cron 时间表达式', 740 | Extra.inReplyTo(ctx.message.message_id)); 741 | return; 742 | } 743 | this.chatsScheduler.removeScheduler(targetChatId, expression); 744 | ctx.reply('移除计划任务 `' + expression + '` 成功。', 745 | Extra.markdown().inReplyTo(ctx.message.message_id)); 746 | this.user_access_log(ctx.message.from.id, 747 | `Remove schedule: chatId=${chatId} expression=${expression}`); 748 | } else if (operation === 'clear') { 749 | this.chatsScheduler.clearSchedulersForChat(targetChatId); 750 | settings.setChatSchedules(targetChatId, []); 751 | ctx.reply('已清除所有计划任务。', Extra.inReplyTo(ctx.message.message_id)); 752 | this.user_access_log(ctx.message.from.id, 753 | `Clear schedules: chatId=${chatId}`); 754 | } 755 | await this.bot.telegram.editMessageText( 756 | chatId, messageId, undefined, 757 | this.getManageSchedulesMessageText(targetChatId), 758 | { 759 | chat_id: chatId, 760 | message_id: messageId, 761 | parse_mode: 'Markdown' 762 | }); 763 | }; 764 | 765 | onCommandManageChat = async (ctx) => { 766 | let [_, chatId] = ctx.message.text.split(' '); 767 | if (!chatId) { 768 | ctx.reply('管理频道命令使用方法:/manage\_chat `chatId`', Extra.markdown()); 769 | return; 770 | } 771 | const targetChat = await this.getChat(chatId || ctx.chat.id); 772 | if (!targetChat) { 773 | ctx.reply('无法找到这个对话。'); 774 | return; 775 | } 776 | chatId = targetChat.id; 777 | if (!settings.getChatConfig(chatId)) { 778 | ctx.reply('这个对话未注册任何弹幕源。'); 779 | return; 780 | } 781 | if (!this.hasPermissionForChat(ctx.message.from.id, chatId)) { 782 | ctx.reply('你没有管理这个对话的权限。'); 783 | return; 784 | } 785 | await this.requestManageChat(ctx, chatId); 786 | }; 787 | 788 | onCommandListDMSrc = async (ctx) => { 789 | let msgText = 'Bot 支持的弹幕源:\n'; 790 | for (let src of settings.danmakuSources) { 791 | msgText += '- `' + src.id + '` : ' + src.description + '\n'; 792 | } 793 | ctx.reply(msgText, Extra.markdown()); 794 | }; 795 | 796 | onCommandCancel = async (ctx) => { 797 | const code = settings.getUserStateCode(ctx.message.from.id); 798 | if (code < 0) { 799 | ctx.reply('你没有取消任何操作。'); 800 | return; 801 | } 802 | settings.clearUserState(ctx.message.from.id); 803 | ctx.reply('已取消互动式操作。'); 804 | }; 805 | 806 | onCommandSetDefaultPattern = async (ctx) => { 807 | let [_, pattern] = ctx.message.text.split(' '); 808 | if (!pattern) { 809 | ctx.reply('请输入要设置的默认过滤规则。', Extra.markdown()); 810 | return; 811 | } 812 | try { 813 | new RegExp(pattern); 814 | settings.setGlobalPattern(pattern); 815 | ctx.reply('成功设置默认过滤规则为:`' + pattern + '`', Extra.markdown()); 816 | this.user_access_log(ctx.message.from.id, 'Set default pattern to ' + pattern); 817 | } catch (e) { 818 | ctx.reply('设置默认过滤规则失败,错误原因:' + e); 819 | } 820 | }; 821 | 822 | onCommandSetDefaultAdmins = async (ctx) => { 823 | const admins = ctx.message.text.split(' ') 824 | .slice(1) 825 | .map((value) => Number(value)) 826 | .filter((value) => !isNaN(value)); 827 | settings.setGlobalAdmin(admins); 828 | ctx.reply('已设置默认管理员为 `' + admins.toString() + '`', Extra.markdown()); 829 | this.user_access_log(ctx.message.from.id, 'Set default admin to ' + admins.toString()); 830 | } 831 | 832 | onCommandSetDefaultSource = async (ctx) => { 833 | let [_, newSrc] = ctx.message.text.split(' '); 834 | if (!newSrc) { 835 | ctx.reply('请输入一个弹幕源 id,要查询 Bot 支持哪些弹幕源可以输入 /list_dm_src'); 836 | return; 837 | } 838 | if (settings.danmakuSources.find((value) => value.id === newSrc)) { 839 | settings.setGlobalDanmakuSource(newSrc); 840 | ctx.reply('成功设置默认弹幕源为 ' + newSrc); 841 | this.user_access_log(ctx.message.from.id, 'Set default danmaku source to ' + newSrc); 842 | } else { 843 | ctx.reply('无法找到弹幕源 id=' + newSrc); 844 | } 845 | } 846 | 847 | onCommandStatUsers = async (ctx) => { 848 | if (!this.statistics.enabled) { 849 | ctx.reply('Bot 统计功能已关闭,请联系 Bot 管理员。'); 850 | return; 851 | } 852 | const users = await this.statistics.getUsers(); 853 | if (!users || users.length === 0) { 854 | ctx.reply('暂未有任何发送过同传弹幕的用户统计信息。'); 855 | return; 856 | } 857 | const usersText = users.reduce((a, b) => `${a}, ${b}`); 858 | ctx.reply('已统计同传弹幕发送信息的用户:\n`' + usersText + '`', Extra.markdown()); 859 | }; 860 | 861 | onCommandStatUserQuery = async (ctx) => { 862 | if (!this.statistics.enabled) { 863 | ctx.reply('Bot 统计功能已关闭,请联系 Bot 管理员。'); 864 | return; 865 | } 866 | const [_, userId] = ctx.message.text.split(' '); 867 | if (!userId || userId.indexOf('_') < 0) { 868 | ctx.reply('用户 ID 参数不正确,请检查格式是否正确。'); 869 | return; 870 | } 871 | const sentences = await this.statistics.countSentencesByUserId(userId); 872 | const words = await this.statistics.countWordsByUserId(userId); 873 | ctx.reply(`用户 ${userId} 统计信息:\n已同传的弹幕数量:${sentences}\n已同传的字数:${words}`); 874 | }; 875 | } 876 | 877 | module.exports = DanmaquaBot; 878 | --------------------------------------------------------------------------------