-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.js
242 lines (203 loc) · 7.93 KB
/
app.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
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
import 'dotenv/config';
import express from 'express';
import { DateTime } from 'luxon';
import axios from 'axios';
import crypto from 'crypto';
import { Client, Events, GatewayIntentBits, EmbedBuilder } from 'discord.js';
import {
InteractionType,
InteractionResponseType,
InteractionResponseFlags,
MessageComponentTypes,
ButtonStyleTypes,
} from 'discord-interactions';
import { VerifyDiscordRequest, getRandomEmoji, DiscordRequest } from './utils.js';
import {
RIDETHEWAVE_COMMAND,
HasGuildCommands,
} from './commands.js';
import cache from './cache.js';
import { getAccessToken } from './strava.js';
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
let channel = null
client.once(Events.ClientReady, c => {
channel = client.channels.cache.get('1058121514404282428');
console.log('Ready! Logged in as '+c.user.tag);
console.log('Currently sending updates in :'+channel)
});
client.login(process.env.DISCORD_TOKEN);
function generateHash(string) {
var hash = 0;
if (string.length == 0)
return hash;
for (let i = 0; i < string.length; i++) {
var charCode = string.charCodeAt(i);
hash = ((hash << 7) - hash) + charCode;
hash = hash & hash;
}
return hash;
}
// Create an express app
const app = express();
// Get port, or default to 3000
const PORT = process.env.PORT || 3000;
// Parse request body and verifies incoming requests using discord-interactions package
app.use(express.json({ verify: VerifyDiscordRequest(process.env.PUBLIC_KEY) }));
/**
* Interactions endpoint URL where Discord will send HTTP requests
*/
app.post('/interactions', async function (req, res) {
// Interaction type and data
const { type, id, data } = req.body;
/**
* Handle verification requests
*/
if (type === InteractionType.PING) {
return res.send({ type: InteractionResponseType.PONG });
}
/**
* Handle slash command requests
* See https://discord.com/developers/docs/interactions/application-commands#slash-commands
*/
if (type === InteractionType.APPLICATION_COMMAND) {
const { name } = data;
// "ridethewave" guild command
if (name === 'ridethewave') {
const exampleEmbed = new EmbedBuilder()
.setColor('#5563fa')
.setTitle('MLC Wave Runners')
.setAuthor({ name: 'Strava' })
.setURL('https://strava.com/clubs/mlc-wave-runners/')
.setThumbnail('https://asweinrich.dev/media/WAVERUNNERS.png')
.setDescription('Join the club and run with the best')
.setTimestamp()
.setFooter({ text: 'MLC Wave Runners', iconURL: 'https://asweinrich.dev/media/WAVERUNNERS.png' });
// Send a message into the channel where command was triggered from
return res.send({
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
embeds: [exampleEmbed]
}
});
}
// additional guild commands go here:
}
});
app.listen(PORT, () => {
console.log('Listening on port', PORT);
// Check if guild commands from commands.js are installed (if not, install them)
HasGuildCommands(process.env.APP_ID, process.env.GUILD_ID, [
RIDETHEWAVE_COMMAND,
]);
});
let lastActivityString = null;
let accessToken = null;
setInterval(() => {
const lastActivityString = cache.get('lastActivityString', null) || 'No activities'
console.log('Last Activity: '+cache.get('lastActivityString', null))
getAccessToken()
.then(token => {
accessToken = token
})
.catch(error => {
console.error(error)
})
axios.get('https://www.strava.com/api/v3/clubs/1100648/activities?page=1&per_page=1', {
headers: {
'Authorization': 'Bearer '+accessToken
}
}).then((response) => {
const data = response.data
const activityName = data[0].name
const athlete = data[0].athlete.firstname+' '+data[0].athlete.lastname
const dist = Number((data[0].distance/1609.34).toFixed(2))
const seconds = data[0].moving_time
const secondsTot = data[0].elapsed_time
let duration = 0
if(seconds > 3600) {
const hours = Math.trunc(seconds/3600)
const minutes = ((seconds%3600)/60).toFixed(0)
duration = hours+' Hr '+minutes+' Min'
} else {
const minutes =(seconds/60).toFixed(0)
duration = minutes+' Min'
}
let durationTot = 0
if(secondsTot > 3600) {
const hoursTot = Math.trunc(secondsTot/3600)
const minutesTot = ((secondsTot%3600)/60).toFixed(0)
durationTot = hoursTot+' Hr '+minutesTot+' Min'
} else {
const minutesTot = (seconds/60).toFixed(0)
durationTot = minutesTot+' Min'
}
const activityString = 'ATHL:'+athlete+'-DIST:'+dist+'-TIME:'+seconds
cache.set('lastActivityString', activityString)
if(lastActivityString === activityString) {
console.log('Last Activity String: '+lastActivityString);
console.log('No New Activites');
} else {
const speed = (dist/(seconds/3600)).toFixed(1)
const paceRaw = (seconds/dist)
const paceMin = Math.trunc(paceRaw/60)
let paceSec = (((paceRaw/60)%paceMin)*60).toFixed(0)
if(paceSec < 10) {
paceSec = paceSec.toString().padStart(2, '0')
}
const pace = paceMin+':'+paceSec
const activity = data[0].sport_type
let message
console.log(response.data);
if(activity === 'Ride') {
message = athlete+' just completed a '+dist+' mile '+activity.toLowerCase()+'!'
// inside a command, event listener, etc.
const exampleEmbed = new EmbedBuilder()
.setColor('#5563fa')
.setTitle(activityName)
.setDescription(message)
.addFields(
{ name: 'Distance', value: dist+' Miles', inline: true },
{ name: 'Time', value: duration, inline: true },
{ name: 'Avg Speed', value: speed+' MPH', inline: true },
)
.setThumbnail('https://asweinrich.dev/media/WAVERUNNERS.png')
.setTimestamp()
.setFooter({ text: 'MLC Wave Runners' , iconURL: 'https://asweinrich.dev/media/WAVERUNNERS.png'});
channel.send({ embeds: [exampleEmbed] });
} else if(activity === 'Run') {
message = athlete+' just completed a '+dist+' mile '+activity.toLowerCase()+'!'
// inside a command, event listener, etc.
const exampleEmbed = new EmbedBuilder()
.setColor('#77c471')
.setTitle(activityName)
.setDescription(message)
.addFields(
{ name: 'Distance', value: dist+' Miles', inline: true },
{ name: 'Time', value: duration, inline: true },
{ name: 'Avg Pace', value: pace+' per mile', inline: true },
)
.setThumbnail('https://asweinrich.dev/media/WAVERUNNERS.png')
.setTimestamp()
.setFooter({ text: 'MLC Wave Runners' , iconURL: 'https://asweinrich.dev/media/WAVERUNNERS.png' });
channel.send({ embeds: [exampleEmbed] });
} else {
message = athlete+' just completed a '+durationTot+' '+activity.toLowerCase()+' session!'
// inside a command, event listener, etc.
const exampleEmbed = new EmbedBuilder()
.setColor('#aa0000')
.setTitle(activityName)
.setDescription(message)
.addFields(
{ name: 'Distance', value: dist+' Miles', inline: true },
{ name: 'Time', value: durationTot, inline: true },
)
.setThumbnail('https://asweinrich.dev/media/WAVERUNNERS.png')
.setTimestamp()
.setFooter({ text: 'MLC Wave Runners' , iconURL: 'https://asweinrich.dev/media/WAVERUNNERS.png' });
channel.send({ embeds: [exampleEmbed] });
}
}
}).catch((error) => {
console.error(error);
});
}, 300000);