-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.js
236 lines (199 loc) · 6.96 KB
/
bot.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
import { Client, EmbedBuilder } from "discord.js";
import { VoiceConnectionStatus, entersState } from "@discordjs/voice";
import { config } from "dotenv";
import { CLIENT_CONFIG, TIMER_SETTINGS, SOUND_CONFIG } from "./config.js";
import {
createWelcomeMessage,
formatTimerMessage,
createCancelButton,
createCancelledMessage
} from "./utils/messages.js";
import {
connectToVoice,
muteMembersInChannel,
playChime,
} from "./utils/voice.js";
import fs from "fs";
// Load environment variables
config();
// Initialise Discord client
const client = new Client(CLIENT_CONFIG);
let currentSessionInterval;
let currentVoiceConnection;
// Verify sound file exists before starting
if (!fs.existsSync(SOUND_CONFIG.CHIME_PATH)) {
console.error("Error: Sound file not found at", SOUND_CONFIG.CHIME_PATH);
currentVoiceConnection.destroy();
process.exit(1);
}
// Log when bot is ready and connected to Discord
client.once("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
// Listen for the "hi pomo" command in chat
client.on("messageCreate", async (message) => {
if (message.content.toLowerCase() === "hi pomo") {
const welcomeMessage = createWelcomeMessage();
// Send welcome message with session options
await message.channel.send({
embeds: [welcomeMessage.embed],
components: [welcomeMessage.buttons],
});
}
});
// Handle all button interactions (session start, cancel)
client.on("interactionCreate", async (interaction) => {
// Ignore non-button interactions
if (!interaction.isButton()) return;
const member = interaction.member;
const voiceChannel = member?.voice.channel;
// Check if user is in a voice channel
if (!voiceChannel) {
return interaction.reply({
content: "You need to be in a voice channel!",
ephemeral: true, // Only visible to the user who clicked
});
}
await interaction.deferReply();
// Handle session cancellation
if (interaction.customId === "cancel_session") {
if (currentSessionInterval) clearInterval(currentSessionInterval);
await muteMembersInChannel(voiceChannel, false);
const sessionCancelledMessage = createCancelledMessage()
await interaction.editReply({
embeds: [sessionCancelledMessage],
components: [],
});
if (currentVoiceConnection) currentVoiceConnection.destroy();
return;
}
// Connect to voice channel and set up event handlers
currentVoiceConnection = connectToVoice(voiceChannel);
// Voice connection event handlers
currentVoiceConnection.on("ready", () => {
console.log("Connected to the voice channel!");
});
// Handle disconnection attempts and reconnection
currentVoiceConnection.on(VoiceConnectionStatus.Disconnected, async () => {
try {
await Promise.race([
entersState(
currentVoiceConnection,
VoiceConnectionStatus.Signalling,
5_000
),
entersState(
currentVoiceConnection,
VoiceConnectionStatus.Connecting,
5_000
),
]);
} catch (error) {
currentVoiceConnection.destroy();
console.error("Voice connection disconnected:", error);
}
});
// Handle voice connection errors
currentVoiceConnection.on("error", (error) => {
console.error(`Voice connection error: ${error.message}`);
interaction.followUp(
"An error occurred while connecting to the voice channel."
);
});
// Main Pomodoro session handler
const startPomoSession = async (focusDuration, breakDuration) => {
// Mute all users at start of focus session
await muteMembersInChannel(voiceChannel, true);
let timerMessage = await interaction.editReply({
...formatTimerMessage("Focus", focusDuration),
components: [createCancelButton()],
});
const startTime = Date.now();
// Update timer every TIMER_SETTINGS.UPDATE_INTERVAL milliseconds
currentSessionInterval = setInterval(async () => {
const elapsedTime = Date.now() - startTime;
const remainingTime = focusDuration - elapsedTime;
// When focus timer ends
if (remainingTime <= 0) {
clearInterval(currentSessionInterval);
playChime(currentVoiceConnection);
await muteMembersInChannel(voiceChannel, false);
// Show completion message and start break
const completionEmbed = new EmbedBuilder()
.setColor("#43b581")
.setTitle("Focus Session Complete! 🎉")
.setDescription("Great work! Time for a break.")
.addFields({
name: "Next up",
value: `${
breakDuration === TIMER_SETTINGS.SHORT_BREAK ? "5" : "15"
} minute break`,
});
await timerMessage.edit({
embeds: [completionEmbed],
components: [],
});
// Start break session
await startBreak(
breakDuration === TIMER_SETTINGS.SHORT_BREAK
? "Short Break"
: "Long Break",
breakDuration,
timerMessage
);
return;
}
// Update timer display
timerMessage.edit({
...formatTimerMessage("Focus", remainingTime),
components: [createCancelButton()],
});
}, TIMER_SETTINGS.UPDATE_INTERVAL);
};
// Break session handler
const startBreak = async (breakType, breakDuration, timerMessage) => {
const startTime = Date.now();
// Update break timer display
currentSessionInterval = setInterval(async () => {
const elapsedTime = Date.now() - startTime;
const remainingTime = breakDuration - elapsedTime;
// When break timer ends
if (remainingTime <= 0) {
clearInterval(currentSessionInterval);
// Play the chime
playChime(currentVoiceConnection);
// Wait for a short duration to ensure the chime plays
setTimeout(async () => {
if (currentVoiceConnection) currentVoiceConnection.destroy();
// Show break completion message
const breakCompletionEmbed = new EmbedBuilder()
.setColor("#43b581")
.setTitle("Break Complete! ⏰")
.setDescription("Ready for another session?")
.addFields({
name: "Start New Session",
value: 'Type "hi pomo" to begin',
});
await timerMessage.edit({
embeds: [breakCompletionEmbed],
components: [],
});
}, TIMER_SETTINGS.UPDATE_INTERVAL);
return;
};
// Update break timer display
timerMessage.edit({
...formatTimerMessage(breakType, remainingTime),
components: [],
});
}, TIMER_SETTINGS.UPDATE_INTERVAL);
};
// Handle session type selection
if (interaction.customId === "focus_short") {
await startPomoSession(TIMER_SETTINGS.FOCUS, TIMER_SETTINGS.SHORT_BREAK);
} else if (interaction.customId === "focus_long") {
await startPomoSession(TIMER_SETTINGS.FOCUS, TIMER_SETTINGS.LONG_BREAK);
}
});
// Connect bot to Discord
client.login(process.env.BOT_TOKEN);