-
Notifications
You must be signed in to change notification settings - Fork 0
/
Index.ts
278 lines (261 loc) · 10.3 KB
/
Index.ts
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
AlterSaberr
/
NovaNetworkRealmBot
Public
forked from BeRP-Plugins/DiscordBridge
Code
Pull requests
Actions
Projects
Security
Insights
main
NovaNetworkRealmBot/src/index.ts
@ATXLtheAxolotl
ATXLtheAxolotl Merge branch 'main' into main
2 contributors
242 lines (228 sloc) 9.82 KB
import { PluginApi } from "./@interface/pluginApi.i";
import {
Client,
Intents,
MessageEmbed,
TextChannel,
Interaction,
} from "discord.js";
import { SlashCommandBuilder } from "@discordjs/builders";
import { REST } from '@discordjs/rest';
import { Routes } from 'discord-api-types/v9';
const { token, channelId, clientId, guildId, AutoConnect, realmName, logMessageEvents } = require("../config.json");
function getSavedPic(eventXuid){
const tempPicMap = {
2533274884028261: "https://cdn.discordapp.com/avatars/269249777185718274/a_f7a7df655ec0c612ec4e42094adc1903.png"
}
if (eventXuid in tempPicMap) {
return tempPicMap[eventXuid]
} else {
return "https://i.imgur.com/7ltWLoa.png"
}
}
class DiscBot {
private api: PluginApi
private commandMap: Map<string, CallableFunction>
private commandArray: SlashCommandBuilder[]
private client: Client
private ready: boolean = false
private messageQueue: { message:string, channel?:string }[] = []
private embedQueue: { embed: MessageEmbed[], channel?:string }[] = []
private commandQueue: DiscordCommand[] = []
constructor(api: PluginApi) {
this.api = api;
this.client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MEMBERS,
],
});
this.commandArray = [];
this.commandMap = new Map();
}
async onLoaded(): Promise<void> {
this.api.getLogger().info("Discord-MC Bridge loaded!");
if(!AutoConnect.attempt) return
this.api.getLogger().info("Attempting auto-connection with realm...");
try {
this.api.autoConnect(AutoConnect.email, AutoConnect.realmId)
}
catch(error) {
this.api.getLogger().error("AutoConnect failed... Attempting reconnect", error)
try {
this.api.autoReconnect(AutoConnect.email, AutoConnect.realmId)
}
catch(anotherError) {
this.api.getLogger().error("AutoReconnect failed. Skipping...", anotherError)
}
}
}
async onEnabled(): Promise<void> {
this.api.getLogger().info("Discord-MC Bridge enabled! (onEnabled)");
this.api.getLogger().info("Discord-MC Bridge connecting to Discord Client...");
let client = this.client
client.login(token);
this.api.getLogger().info("Discord-MC Bridge login complete.");
client.on("ready", async () => {
this.ready = true;
if(this.messageQueue.length > 0) this.messageQueue.forEach(({message, channel}) => this.sendMessage(message, channel));
if(this.embedQueue.length > 0) this.embedQueue.forEach(({embed, channel}) => this.sendEmbed(embed, channel));
if(this.commandQueue.length > 0) this.commandQueue.forEach((command) => this.registerCommand(command));
this.api.getLogger().info("Discord-MC Bridge Client Ready, setting activity...");
client.user.setActivity(`over ${realmName}`, { type: "WATCHING" })
this.api.getLogger().info("Discord-MC Bridge Activity set.");
this.api.getLogger().info(`Now bridged with Discord as ${client.user.username}`);
const StartEmbed = new MessageEmbed()
.setColor("#139dbf")
.setDescription(`**${realmName}'s chat has been bridged with discord**`)
this.sendEmbed([StartEmbed])
this.api
.getCommandManager()
.executeCommand(`tellraw @a {\"rawtext\":[{\"text\":\"§a§l§oDiscord-MC Bridge has been connected.§r\"}]}`);
this.registerCommand({name: 'list', description: 'Gets a list of people currently on the realm.', response: async (interaction) => {
if (!interaction.isCommand()) return;
const realmName = this.api.getConnection().realm.name;
let response = `/10 Players Online**:`;
let players = [];
response += `\n*-* ${this.api.getConnection().getXboxProfile().extraData.displayName}`;
for (const [, p] of this.api.getPlayerManager().getPlayerList()) {
players.push(p.getName());
response += `\n*-* ${p.getName()}`;
}
const fancyResponse = new MessageEmbed()
.setColor("#5a0cc0")
.setTitle(`${realmName}`)
.setDescription(`**${players.length + 1}${response}`);
await interaction
.reply({ embeds: [fancyResponse] })
.catch((error) => {
this.api.getLogger().error(error);
});
}})
});
client.on("messageCreate", (message) => {
if (message.author.bot)
return;
if (message.channel.id == channelId) {
if (logMessageEvents) {
this.api.getLogger().success("Received new message event from the Discord client:");
this.api.getLogger().success(` "${message.content}"`);
}
this.api
.getCommandManager()
.executeCommand(`tellraw @a {\"rawtext\":[{\"text\":\"§8[§9Discord§8]§f §7${message.author.username}§f: ${message.content}§r\"}]}`);
}
});
this.api.getEventManager().on("PlayerMessage", async (packet) => {
if (logMessageEvents) {
this.api.getLogger().success("Received new message event from the Realms client:");
this.api.getLogger().success(` "${packet.message}"`);
}
this.sendMessage(`[${packet.sender
.getConnection()
.realm.name.replace(/§[0-9A-FK-OR]/gi, "")
.replace("§g", "")}] ${packet.sender.getName()}: ${packet.message}`)//§r
});
this.api.getEventManager().on("PlayerInitialized", (userJoin) => {
let eventXuid = userJoin.getXuid()
const Join = new MessageEmbed()
.setColor("#00ff00")
.setTitle("__Player connected!__")
.setDescription(`**${userJoin.getName()}** has joined the realm\nXUID: [${eventXuid}]\nDevice: ${userJoin.getDevice()}`)
.setImage(getSavedPic(eventXuid));
return this.sendEmbed([Join]);
});
/** this.api.getEventManager().on("PlayerDied", (userDied) => {
const Death = new MessageEmbed()
.setColor("#ff0000")
.setDescription(`Oof! **${userDied.player}** was just killed by ${userDied.killer}. RIP!`);
return this.sendEmbed([Death])
});**/
this.api.getEventManager().on("PlayerLeft", async (userLeave) => {
const Leave = new MessageEmbed()
.setColor("#9d3838")
.setDescription(`**${userLeave.getName()}** has left the realm.`);
return this.sendEmbed([Leave]);
});
client.on("interactionCreate", async (interaction) => {
if (!interaction.isCommand())
return;
const { commandName } = interaction;
if(!this.commandMap.has(commandName)) return;
this.commandMap.get(commandName)(interaction)
});
}
public onDisabled() {
const fancyStopMSG = new MessageEmbed()
.setColor("#139dbf")
.setDescription(":octagonal_sign: ***Discord-MC Bridge has been disconnected.***");
this.sendEmbed([fancyStopMSG])
}
public sendMessage(message: string, channel?: string): void {
if(!this.ready) {
this.messageQueue.push({message, channel});
return;
};
if(!channel) channel = channelId;
this.client.channels
.fetch(channel)
.then((channel) => (channel as TextChannel)
.send(message))
.catch((error) => {
this.api.getLogger().error(error);
});
}
public sendEmbed(embed: MessageEmbed[], channel?: string): void {
if(!this.ready) {
this.embedQueue.push({embed, channel});
return;
};
if(!channel) channel = channelId;
this.client.channels
.fetch(channel)
.then(async (channel) => await (channel as TextChannel).send({ embeds: embed }).catch((error) => {
this.api.getLogger().error(error);
})).catch((error) => {
this.api.getLogger().error(error);
});
}
public registerCommand(command: DiscordCommand): void {
if(!this.ready) {
this.commandQueue.push(command)
return;
};
if(this.commandMap.has(command.name)) return this.api.getLogger().error(`${command.name} has already been registered!`)
this.commandArray.push(
new SlashCommandBuilder()
.setName(command.name)
.setDescription(command.description)
);
const commands = this.commandArray.map((command) => command.toJSON());
this.api.getLogger().info(`Attempting to register "${command.name}"`)
const rest = new REST({ version: "9" }).setToken(token);
(async () => {
try {
await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
body: commands,
});
this.api
.getLogger()
.success(`Successfully registered "${command.name}".`);
this.commandMap.set(command.name, command.response);
}
catch (error) {
this.api.getLogger().error(`Error occurred while attempting to register "${command.name}" command`, error);
}
})();
}
public getClient(): Client {
return this.client;
}
}
export = DiscBot;
interface DiscordCommand {
name: string;
description: string;
response: (interaction: Interaction) => void;
}
Give feedback
Footer
© 2023 GitHub, Inc.
Footer navigation
Terms
Privacy
Security
Status
Docs
Contact GitHub
Pricing
API
Training
Blog
About
NovaNetworkRealmBot/index.ts at main · AlterSaberr/NovaNetworkRealmBot