When I use the -play command,I get an "Uncaught SyntaxError SyntaxError" [duplicate] - javascript

This question already has an answer here:
Discord.js v12 code breaks when upgrading to v13
(1 answer)
Closed 11 months ago.
I'm trying to make a discord music bot and when I use the -play command which is the only one I've created so far it gives me this error is console
"(node:20336) DeprecationWarning: The message event is deprecated. Use messageCreate instead
(Use `node --trace-deprecation ...` to show where the warning was created)"
which when I do, I get this
Uncaught SyntaxError SyntaxError: Unexpected identifier
at (program) (<eval>/VM46947595:1:8)
as a result, I am very confused
also here's the code
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const { Message } = require('discord.js');
const queue = new Map();
modulue.exports = {
name: 'play',
aliases:['skip', 'stop', 'pause', 'resume'],
cooldown: 0,
description: 'dat jazz baby',
async execute(Message, args, cmd, client, Discord){
const voice_channel = Message.member.voice.channel;
if (!voice_channel) return message.channel.send('you ain\'t in a voice channel dummy');
const permissions = voice_channel.permissionsFor(Message.client.user);
if (!permissions.has('CONNECT') || !permissions.has('SPEAK')) return message.channel.send('can\'t talk');
const server_queue = queue.get(Message.guild.id);
if (Message.content === prefix + play){
if (!args.length) return message.channel.send('no args. You keep this up and Mark Zukerberg could die of ligma');
let song = {};
if (ytdl.validateURL(args[0])){
const song_info = await ytdl.getInfo(args[0]);
song = {title: song_info.videoDetails.title, url: song_info.videoDetails.video_url};
} else {
const video_finder = async (query) => {
const videoresult = await ytSearch(query);
return (videoresult.videos.length > 0) ? videoresult.videos[0] : null;
}
const song_info = await video_finder(args.join(' '));
if (video){
song = title; video.title, url; video.url }
else {
return Message.channel.send('damn so no maidens or vidjas');
}
}
if (!server_queue){
const queue_constructor = {
textChannel: message.channel,
voiceChannel: voice_channel,
connection: null,
songs: [],
}
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push.push(song)
try {
const connection = await voice_channel.join();
queue_constructor.connection = connection;
play(message.guild, queue_constructor.songs[0]);
} catch (err) {
console.log(err);
queue.delete(message.guild.id);
return message.channel.send(err);
message.channel.send('I fell and I can\'t get up\(try again\)');
throw err; // this will throw the error to the console
}
} else {
server_queue.song.push(song);
return message.channel.send(`${song.title} has been added to the queue`);
}
}
}
}
const video_player = async (guild, song) => {
const server_queue = queue.get(guild.id);
if (!song) {
server_queue.voiceChannel.leave();
queue.delete(guild.id);
return;
}
const stream = ytdl(song.url, {filter: 'audioonly'});
song_queue.connection.play(stream, { Seek: 0, volume: 0.5})
.on(finish, () => {
server_queue.songs.shift();
video_player(guild, server_queue.songs[0]);
})
}
I didn't exactly expect it to work, but seeing as I'm pretty new to coding I'm kinda helpless

The error shown in your message is not an error, it's a module DeprecationError. I'm pretty sure that's not causing the problem. The real error is the SyntaxError.
Is your code in Typescript (TS)?
(ytdl-core is a node js dependency, so you have to use require unless you are using TS)

Related

voiceChannel.join() isn't a function node v16 discord.js

I made a bot that plays music. I upgraded to NodeJS v16.6.1 and voiceChannel.join doesn't work anymore.
I already tried using const { voiceChannel } = require('#discord.js/voice'); but it just says module not found.
Code:
const ytdl = require("ytdl-core");
const ytSearch = require("yt-search");
module.exports = {
name: 'play',
description: 'Joins and plays a video from youtube',
async execute(message, args) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('You need to be in a channel to execute this command');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the neccesary permissions');
if (!permissions.has("SPEAK")) return message.channel.send('You dont have the neccesary permissions');
if (!args.length) return message.channel.send('Define Video');
const connection = await voiceChannel.join();
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await videoFinder(args.join(' '));
if (video) {
const stream = ytdl(video.url, {
filter: 'audioonly'
});
connection.play(stream, {
seek: 0,
volume: 1
})
.on('finish', () => {
voiceChannel.leave();
});
await message.reply(`Now Playing **${video.title}**`)
} else {
message.channel.send('No videos found');
}
}
}```
As the error says, voiceChannel#join is not, in fact, a function. While it did exist on Discord.js v12, which I assume you were using before updating your Node.js version, note that it is nowhere to be found in the Discord.js v13 documentation on VoiceChannel. Instead, you are to migrate to #discordjs/voice, whose joinVoiceChannel function can be used as a replacement.

Why do I get the error 'Invalid interaction application command' when I use this Slash command in discord.js?

When I try do use this slash command it says 'Invalid interaction application command'. How do I fix this? I can show more code if needed.
const Command = require('../structures/command.js');
const config = require('../data/config.json');
const { MessageEmbed } = require('discord.js');
const Discord = require('discord.js');
module.exports = new Command({
name: "ping",
description: "Shows the ping of the bot.",
type: "BOTH",
slashCommandOptions: [],
permission: "ADMINISTRATOR",
async run(message, args, client) {
if (message.author.id === config.dev) {
// const pingEmbed = new MessageEmbed()
// .setTitle(`Bot Ping: ${client.ws.ping} ms`)
// .setAuthor('System')
// // .setFooter(`${client.ws.ping} ms`)
// .setColor('5FA6E0')
const m = await message.reply(`Bot Ping: ${client.ws.ping} ms`);
const msg = message instanceof Discord.CommandInteraction ? await message.fetchReply() : m;
msg.edit(`Ping: ${client.ws.ping} ms\nMessage Ping: ${msg.createdTimestamp - message.createdTimestamp} ms`);
} else {
message.reply(`Must be a developer to use the command [${this.name}]`);
}
}
});

Discord.js i make a warn command that write a file using FS

So when i warn a user it works perfectly, but when i try to warn again a person it replace the old string (the reason) but i want to make it add and keep the old string. (the reason) i tryed many things but still, fs is replacing automaticaly the old string (the reason).
And there is my javascript code :
const Discord = require("discord.js")
const fs = require("fs");
module.exports = {
name: "warn",
description: "Warn command",
async execute( message){
let config = require("../config.json")
let lang = JSON.parse(fs.readFileSync("./langs.json", "utf8"));
if(!lang[message.guild.id]){
lang[message.guild.id] = {
lang: config.lang
};
}
let correct1 = lang[message.guild.id].lang;
const ping = require(`../lang/${correct1}/warn.json`)
const response = ping
const messageArray = message.content.split(' ');
const args = messageArray.slice(1);
let sEmbed1 = new Discord.MessageEmbed()
.setColor("#FF0000")
.setTitle("Permission refused.")
.setDescription("<:dont:803357503412502588> | You don't have the permission for this command. (`MANAGE_ROLES`)");
if(!message.member.hasPermission("MANAGE_ROLES")) return message.reply(sEmbed1)
const user = message.mentions.users.first()
if(!user) {
return message.channel.send("<:dont:803357503412502588> | You need to mention a user.")
}
if(message.mentions.users.first().bot) {
return message.channel.send("<:dont:803357503412502588> | You can't warn a bot")
}
if(message.author.id === user.id) {
return message.channel.send("<:dont:803357503412502588> | You can't warn yourself!")
}
const reason = args.slice(1).join(" ")
if(!reason) {
return message.channel.send("<:dont:803357503412502588> | You need a reason")
}
const warnings = {
reason: `${reason}`,
guild_id: `${message.guild.id}`,
user_id: `${user.id}`,
moderator: `${message.author.username}`
}
const jsonString = JSON.stringify(warnings)
fs.writeFile('./warnings.json', jsonString, err => {
if (err) {
console.log('Error writing file', err)
} else {
console.log('Successfully wrote file')
}
})
}
}
const jsonString = JSON.stringify(warnings)
fs.writeFile('./warnings.json', jsonString, err => {
if (err) {
console.log('Error writing file', err)
} else {
console.log('Successfully wrote file')
}
})
Could you replace line 2 with fs.writeFileSync("./warnings.json", jsonString, {'flags': 'a'}, err => {

TypeError: message.client.commands.get(...).execute is not a function

module.exports = {
name: 'search',
aliases: ['search'],
description: 'Search and select videos to play.',
run: async (client, message, args) => {
if (!args.length)
return message.reply(`Usage: ${message.client.prefix}${module.exports.name} <Video Name>`).catch(console.error);
if (message.channel.activeCollector)
return message.reply("A message collector is already active in this channel.");
if (!message.member.voice.channel)
return message.reply("You need to join a voice channel first!").catch(console.error);
const search = args.join(" ");
let resultsEmbed = new MessageEmbed()
.setTitle(`**Reply with the song number you want to play**`)
.setDescription(`Results for: ${search}`)
.setColor(COLORS.DARK_RED);
try {
const results = await youtube.searchVideos(search, 20);
results.map((video, index) => resultsEmbed.addField(video.shortURL, `${index + 1}. ${video.title}`));
var resultsMessage = await message.channel.send(resultsEmbed);
function filter(msg) {
const pattern = /(^[1-9][0-9]{0,1}$)/g;
return pattern.test(msg.content) && parseInt(msg.content.match(pattern)[0]) <= 20;
}
message.channel.activeCollector = true;
const response = await message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ["time"]
});
const choice = resultsEmbed.fields[parseInt(response.first()) - 1].name;
message.channel.activeCollector = false;
message.client.commands.get("play").execute(message, [choice]);
resultsMessage.delete().catch(console.error);
} catch (error) {
console.error(error);
message.channel.activeCollector = false;
}
}
};
I have a problem with my code, when I run the code it throws me an embed with the song list, but when I choose the song, I get an error TypeError: message.client.commands.get(...).execute is not a function on line 49
Que debo de hacer para corregir?
Did you mean to get the bot client instead of the client who sent the message?
Try changing
message.client.commands.get("play").execute(message, [choice]);
// to
client.commands.get("play").execute(message, [choice]);
You are assuming that "play" exists.
Perhaps you should check if play doesn't exist, handle that scenario.
if (message.client.commands.get("play") === undefined){
... do some logic
}

Working on a Discord bot with discord.js, tempmute won't work

making a discord bot in javascript with visual studio code but for some reason getting an error. I'll show you the code that is relevant first.
Overall trying to get a temporary mute function to work and I want to add it to the available commands which pops up when you hit !help. Table looks like this:
!help
classes I'm working with
Here is the index.js:
const { Client, Collection } = require("discord.js");
const { config } = require("dotenv");
const fs = require("fs");
const client = new Client({
disableEveryone: true
});
client.commands = new Collection();
client.aliases = new Collection();
client.categories = fs.readdirSync("./commands/");
config({
path: __dirname + "/.env"
});
["command"].forEach(handler => {
require(`./handlers/${handler}`)(client);
});
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
client.user.setPresence({
status: "online",
game: {
name: "you get boosted❤️",
type: "Watching"
}
});
});
client.on("message", async message => {
const prefix = "!";
if (message.author.bot) return;
if (!message.guild) return;
if (!message.content.startsWith(prefix)) return;
if (!message.member) message.member = await message.guild.fetchMember(message);
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command = client.commands.get(cmd);
if (!command) command = client.commands.get(client.aliases.get(cmd));
if (command)
command.run(client, message, args);
});
client.login(process.env.TOKEN);
Here is tempmute:
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'mute':
var person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]));
if(!person) return message.reply("I CANT FIND THE USER " + person)
let mainrole = message.guild.roles.find(role => role.name === "Newbie");
let role = message.guild.roles.find(role => role.name === "mute");
if(!role) return message.reply("Couldn't find the mute role.")
let time = args[2];
if(!time){
return message.reply("You didnt specify a time!");
}
person.removeRole(mainrole.id)
person.addRole(role.id);
message.channel.send(`#${person.user.tag} has now been muted for ${ms(ms(time))}`)
setTimeout(function(){
person.addRole(mainrole.id)
person.removeRole(role.id);
console.log(role.id)
message.channel.send(`#${person.user.tag} has been unmuted.`)
}, ms(time));
break;
}
});
Here is the help.js which lists all commands
const { RichEmbed } = require("discord.js");
const { stripIndents } = require("common-tags");
module.exports = {
name: "help",
aliases: ["h"],
category: "info",
description: "Returns all commands, or one specific command info",
usage: "[command | alias]",
run: async (client, message, args) => {
if (args[0]) {
return getCMD(client, message, args[0]);
} else {
return getAll(client, message);
}
}
}
function getAll(client, message) {
const embed = new RichEmbed()
.setColor("RANDOM")
const commands = (category) => {
return client.commands
.filter(cmd => cmd.category === category)
.map(cmd => `- \`${cmd.name}\``)
.join("\n");
}
const info = client.categories
.map(cat => stripIndents`**${cat[0].toUpperCase() + cat.slice(1)}** \n${commands(cat)}`)
.reduce((string, category) => string + "\n" + category);
return message.channel.send(embed.setDescription(info));
}
function getCMD(client, message, input) {
const embed = new RichEmbed()
const cmd = client.commands.get(input.toLowerCase()) || client.commands.get(client.aliases.get(input.toLowerCase()));
let info = `No information found for command **${input.toLowerCase()}**`;
if (!cmd) {
return message.channel.send(embed.setColor("RED").setDescription(info));
}
if (cmd.name) info = `**Command name**: ${cmd.name}`;
if (cmd.aliases) info += `\n**Aliases**: ${cmd.aliases.map(a => `\`${a}\``).join(", ")}`;
if (cmd.description) info += `\n**Description**: ${cmd.description}`;
if (cmd.usage) {
info += `\n**Usage**: ${cmd.usage}`;
embed.setFooter(`Syntax: <> = required, [] = optional`);
}
return message.channel.send(embed.setColor("GREEN").setDescription(info));
}
ERROR:
Error message, bot not defined.
Overall trying to get a temporary mute function to work and I want to add it to the available commands which pops up when you hit !help. Table looks like this:
!help
I think the tempmute simply doesn't work because you use bot.on() instead of client.on(), which was defined in the index.js. I can't help you for the rest but everything is maybe related to this.

Categories

Resources