This repository was archived by the owner on Apr 21, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbot.js
More file actions
168 lines (136 loc) · 5.35 KB
/
bot.js
File metadata and controls
168 lines (136 loc) · 5.35 KB
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
'use strict';
const
fs = require('fs'),
telebot = require('telebot'),
time = require('./time'),
Ioredis = require('ioredis'),
path = require('path'),
symbols = require('./core-symbols'),
control = {
configFilePath: process.argv[2] || './config.json',
shutdown: (reason = "Unknown reason", fail) => {
console.log(`Terminated: ${reason}. [SHUTDOWN_CLEAN]`);
process.exitCode = !fail;
bot.api.stop(reason);
bot.db.quit();
}
};
let bot = { }, authTimer, spanningTimer = time.startTimer('ready');
const {pluginName} = symbols;
control.config = require(control.configFilePath);
try {
process.once('SIGINT', () => control.shutdown("SIGINT"));
process.once('SIGTERM', () => control.shutdown("SIGTERM"));
process.once('SIGBREAK', () => control.shutdown("Ctrl + Break"));
console.log(`\nRunning on node ${process.version} with process id ${process.pid}.\nLoading config from "${control.configFilePath}".`);
Object.freeze(control.config);
bot.db = new Ioredis(control.config.db);
bot.api = new telebot(control.config.auth_token);
bot.api.start();
time.start();
bot.time = time;
bot.control = control;
time.startTimer('auth');
bot.api.getMe().then(me => {
console.log(`Connected. (${authTimer = time.resolveTimer('auth')} ms)`);
bot.profile = me;
console.log(`Profile:\n Id: ${me.id}\n Name: ${me.first_name}\n Username: @${me.username}`);
setup();
});
} catch (e) {
console.error(e);
control.shutdown("Unable to finish authentication", true);
}
function setup () {
bot.functions = { };
const getPluginName = () => {
const path_ = plugins[i].path;
const name = path.basename(path_, path.extname(path_));
return name.toLowerCase();
}
bot.register = (sth, fn) => {
const name = getPluginName();
bot.api.on(sth, async message => {
if (message[symbols.handled] || await isPluginDisabled(message.chat.id, name)) {
return;
}
return fn.call(this, message);
});
}
bot.register.command = (commands, fn) => {
if (typeof commands === 'string') {
commands = [commands];
}
fn[pluginName] = getPluginName();
for (const command of commands) {
if (bot.functions.hasOwnProperty(command.toLowerCase())) {
throw new Error(`Attempt to register ${command} command, already registered by ${bot.functions[command.toLowerCase()][pluginName]} plugin`);
}
bot.functions[command.toLowerCase()] = fn
}
};
Object.seal(bot);
bot.api.on('text', receive);
let plugins = control.config.plugins, failed = 0;
time.startTimer('loadAll');
for (var i = 0; i < plugins.length; i++) {
try {
require(plugins[i].path).init(bot, plugins[i].prefs);
} catch (e) {
console.error(`Failed to load plugin "${plugins[i].path}".`);
console.error(e);
plugins[i][symbols.error] = e;
failed++;
}
}
console.log(`Done loading plugins: ${plugins.length - failed} OK, ${failed} failed. (${time.resolveTimer('loadAll')} ms)`);
bot.register = null; // time for registering is now over
let spanningTimer = time.resolveTimer('ready');
console.log(`Ready to process messages. (${(spanningTimer - authTimer).toFixed(2)} ms | ${spanningTimer} ms)`);
}
const isPluginDisabled = (chatid, name) => bot.db.sismember(`chat${chatid}:disabledPlugins`, name.toLowerCase())
async function receive (message) {
if (bot.time.isExpired(message.date))
return;
if (!message.entities)
return;
const firstEntity = message.entities[0];
if (firstEntity.offset || firstEntity.type != 'bot_command')
return;
let commandEntity = message.text.substr(1, firstEntity.length - 1).toLowerCase();
message.args = message.text.slice(message.entities[0].length + 1)
const botMention = commandEntity.match(/@.*/);
if (botMention) {
if (botMention[0].substr(1) !== bot.profile.username.toLowerCase())
return;
commandEntity = botMention.input.substr(0, botMention.index);
}
if (!bot.functions[commandEntity])
return;
message.tag = (response, format) => {
switch (typeof response) {
case 'number':
response = String(response);
case 'string':
message.reply.text(response, {
parse: format ? 'HTML' : undefined,
reply: message.message_id
}).catch(e => message.error(e.error_code, e.description));
case 'undefined':
break;
case 'object':
if (response && typeof response.then == 'function'
|| response == null)
break;
default:
message.error("TYPE", `Function Error: returned ${typeof response} instead of string`);
}
};
message.error = (code, desc) =>
message.tag(`Failed. #E_${code} ⚠️\n${desc}.`);
const funct = bot.functions[commandEntity];
if (message[symbols.handled] || await isPluginDisabled(message.chat.id, funct[pluginName])) {
return;
}
message.tag(funct.fn(message), funct.format);
}