-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
175 lines (145 loc) · 5.29 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
// Require the necessary discord.js classes
const fs = require('node:fs');
const path = require('node:path');
const https = require('https');
const { Client, Collection, GatewayIntentBits, InteractionType, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js');
const { token } = require('./config.json');
let stations; // Stations info
let station_names = []; // Stations name (for autocompletion)
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// Parsing existing commands
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
client.commands.set(command.data.name, command);
}
function updateStationInformation(raw_data) {
stations = JSON.parse(raw_data).data.stations;
for (i in stations) {
station_names.push(stations[i].name);
}
!fs.existsSync(path.join(__dirname, 'data')) && fs.mkdirSync(path.join(__dirname, 'data'));
fs.writeFileSync('data/data.json', JSON.stringify(stations));
console.log('Updated stations informations.')
}
// Executed at start
client.once('ready', () => {
// Loading and storing stations infos
https.get('https://velib-metropole-opendata.smoove.pro/opendata/Velib_Metropole/station_information.json', (resp) => {
let raw_data = '';
resp.on('data', (chunk) => {
raw_data += chunk;
});
resp.on('end', () => {
updateStationInformation(raw_data)
setInterval(updateStationInformation, 86400000);
console.log('Ready!');
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
});
// Handling interactions
client.on('interactionCreate', async interaction => {
// Handling commands
if (interaction.isChatInputCommand()) {
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
if (interaction.inGuild()) {
console.log(`> /${interaction.commandName} | ` + `tag: ${interaction.user.tag}` + `, server: ${interaction.guild.name}`);
} else {
console.log(`> /${interaction.commandName} | ` + `tag: ${interaction.user.tag}` + `, server: [None]`);
}
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
}
// Handling autocompletion
else if (interaction.type == InteractionType.ApplicationCommandAutocomplete) {
if (interaction.commandName === 'get') {
const focusedValue = interaction.options.getFocused();
let filtered = station_names.filter(choice => (choice.startsWith(focusedValue) || choice.toLowerCase().startsWith(focusedValue)));
if (filtered.length > 25) {
filtered = filtered.splice(0, 25);
}
await interaction.respond(
filtered.map(choice => ({ name: choice, value: choice })),
);
}
}
// Handling Button (Reload button)
else if (interaction.isButton()) {
// Get station names
const ids = [];
const names = [];
const stations = JSON.parse(fs.readFileSync('data/data.json'));
for (i in interaction.message.embeds[0].fields) {
names[i] = interaction.message.embeds[0].fields[i].name.slice(3);
}
// Get station IDs
for (i in interaction.message.embeds[0].fields) {
for (y in stations) {
if (stations[y].name === names[i]) {
ids.push(stations[y].station_id);
break;
}
}
}
// Get data and update the embed message
https.get('https://velib-metropole-opendata.smoove.pro/opendata/Velib_Metropole/station_status.json', (resp) => {
let raw_data = '';
resp.on('data', (chunk) => {
raw_data += chunk;
});
resp.on('end', () => {
const infos = JSON.parse(raw_data).data.stations;
const new_data = {};
for (i in infos) {
for (y in ids) {
if (infos[i].station_id == ids[y]) {
new_data[y] = infos[i];
break;
}
}
}
const fields = [];
for (i in new_data) {
fields[i] = {
name: `${Number(i) + 1}. ${names[i]}`,
value: `🟩 : **${new_data[i].num_bikes_available_types[0].mechanical}** · 🟦 : **${new_data[i].num_bikes_available_types[1].ebike}** · 🅿️ : **${new_data[i].num_docks_available}**`
};
}
const new_embed = new EmbedBuilder()
.setColor(0x473c6b)
.setFields(fields)
.setImage(interaction.message.embeds[0].data.image.url)
.setTimestamp()
.setFooter({ text: interaction.message.embeds[0].data.footer.text });
const row = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId('reload')
.setStyle(ButtonStyle.Primary)
.setLabel(' Recharger les infos. '));
interaction.update({ embeds: [new_embed], files: [], components: []})
.then(setTimeout(() => {interaction.editReply({ components: [row]})}, 30000));
});
}).on("error", (err) => {
console.log(err);
});
if (interaction.inGuild()) {
console.log(`Reload button for ${interaction.user.tag} in server ${interaction.guild.name}`)
} else {
console.log(`Reload button for ${interaction.user.tag} in DM.`)
}
}
});
// Login to Discord with your client's token
client.login(token);