-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.ts
213 lines (200 loc) · 7.14 KB
/
bot.ts
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
import { Interaction, GuildMember, Snowflake } from 'discord.js';
const Discord = require("discord.js")
import {
AudioPlayerStatus,
AudioResource,
entersState,
joinVoiceChannel,
VoiceConnectionStatus,
} from '@discordjs/voice';
import { Track } from './music/track';
import { MusicSubscription } from './music/subscription';
const express = require('express')
const path = require('path')
const app = express()
var url;
import * as youtubeSearch from "youtube-search";
const server = app.listen(process.env.PORT || 5000, () => {
console.log(`Express running → PORT ${server.address().port}`);
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
var opts: youtubeSearch.YouTubeSearchOptions = {
maxResults: 1,
key: "AIzaSyDgrGH2QnpyujPEJKJywv8Tb0w8dnkHn58"
};
const client = new Discord.Client({ intents: ['GUILD_VOICE_STATES', 'GUILD_MESSAGES', 'GUILDS'] });
client.on('ready', () => {
console.log('Ready!');
client.user.setPresence({ activities: [{ name: 'Ready!' }], status: 'online' });
});
// This contains the setup code for creating slash commands in a guild. The owner of the bot can send "!deploy" to create them.
client.on('messageCreate', async (message) => {
if (!message.guild) return;
if (!client.application?.owner) await client.application?.fetch();
if (message.content.toLowerCase() === '!deploy' && message.author.id === client.application?.owner?.id) {
await message.guild.commands.set([
{
name: 'play',
description: 'Plays a song',
options: [
{
name: 'song',
type: 'STRING' as const,
description: 'The URL of the song to play',
required: true,
},
],
},
{
name: 'skip',
description: 'Skip to the next song in the queue',
},
{
name: 'queue',
description: 'See the music queue',
},
{
name: 'pause',
description: 'Pauses the song that is currently playing',
},
{
name: 'resume',
description: 'Resume playback of the current song',
},
{
name: 'leave',
description: 'Leave the voice channel',
},
]);
await message.reply('Deployed!');
}
});
/**
* Maps guild IDs to music subscriptions, which exist if the bot has an active VoiceConnection to the guild.
*/
const subscriptions = new Map<Snowflake, MusicSubscription>();
// Handles slash command interactions
client.on('interactionCreate', async (interaction: Interaction) => {
if (!interaction.isCommand() || !interaction.guildId) return;
let subscription = subscriptions.get(interaction.guildId);
if (interaction.commandName === 'play') {
// Extract the video URL from the command
if(interaction.options.get('song')!.value!.toString().includes("http")) {
url = interaction.options.get('song')!.value! as string;
} else {
const query = interaction.options.get('song')!.value! as string;
await youtubeSearch(query, opts, (err, results) => {
if(err) return console.log(err);
console.log("yes: " + results[0].link)
url = results[0].link
});
}
// If a connection to the guild doesn't already exist and the user is in a voice channel, join that channel
// and create a subscription.
if (!subscription) {
if (interaction.member instanceof GuildMember && interaction.member.voice.channel) {
const channel = interaction.member.voice.channel;
subscription = new MusicSubscription(
joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
}),
);
subscription.voiceConnection.on('error', console.warn);
subscriptions.set(interaction.guildId, subscription);
}
}
// If there is no subscription, tell the user they need to join a channel.
if (!subscription) {
await interaction.followUp('Join a voice channel and then try that again!');
return;
}
// Make sure the connection is ready before processing the user's request
try {
await entersState(subscription.voiceConnection, VoiceConnectionStatus.Ready, 20e3);
} catch (error) {
console.warn(error);
await interaction.followUp('Failed to join voice channel within 20 seconds, please try again later!');
return;
}
try {
interaction.deferReply();
// Attempt to create a Track from the user's video URL
await new Promise(resolve => setTimeout(resolve, 10));
const track = await Track.from(url, {
onStart() {
client.user.setPresence({ activities: [{ name: `${track.title}` }], status: 'online' });
interaction.followUp({ content: 'Now playing!', ephemeral: true }).catch(console.warn);
},
onFinish() {
client.user.setPresence({ activities: [{ name: `Nothing` }], status: 'idle' });
interaction.followUp({ content: 'Now finished!', ephemeral: true }).catch(console.warn);
},
onError(error) {
console.warn(error);
interaction.followUp({ content: `Error: ${error.message}`, ephemeral: true }).catch(console.warn);
},
});
// Enqueue the track and reply a success message to the user
subscription.enqueue(track);
await interaction.followUp(`Enqueued **${track.title}**`);
} catch (error) {
console.warn(error);
await interaction.reply('Failed to play track, please try again later!');
}
} else if (interaction.commandName === 'skip') {
if (subscription) {
// Calling .stop() on an AudioPlayer causes it to transition into the Idle state. Because of a state transition
// listener defined in music/subscription.ts, transitions into the Idle state mean the next track from the queue
// will be loaded and played.
subscription.audioPlayer.stop();
await interaction.reply('Skipped song!');
} else {
await interaction.reply('Not playing in this server!');
}
} else if (interaction.commandName === 'queue') {
// Print out the current queue, including up to the next 5 tracks to be played.
if (subscription) {
const current =
subscription.audioPlayer.state.status === AudioPlayerStatus.Idle
? `Nothing is currently playing!`
: `Playing **${(subscription.audioPlayer.state.resource as AudioResource<Track>).metadata.title}**`;
const queue = subscription.queue
.slice(0, 5)
.map((track, index) => `${index + 1}) ${track.title}`)
.join('\n');
await interaction.reply(`${current}\n\n${queue}`);
} else {
await interaction.reply('Not playing in this server!');
}
} else if (interaction.commandName === 'pause') {
if (subscription) {
subscription.audioPlayer.pause();
await interaction.reply({ content: `Paused!`, ephemeral: true });
} else {
await interaction.reply('Not playing in this server!');
}
} else if (interaction.commandName === 'resume') {
if (subscription) {
subscription.audioPlayer.unpause();
await interaction.reply({ content: `Unpaused!`, ephemeral: true });
} else {
await interaction.reply('Not playing in this server!');
}
} else if (interaction.commandName === 'leave') {
if (subscription) {
subscription.voiceConnection.destroy();
subscriptions.delete(interaction.guildId);
await interaction.reply({ content: `Left channel!`, ephemeral: true });
} else {
await interaction.reply('Not playing in this server!');
}
} else {
await interaction.reply('Unknown command');
}
});
client.on('error', console.warn);
void client.login();