-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
254 lines (222 loc) · 7.75 KB
/
Copy pathindex.js
File metadata and controls
254 lines (222 loc) · 7.75 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
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
require('dotenv').config(); // Needed to read .env files
const fs = require('fs');
const path = require('node:path');
const express = require('express') // HTTP server
const app = express()
const bodyParser = require('body-parser');
const port = process.env.HTTP_PORT // Get port from .env
// Require the necessary discord.js classes
const { Client, Collection, Events, GatewayIntentBits, EmbedBuilder } = require('discord.js');
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// Log in to Discord with your client's token
client.login(process.env.DISCORD_TOKEN);
// Load json
var variables = require('./variables.json')
function authentication(req, res, next) {
if (process.env.HTTP_REQUIRE_AUTHENTICATION == "true") { // Check if authentication is enabled
var authheader = req.headers.authorization;
if (!authheader) { // Needed to prevent errors
res.status(401).send('Invalid credentials')
return;
}
var auth = new Buffer.from(authheader.split(' ')[1], 'base64').toString().split(':');
var user = auth[0];
var pass = auth[1];
if (user == process.env.HTTP_USER && pass == process.env.HTTP_PASSWORD) {
// If Authorized user
next();
} else {
res.status(401).send('Invalid credentials')
return;
}
} else { // Bypass authentication
next();
}
}
app.use(authentication)
app.use(bodyParser.json({ type: 'application/*+json' }))
app.post('/api/', (req, res) => {
const battery = req.query.batt;
const charging = req.query.charging;
const lock = req.query.lock
const location = req.query.loc;
const alarm = req.query.alarm;
const batterytemp = req.query.batttemp;
if (battery) {
client.channels.fetch(readVariable("CHANNEL_ID"))
.then(channel => {
channel.messages.fetch(readVariable("MESSAGE_ID"))
.then(message => {
// Get the embed from the message
let embed = message.embeds[0];
// Edit the fields
for (let i = 0; i < embed.fields.length; i++) {
if (embed.fields[i].name === "🔋 Battery percentage") {
embed.fields[i].value = Math.round(battery) + "%";
}
}
// Edit the message with the new embed
message.edit({ embeds: [embed] });
});
});
}
if (batterytemp) {
client.channels.fetch(readVariable("CHANNEL_ID"))
.then(channel => {
channel.messages.fetch(readVariable("MESSAGE_ID"))
.then(message => {
// Get the embed from the message
let embed = message.embeds[0];
// Edit the fields
for (let i = 0; i < embed.fields.length; i++) {
if (embed.fields[i].name === "🌡️ Battery temperature") {
embed.fields[i].value = batterytemp + "ºC";
}
}
// Edit the message with the new embed
message.edit({ embeds: [embed] });
});
});
}
if (charging) {
client.channels.fetch(readVariable("CHANNEL_ID"))
.then(channel => {
channel.messages.fetch(readVariable("MESSAGE_ID"))
.then(message => {
// Get the embed from the message
let embed = message.embeds[0];
// Edit the fields
for (let i = 0; i < embed.fields.length; i++) {
if (embed.fields[i].name === "🔌 Charger connected") {
embed.fields[i].value = charging;
}
}
// Edit the message with the new embed
message.edit({ embeds: [embed] });
});
});
}
if (lock) {
client.channels.fetch(readVariable("CHANNEL_ID"))
.then(channel => {
channel.messages.fetch(readVariable("MESSAGE_ID"))
.then(message => {
// Get the embed from the message
let embed = message.embeds[0];
// Edit the fields
for (let i = 0; i < embed.fields.length; i++) {
if (embed.fields[i].name === "🔓 Screen unlocked") {
embed.fields[i].value = lock;
}
}
// Edit the message with the new embed
message.edit({ embeds: [embed] });
});
});
}
if (location) {
client.channels.fetch(readVariable("CHANNEL_ID"))
.then(channel => {
channel.messages.fetch(readVariable("MESSAGE_ID"))
.then(message => {
// Get the embed from the message
let embed = message.embeds[0];
// Edit the fields
for (let i = 0; i < embed.fields.length; i++) {
if (embed.fields[i].name === "🏠 At home?") {
embed.fields[i].value = location;
}
}
// Edit the message with the new embed
message.edit({ embeds: [embed] });
});
});
}
if (alarm) {
function unixTimestamp(date = Date.now()) {
return Math.floor(date / 1000)
}
client.channels.fetch(readVariable("CHANNEL_ID"))
.then(channel => {
channel.messages.fetch(readVariable("MESSAGE_ID"))
.then(message => {
// Get the embed from the message
let embed = message.embeds[0];
// Edit the fields
for (let i = 0; i < embed.fields.length; i++) {
if (embed.fields[i].name === "⏰ Last alarm") {
embed.fields[i].value = `<t:${unixTimestamp()}:f>`;
}
}
// Edit the message with the new embed
message.edit({ embeds: [embed] });
});
});
}
//console.log(battery, charging, location)
res.sendStatus(200)
})
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);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
client.commands.set(command.data.name, command);
}
// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, c => {
console.log(`Ready! Logged in as ${c.user.tag}`);
app.listen(port, () => {
console.log(`Waiting for requests on port ${port}`)
})
});
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
} else {
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
}
});
/**
* Change a value of the variables.json file
* @param {*} key
* @param {*} value
*/
function writeVariable(key, value) {
variables[key] = value;
fs.writeFile('./variables.json', JSON.stringify(variables), (err) => {
if (err) {
console.error(err);
} else {
console.log(`Successfully wrote ${key} with value ${value} to variables.json`);
}
});
}
/**
* Read a value from the variables.json file
* @param {*} key
* @returns {*} The value associated with the key, or null if the key doesn't exist
*/
function readVariable(key) {
if (variables.hasOwnProperty(key)) {
return variables[key];
} else {
return null;
}
}