I have this problem where it always says MessageEmbed is not defined! I don't know why it says that please help me! I have tried to solve this problem but nothing solved the problem!
const wait = require('util').promisify(setTimeout);
const OWNER_ID = require("../../config.json").OWNER_ID;
const { MessageEmbed }= require('discord.js');
require('dotenv').config();
var token = process.env.BOT_TOKEN;
module.exports = {
name: "restart",
description: "restarts the bot",
async execute(interaction, client) {
const logMsg = `Command Used: \`RESTART\` \nUser: \`${interaction.user.id}\` \nChannel: \`${interaction.channel.id} (${interaction.channel.name})\``;
client.channels.cache.get(client.config.errorLog).send(logMsg);
try {
if (interaction.user.id != OWNER_ID || ID) {
await interaction.reply({content: "RESTARRR...",ephemeral: true});
await wait(1000);
await interaction.editReply({content:"Wait ... What?!",ephemeral: true});
await wait(2000);
return await interaction.editReply({content:"Bruh! You are not a developer, this command is not for you : )",ephemeral: true});
}
await interaction.reply("RESTARTING FAST AS F BOIIIIII ...").then((m) => {
client.destroy(BOT_TOKEN);
});
await wait(2000).then((m) => {
client.login(BOT_TOKEN);
});
await interaction.editReply("Damn! I'm Back 🔥");
} catch(err) {
const errTag = client.config.errTag;
client.channels.cache.get(client.config.ERROR_LOGS_CHANNEL).send(`**ERROR!** ${errTag} \n${err}\nCommand: \`RESTART\` \nChannel: \`${interaction.channel.id} (${interaction.channel.name})\` \n User: \`${interaction.user.id}\`\n`);
}
},
};
I have tried to solve this problem but nothing happened!
here the code in the command.js file
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
try {
command.run(client, message, args, p, cooldowns);
} catch (error) {
console.error(error);
let embed2000 = new MessageEmbed()
.setDescription("There was an error executing that command.")
.setColor("BLUE");
message.channel.send({ embeds: [embed2000] }).catch(console.error);
}
};
Related
I want to make a Discord bot that can react to the slash commands and "type" commands. To prevent naming collisions, I renamed the command variable into scommand. However, when I do this, the code of slash command doesn't work. How can I fix it?
discord.js version: 12.5.3
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const {Collection} = require("discord.js")
const scommands = [];
const scommandFiles = fs.readdirSync('./slash.commands').filter(file => file.endsWith('.js'));
client.scommands = new Collection();
const clientId = process.env["clientId"]
for (const file of scommandFiles) {
try {
const scommand = require(`./slash.commands/${file}`);
scommands.push(scommand.data.toJSON());
client.scommands.set(scommand.data.name, scommand)
} catch (err) {console.log(err)}
}
const rest = new REST({ version: '10' }).setToken(token);
(async () => {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationCommands(clientId),
{ body: scommands },
);
console.log('Successfully reloaded application (/) commands.');
})();
client.ws.on('INTERACTION_CREATE', async interaction => {
if (!interaction.isChatInputCommand()) return;
const command = client.scommands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
This is the code of the file in the ./slash.commands folder:
const { SlashCommandBuilder } = require('#discordjs/builders');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('pong'),
async execute(interaction){
interaction.reply("pong")
}
Is it ok to use scommand and how should I fix it?
It seems to me, you declared a scommands field in client, but when executing, you refer to it as commands...
Try:
const command = client.scommands.get(interaction.commandName);
(sry for my English)
I just want to make a simple reaction message, connection to vocal where user use one word as "exemple" in this "it is an exemple", and play one song.mp3, after the bot deconnect when he finish this song.mp3.
This is my index.js
const { Client, VoiceChannel, Intents } = require('discord.js');
const client = new Client({ intents: 32767 });
const dotenv = require('dotenv'); dotenv.config();
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource,
entersState,
StreamType,
AudioPlayerStatus,
VoiceConnectionStatus,
} = require ('#discordjs/voice');
const { createDiscordJSAdapter } = require ('./?');
const player = createAudioPlayer();
client.login(process.env.DISCORD_TOKEN);
function playSong() {
const resource = createAudioResource('./music/try.mp3', {
inputType: StreamType.Arbitrary,
});
player.play(resource);
return entersState(player, AudioPlayerStatus.Playing, 5e3);
};
client.on('ready', async () => {
console.log('Discord.js client is ready!');
try {
await playSong();
console.log('Song is ready to play!');
} catch (error) {
console.error(error);
}
});
async function connectToChannel(channel = VoiceChannel) {
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: createDiscordJSAdapter(channel),
});
try {
await entersState(connection, VoiceConnectionStatus.Ready, 30e3);
return connection;
} catch (error) {
connection.destroy();
throw error;
}
};
client.on('messageCreate', async (message) => {
if (!message.guild) return;
if (message.content === '-join') {
const channel = message.member?.voice.channel;
if (channel) {
try {
const connection = await connectToChannel(channel);
connection.subscribe(player);
await message.reply('Playing now!');
} catch (error) {
console.error(error);
}
} else {
void message.reply('Join a voice channel then try again!');
}
}
});
I have this error :
Screenshot of console error
This error is here in my index.js :
const { createDiscordJSAdapter } = require ('./?');
I just don't know how import this function createDiscordJSAdapter ....
I have my .env file true, (the bot is connected to my server).
I have my folder music with my song name "try.mp3".
And this index.js :D
If someone can help me to build this simple exemple,
Thx !
Sunclies
I have not touched js in years, hense I'm quite rusty in terms of coding in javascript. If you have answers, feel free to tell me and critizise!
Inside ping.js
const { SlashCommandBuilder } = require('#discordjs/builders');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
return interaction.reply('Pong!');
},
};
in my bot.js file
client.commands = new Collection();
const commandFiles = fs.readdirSync('./src/commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./src/commands/${file}`);
client.commands.set(command.data.name, command);
}
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
Im new to Discod.js v13. I get this error
(async () => {
^
TypeError: (intermediate value) is not a function
This is the code i think its the problem
const rest = new REST({
version: "9"
}).setToken("MyToken")
(async () => {
If you need the full code:
const { Client, Intents, Collection } = require("discord.js")
const fs = require("fs")
const {REST} = require("#discordjs/rest");
const {Routes} = require("discord-api-types/v9");
const client = new Client({
intents:[
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
})
const BotName = "TestBot"
const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));
const commands = []
client.commands = new Collection()
for(const file of commandFiles){
const command = require("./commands/"+file)
commands.push(command.data.toJSON());
client.commands.set(command.data.name, command)
}
client.once("ready", applicationId =>{
console.log(`${BotName} is now online`)
const CLIENT_ID = client.user.id
const rest = new REST({
version: "9"
}).setToken("MyToken")
(async () => {
try{
if(process.env.ENV === "production"){
await rest.put(Routes.applicationCommands(CLIENT_ID), {
body: commands
})
console.log("Success command register globally")
}else{
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID), {
body: commands
})
console.log("Success command register locally")
}
}catch(err){
console.log(err)
}
})();
})
client.on("interaction", async interaction =>{
if(!interaction.isCommand()) return
const command = client.commands.get(interaction.commandName)
if(!command) return
try{
await command.execute(interaction);
}catch(err){
console.log(err)
await interaction.reply({
content: "ERROR" + err,
ephemeral:true
})
}
})
client.login("MyToken")
As said in my comment, this is a ASI (automatic semicolon insertion) related error. I checked it, and after putting a semicolon after }).setToken("MyToken"); it worked fine.
Always use semicolons to avoid these mistakes.
I'm trying to create a ping command for my discord bot. My code seems pretty straightforward:
index.js:
require("dotenv").config();
const { Client, Intents, Collection } = require("discord.js");
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
const fs = require("fs");
client.commands = new Collection();
const commandFiles = fs
.readdirSync("./commands")
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
}
const eventFiles = fs
.readdirSync("./events")
.filter((file) => file.endsWith(".js"));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client));
}
}
client.on("interactionCreate", (interaction) => {
console.log(interaction);
});
client.login(process.env.TOKEN);
messageCreate.js:
require("dotenv").config();
module.exports = {
name: "messageCreate",
on: true,
async execute(msg, client) {
// If message author is a bot, or the message doesn't start with the prefix, return.
if (msg.author.bot || !msg.content.startsWith(process.env.PREFIX)) return;
var command = msg.content.substring(1).split(" ")[0].toLowerCase();
// Remove the command from the args
var args = msg.content.substring().split(/(?<=^\S+)\s/)[1];
if (!client.commands.has(command)) return;
try {
await client.commands.get(command).execute(msg, args, client);
} catch (error) {
console.error(error);
await msg.reply({
content: "Error: Please check console for error(s)",
ephemeral: true,
});
}
},
};
ping.js:
const { SlashCommandBuilder } = require("#discordjs/builders");
const { MessageEmbed } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Replies to ping with pong"),
async execute(msg, args, client, interaction) {
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle("🏓 Pong!")
.setDescription(
`Latency is ${
Date.now() - msg.createdTimestamp
}ms. API Latency is ${Math.round(client.ws.ping)}ms`
)
.setTimestamp();
await interaction.reply({
embeds: [embed],
ephemeral: true,
});
},
};
I'm passing my msg parameter, so why is it that it doesn't recognize the msg.createdTimestamp within ping.js? EDIT: I've updated some of my code, updating the way the parameters are passed. Now I'm getting a TypeError: Cannot read properties of undefined (reading 'reply') error in my ping.js file.
So I figured it out. The msg portion of what I'm passing actually gets passed down to the interaction argument. Just had to change msg to interaction to get everything to work:
ping.js
const { SlashCommandBuilder } = require("#discordjs/builders");
const { MessageEmbed } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Replies to ping with pong"),
async execute(interaction, args, client) {
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle("🏓 Pong!")
.setDescription(
`Latency is ${
Date.now() - interaction.createdTimestamp
}ms. API Latency is ${Math.round(client.ws.ping)}ms`
)
.setTimestamp();
await interaction.reply({
embeds: [embed],
ephemeral: true,
});
},
};