-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.js
210 lines (164 loc) · 7.02 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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
// @ts-check
const path = require('path');
const fs = require('fs');
const { Client, GatewayIntentBits, codeBlock } = require('discord.js');
const { DiscordInteractions } = require('@akki256/discord-interaction');
const { Server, Logger } = require('socket-be');
const readline = require('readline');
const { validateConfig, getConfig } = require('./util/util');
const Translate = require('./util/Translate');
const embeds = require('./embeds');
const { handleMessage } = require('./handlers/MessageHandler');
const { handleChat } = require('./handlers/ChatHandler');
const { PanelHandler } = require('./handlers/PanelHandler');
const { ScriptHandler } = require('./handlers/ScriptHandler');
const logo = require('./util/logo');
const { version: VERSION } = require('../package.json');
if (!fs.existsSync('data')) fs.mkdirSync('data');
class Main {
constructor() {
console.log(logo);
console.log(`discord-mcbe v${VERSION}`);
this.version = VERSION;
this.config = getConfig();
this.logger = new Logger('Discord', {
timezone: this.config.timezone,
debug: this.config.debug
});
this.lang = new Translate(this.config.language);
this.client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
],
allowedMentions: { repliedUser: false }
});
if ('DISCORD_TOKEN' in process.env) this.config.discord_token ||= process.env.DISCORD_TOKEN;
validateConfig(this.config);
this.interactions = new DiscordInteractions(this.client);
this.interactions.loadRegistries(path.resolve(__dirname, './interactions'));
this.server = new Server({
port: this.config.port,
timezone: this.config.timezone,
commandVersion: this.config.command_version,
debug: this.config.debug
});
this.panels = new PanelHandler(this);
this.scripts = new ScriptHandler(this);
this.client.once('ready', async () => {
this.interactions.registerCommands(this.config.guild_id);
this.logger.info(this.lang.run('console.login', [ this.client.user?.tag ]));
const embed = embeds.ready().setFooter({ text: this.lang.run('discord.ready') });
if (this.config.ready_message) this.sendDiscord({ embeds: [ embed ] });
this.updateActivity();
setInterval(() => this.updateActivity(), 20*1000);
this.panels.startInterval();
});
this.client.on('messageCreate', async message => {
if (message.author.bot || message.channel.id !== this.config.channel_id) return;
handleMessage(this, message).catch(e => this.logger.error(e));
});
this.client.on('interactionCreate', interaction => {
// @ts-ignore
this.interactions.run(interaction).catch(e => {
this.logger.error(e);
const embed = embeds.error(codeBlock(String(e)))
.setAuthor({ name: this.lang.run('command.error.catch') });
if (interaction.isCommand()) interaction.channel.send({ embeds: [embed] });
});
});
this.server.events.on('serverOpen', () => {
this.logger.info(this.lang.run('console.listening', [ `${this.server.ip}:${this.config.port}` ]));
});
this.server.events.on('worldAdd', async ({ world }) => {
const host = await world.getLocalPlayer();
this.server.logger.info(this.lang.run('console.connect', [ world.name, host ]));
const embed = embeds.connect(this.lang.run('discord.connect', [ host ]), world.name);
this.sendDiscord({ embeds: [ embed ] });
world.sendMessage(this.lang.run('minecraft.connect', [ world.name ]));
this.updateActivity();
});
this.server.events.on('worldRemove', async ({ world }) => {
this.server.logger.info(this.lang.run('console.disconnect', [ world.name ]));
const embed = embeds.disconnect(this.lang.run('discord.disconnect'), world.name);
this.sendDiscord({ embeds: [ embed ] });
this.updateActivity();
});
this.server.events.on('playerJoin', async ev => {
const { players, world, world: { lastPlayers, maxPlayers } } = ev;
world.logger.log(this.lang.run('console.join', [ players.join(', '), lastPlayers.length, maxPlayers ]));
const embed = embeds.join(
this.lang.run('discord.join', [ players.join(', '), lastPlayers.length, maxPlayers ]),
this.server.getWorlds().length > 1 ? world.name : null
);
await this.sendDiscord({ embeds: [ embed ] });
this.updateActivity();
});
this.server.events.on('playerLeave', async ev => {
const { players, world, world: { lastPlayers, maxPlayers } } = ev;
world.logger.log(this.lang.run('console.leave', [ players.join(', '), lastPlayers.length, maxPlayers ]));
const embed = embeds.leave(
this.lang.run('discord.leave', [ players.join(', '), lastPlayers.length, maxPlayers ]),
this.server.getWorlds().length > 1 ? world.name : null
);
await this.sendDiscord({ embeds: [ embed ] });
this.updateActivity();
});
this.server.events.on('playerChat', async ev => {
handleChat(this, ev).catch(e => this.logger.error(e));
});
const reader = readline.createInterface({
input: process.stdin,
output: process.stdout
});
reader.on('line', (line) => {
if (line.startsWith('.')) {
try {
const res = eval(line.slice(1));
console.log('<', res);
} catch (e) {
console.error('<', e);
}
} else {
const command = line.replace(/^\/*/, '');
this.server.runCommand(command).then(res => console.log(res));
}
});
this.server.events.on('error', console.error);
this.client.on('error', console.error);
this.client.login(this.config.discord_token);
}
/**
* @param {string|import('discord.js').MessageCreateOptions} message
* @param {import('discord.js').Snowflake} [channelId]
* @returns {Promise<import('discord.js').Message|undefined>}
*/
async sendDiscord(message, channelId = this.config.channel_id) {
if (!message) return;
const channel = this.client.channels.cache.get(channelId);
if (!channel) throw Error('Failed to get channel');
if (channel.isSendable()) return await channel.send(message);
}
async updateActivity() {
const worlds = this.server.getWorlds();
let info;
if (worlds.length > 1) {
const sum = worlds.map(w => w.lastPlayers.length).reduce((a, b) => a + b);
info = `Players(total): ${sum} | Worlds: ${worlds.length}`;
} else if (worlds.length === 1) {
info = `Players: ${worlds[0].lastPlayers.length}/${worlds[0].maxPlayers}`;
} else {
info = 'Players: OFFLINE';
}
this.client.user.setPresence({
activities: [{ name: `${info} | /help` }]
});
}
}
const main = new Main();
module.exports = main;
main.scripts.load();
process.on('unhandledRejection', (err) => {
console.error('unhandledRejection:', err);
});