-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
173 lines (156 loc) · 4.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
const https = require('https');
const util = require('util');
exports.TelegramLogger = class TelegramLogger {
/** @private @type {string} */
_ctx = this.constructor.name;
/** @private @type {string} */
_apiUrl = 'https://api.telegram.org/bot';
/** @private @type {number | null} */
_chatId = null;
/**
* @class TelegramLogger
* @param {string} token should get from https://t.me/BotFather
* @param {number} chatId should get using https://t.me/MyIdBot
*/
constructor(token, chatId) {
this._init(token, chatId);
}
/**
* Sends `debug` message to chat
* @param {any} data
*/
debug(...data) {
return this._sendMessage(this.debug.name, data);
}
/**
* Sends `error` message to chat
* @param {any} data
*/
error(...data) {
return this._sendMessage(this.error.name, data);
}
/**
* Sends `log` message to chat
* @param {any} data
*/
log(...data) {
return this._sendMessage(this.log.name, data);
}
/**
* Sends `plain` message to chat
* @param {any} data
*/
plain(...data) {
return this._sendMessage('', data, false);
}
/**
* @description Initial validation of bot `token` and `chatId`
* @param {string} token
* @param {number} chatId
*/
async _init(token, chatId) {
// Check token and chat
try {
this._apiUrl += token;
this._chatId = chatId;
await this._get(`${this._apiUrl}/getMe`);
await this._post(`${this._apiUrl}/getChat`, { chat_id: chatId });
} catch (error) {
throw new Error(`${this._ctx}, _init input token:${token} chatId:${chatId} err:`, err);
}
}
/**
* @private
* @description Sends log to chat
* @param {String} type log message type
* @param {any[]} data
*/
async _sendMessage(type, data, format = true) {
try {
await this._post(`${this._apiUrl}/sendMessage`, {
chat_id: this._chatId,
text: format ? this._fmt(type, data) : data,
parse_mode: 'HTML',
});
} catch (err) {
throw new Error(
`${this._ctx}, _sendMessage input type:${type} data:${util.inspect(data, { depth: null })} err:`,
err
);
}
}
/**
* @private
* @description Formats message `body` of given `type`
* @param {String} type message type
* @param {any[]} body
* @returns {String} formatted text
*/
_fmt(type, body) {
let head = '';
switch (type) {
case this.debug.name:
head = `⚙️ ${type.toUpperCase()}\n`;
break;
case this.error.name:
head = `🆘 ${type.toUpperCase()}\n`;
break;
default:
head = `ℹ️ ${this.log.name.toUpperCase()}\n`;
break;
}
const mentions = [];
const tags = [];
let text = '';
body.forEach(arg => {
if (Array.isArray(arg)) {
text += `\n${util.inspect(arg, { depth: null })}`;
} else if (typeof arg === 'object') {
text += `\n${util.inspect(arg, { depth: null, compact: false })}`;
} else if (typeof arg === 'string') {
if (arg.startsWith('@')) {
mentions.push(arg);
} else if (arg.startsWith('#')) {
tags.push(arg);
} else {
text += `${arg}`;
}
} else {
text += `${arg}`;
}
});
return `<b>${head}</b>` + `${tags.join(' ')}\n\n` + `<pre>${text}</pre>\n\n` + mentions.join(' ');
}
/**
* @private
* @description Http send get requset
* @param {string} url
*/
async _get(url) {
return new Promise((resolve, reject) => {
let data = '';
https.get(url, res => {
res.on('data', chunk => (data += chunk));
res.on('end', () => resolve(JSON.parse(data)));
res.on('error', () => reject(data));
});
});
}
/**
* @private
* @description Http send post requset url params
* @param {string} url
* @param {Record<string, any>} params
*/
async _post(url, params) {
return new Promise((resolve, reject) => {
let data = '';
const req = https.request(url + '?' + new URLSearchParams(params), res => {
res.on('data', chunk => (data += chunk));
res.on('end', () => resolve(JSON.parse(data)));
res.on('error', () => reject(data));
});
req.end();
});
}
};