Skip to content

Commit

Permalink
Merge branch 'dev'
Browse files Browse the repository at this point in the history
  • Loading branch information
OrigamingWasTaken committed Apr 13, 2024
2 parents 501e2d5 + 96871ac commit a343f65
Show file tree
Hide file tree
Showing 9 changed files with 157 additions and 135 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "French Minecraft events Helper",
"main": "src/index.ts",
"scripts": {
"start": "node scripts/start.js && npm run build && cd dist && node src/index.js",
"start": "node scripts/start.js && npm run build && cd dist && node --no-warnings src/index.js",
"build": "rimraf dist/* && tsc && tsc-alias && tscp",
"build:watch": "tsc -c && tscp && (concurrently \"tsc -w\" \"tsc-alias -w\")",
"watch": "npm run build:watch",
Expand Down
5 changes: 5 additions & 0 deletions src/commands/alerts/alerts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ export default {
.setDescription("Le salon dans lequel les alertes seront envoyées")
.addChannelTypes(ChannelType.GuildText)
.setRequired(true)))
// .addSubcommand(subcommand =>
// subcommand
// .setName("panel")
// .setDescription("Envoie le panel de séléction de rôles")
// )
.addSubcommand(subcommand =>
subcommand
.setName("enable")
Expand Down
21 changes: 18 additions & 3 deletions src/commands/alerts/functions.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { logging } from "../../core/utilities";
import { ChatInputCommandInteraction, EmbedBuilder, StringSelectMenuBuilder, ActionRowBuilder, AttachmentBuilder, ComponentType, StringSelectMenuOptionBuilder } from "discord.js";
import { Collection, Db, MongoClient, ServerApiVersion } from "mongodb";
import { BotConfig, DiscordServerInfo } from '@src/types';
import { /*BotConfi,*/ DiscordServerInfo } from '@src/types';
import { EventSource } from "@src/types"
import fetch from "cross-fetch";
import emojiRegex from "emoji-regex";
const BotInfo: BotConfig = loadYaml("bot/info.yml")
const BotInfo/*: BotConfig*/ = loadYaml("bot/info.yml")

const mongo = new MongoClient(process.env.mongoUri, {
serverApi: {
Expand Down Expand Up @@ -239,4 +239,19 @@ export async function bind(interaction: ChatInputCommandInteraction, operation:
await mongo.close()
}
}
}
}

// async function sendPanel(interaction: ChatInputCommandInteraction) {
// try {
// await mongo.connect()
// const db: Db = mongo.db("discord")

// const collection: Collection = db.collection("servers")
// const savedSources: any[] = (await collection.findOne({ id: interaction.guild.id })).sources || []
// const sources = await getSources()
// const enabledSources: EventSource[] = savedSources.map(src => sources.find(s => s.guildId === src))
// interaction.reply(enabledSources.toString())
// } catch (err) {
// logging(`An error occured while sending the roles panel:\n${err}`,"error")
// }
// }
3 changes: 3 additions & 0 deletions src/commands/private/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Private commands

Commands here are used on the [Communauté Events' discord server](https://commu.events/discord)
35 changes: 0 additions & 35 deletions src/commands/private/embeds/premade_embed.ts

This file was deleted.

Empty file.
210 changes: 115 additions & 95 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
// Pre-run scripts
import "@core/globals"
import 'dotenv/config'
import '@core/globals';
import 'dotenv/config';

// File imports
import { ansi, logging } from "@core/utilities"
import { deployCommands, getCommands } from "@core/deploy-commands"
import { initEvents } from "./core/events"
import { alert } from "./alerts/hander"
import {ansi, logging} from '@core/utilities';
import {deployCommands, getCommands} from '@core/deploy-commands';
import {initEvents} from './core/events';
import {alert} from './alerts/hander';

// Imports
import { Client, Events, GatewayIntentBits, messageLink } from "discord.js"
import { WebSocket } from "ws"
import fetch from "cross-fetch"
import {ActivityType, Client, Events, GatewayIntentBits} from 'discord.js';
import {WebSocket} from 'ws';
import fetch from 'cross-fetch';
import {getSources} from './commands/alerts/functions';

// Main
const client = new Client({intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent]});
(async()=>{
client.commands = await getCommands()
})()
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent],
});
(async () => {
client.commands = await getCommands();
})();

// function checkWs(ws: WebSocket) {
// if (ws.readyState != WebSocket.OPEN) {
Expand All @@ -27,104 +30,121 @@ const client = new Client({intents: [GatewayIntentBits.Guilds, GatewayIntentBits
// }
// }

let websockets: WebSocket[] = []
let websockets: WebSocket[] = [];
let isReconnecting;

export let botInfo = {
websocket: false,
lastConexion: 0
}
websocket: false,
lastConexion: 0,
};

export function closeWebsockets() {
websockets.forEach(ws => {
const url = ws.url
ws.terminate()
logging(`Closed ws "${url}" at "${new Date().toISOString()}"`,"minimal")
})
websockets = []
websockets.forEach((ws) => {
const url = ws.url;
ws.terminate();
logging(`Closed ws "${url}" at "${new Date().toISOString()}"`, 'minimal');
});
websockets = [];
}

export async function wsConnect(): Promise<WebSocket> {
function wsError(error) {
botInfo.websocket = false
if (isReconnecting) return
isReconnecting = true
logging(`WebSocket error, retrying to connect in 10 seconds.\n${error}: ${error.message}`, "error");
// Retry after 10 seconds
setTimeout(wsConnect, 10000);
}

isReconnecting = false
try {
const response = await fetch("https://raw.githubusercontent.com/Communaute-Events/paths/main/paths.json", {
method: "GET",
headers: { "Content-Type": "application/json" }
});

const res = await response.json();
const ws = new WebSocket(res.websocket)

// checkWs(ws)
websockets.push(ws)

ws.on("message", msg => {
try {
const data = JSON.parse(msg.toString());
if ("_type" in data && data._type === "event") {
alert(data, client);
}
} catch (error) {
logging(`Error in ws:\n${error}`,"error");
}
});

ws.on("close", (code, reason) => {
wsError({message: reason})
});

ws.on("error", error => {
wsError(error)
});

ws.on("open",()=> {
logging(`WebSocket connection has been established. The bot is operational.`,"success")
botInfo.websocket = true
botInfo.lastConexion = Math.floor(new Date().getTime() / 1000)
})
return ws
} catch (error) {
wsError({message: error})
}
function wsError(error) {
botInfo.websocket = false;
if (isReconnecting) return;
isReconnecting = true;
logging(`WebSocket error, retrying to connect in 10 seconds.\n${error}: ${error.message}`, 'error');
// Retry after 10 seconds
setTimeout(wsConnect, 10000);
}

isReconnecting = false;
try {
const response = await fetch('https://raw.githubusercontent.com/Communaute-Events/paths/main/paths.json', {
method: 'GET',
headers: {'Content-Type': 'application/json'},
});

const res = await response.json();
const ws = new WebSocket(res.websocket);

// checkWs(ws)
websockets.push(ws);

ws.onmessage = (msg) => {
try {
const data = JSON.parse(msg.data.toString());
if ('_type' in data && data._type === 'event') {
alert(data, client);
}
} catch (error) {
logging(`Error in ws:\n${error}`, 'error');
}
};

ws.onclose = ({code, reason}) => {
wsError({message: reason});
};

ws.onerror = (error) => {
wsError(error);
};

ws.onopen = () => {
logging(`WebSocket connection has been established. The bot is operational.`, 'success');
botInfo.websocket = true;
botInfo.lastConexion = Math.floor(new Date().getTime() / 1000);
};
return ws;
} catch (error) {
wsError({message: error});
}
}

export async function reconnectWebsocket() {
logging("Reconnecting to the WebSocket...","info")
logging(`Closed all Websockets. (3 sec delay)`,"info")
closeWebsockets()
await setTimeout(()=>{},3000)
logging("Re-establishing connection...","info")
const ws = await wsConnect()
logging(`Connection should be up. Current state: ${ws.readyState}`,`success`)
logging('Reconnecting to the WebSocket...', 'info');
logging(`Closed all Websockets. (3 sec delay)`, 'info');
closeWebsockets();
await setTimeout(() => {}, 3000);
logging('Re-establishing connection...', 'info');
const ws = await wsConnect();
logging(`Connection should be up. Current state: ${ws.readyState}`, `success`);
}

async function automaticWsRestart() {
logging(`Automatically restarting websocket (10min interval)`,"info")
await reconnectWebsocket()
logging(`Finished automated restarting function.`,"success")
logging(`Automatically restarting websocket (10min interval)`, 'info');
await reconnectWebsocket();
logging(`Finished automated restarting function.`, 'success');
}

async function updateStatus(client: Client) {
client.user.setPresence({
activities: [
{
name: `${(await getSources()).length} évents pour ${client.guilds.cache.size} serveurs.`,
type: ActivityType.Watching,
url: 'https://commu.events/projects/events-helper',
},
],
status: 'online',
});
}

client.once(Events.ClientReady, async(c) => {
logging("Init. Client...","info")
logging(ansi(`Logged in as %bold%${c.user.tag}%end%%light_green%!%end%`),"success");
logging(`Initalizing Events...`,"info")
await initEvents(c)
logging(`Started deploying slash commands...`,"info")
await deployCommands()
logging(`All slash commands have been deployed.`,"success")
logging(`Connecting to the Event Websocket`,"info")
await wsConnect()
setInterval(automaticWsRestart,600000)
client.once(Events.ClientReady, async (c: Client) => {
logging('Init. Client...', 'info');
logging(ansi(`Logged in as %bold%${c.user.tag}%end%%light_green%!%end%`), 'success');
logging(`Initalizing Events...`, 'info');
await initEvents(c);
logging(`Started deploying slash commands...`, 'info');
await deployCommands();
logging(`All slash commands have been deployed.`, 'success');
logging(`Connecting to the Event Websocket`, 'info');
await wsConnect();
setInterval(automaticWsRestart, 600000);
updateStatus(client);
setInterval(() => {
updateStatus(c);
},60_000);
});

// Login, needs to be at the bottom
client.login(process.env.token);
client.login(process.env.token);
13 changes: 13 additions & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,19 @@ export interface BotConfig {
Admins: string[]
}

// export interface RolesConfig {
// 'Roles': {
// name: string
// emoji: string,
// id: string
// }[]
// 'Event Roles': {
// name: string
// emoji: string,
// id: string
// }[]
// }

export interface HelpCommandCategory {
name: string,
command: string,
Expand Down
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"target": "es2020"
},
"exclude": [
"node_modules"
"node_modules",
"dist"
]
}

0 comments on commit a343f65

Please sign in to comment.