I am working on building a Discord Music Bot. Right now, when I send the command in Discord "!play " I get no response from the bot. It seems the bot returns the message content as empty. Here is my code:
const Discord = require("discord.js");
const { Client, Intents } = require("discord.js");
const ytdl = require("ytdl-core");
const youtubeSearch = require("youtube-search");
const dotenv = require("dotenv");
dotenv.config(); // Load environment variables from .env file
const { YT_API_KEY, DISCORD_BOT_TOKEN } = process.env;
if (!YT_API_KEY) {
console.error("Missing YouTube API key!");
process.exit(1);
}
if (!DISCORD_BOT_TOKEN) {
console.error("Missing Discord bot token!");
process.exit(1);
}
const client = new Client({ intents: 32767 });
const opts = {
maxResults: 1,
key: YT_API_KEY,
type: "video",
videoCategoryId: "10",
};
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", async (msg) => {
console.log("Received play command!: " + msg.content);
if (!msg.content.trim()) {
return; // Ignore empty or whitespace-only messages
}
console.log(`Received message: ${msg.content}`);
console.log(`Message length: ${msg.content.length}`);
if (msg.content.startsWith("!play")) {
console.log("Received play command!");
const channel = msg.member?.voice.channel;
console.log(`Channel: ${channel}`);
if (!channel) {
console.log("User not in a voice channel!");
return msg.reply(
"You need to join a voice channel before I can play music!"
);
}
const query = msg.content.substring(6).trim();
try {
const results = await youtubeSearch(query, opts);
console.log("Results:", results);
if (results.length === 0) {
return msg.reply("No video results found!");
}
const connection = await channel.join();
connection.on("error", console.error);
const stream = ytdl(results[0].link, { filter: "audioonly" });
console.log(`Playing: ${results[0].title}`);
console.log(`URL: ${results[0].link}`);
const dispatcher = connection.play(stream);
dispatcher.on("finish", () => {
channel.leave();
});
} catch (err) {
console.error(err);
msg.reply("An error occurred while playing the song!");
}
}
});
client.login(DISCORD_BOT_TOKEN);
I have tried using:
client.on("messageCreate", async (msg) => {
console.log("Received play command!: " + msg.content);
if (!msg.content.trim()) {
return; // Ignore empty or whitespace-only messages
}
And also get no response from msg.content
Does anyone see what might be wrong? Thank you!