Discord bot always erroring with: "SyntaxError: Missing catch or finally after try." - discord.js

So I'm making a Discord bot, and I'm FINALLY getting to the music aspect. The only problem is, EVERY time I run the bot, it always ends up throwing this error, and I have no idea why... SyntaxError: Missing catch or finally after try.
if(message.content==='!play') {
if(!message.member.voice.channel) {
message.reply('❌ Please join a voice channel before executing this command!');
return;
};
const Connection = joinVoiceChannel({
channelId: '' // Removed for security, but this isn't the issue.,
guildId: message.channel.guild.id,
adapterCreator: message.channel.guild.voiceAdapterCreator,
});
Connection.on(VoiceConnectionStatus.Ready, () => {
const stream = ytdl('https://www.youtube.com/watch?v=d0AAECyXT0Y', { filter : 'audioonly' });
const player = createAudioPlayer();
const resource = createAudioResource(stream);
player.play(resource);
});
Connection.on(AudioPlayerStatus.Idle, () => {
Connection.destroy();
});
};
Any help is appreciated!

Related

Number Type Schema not updating

I'm trying to make a bot that let's you give fame points to users as well as currency, currency works just fine and it updates whenever someone sends a message with a 1 minute cooldown. however I'm having problems with my fame schema. the bot creates a new schema if there's not an already existing one without problem and it also displays the amount correctly, however, when you click the button to give someone a Fame point, it doesn't, it stays at 0. I'm probably missing something simple but I can't seem to find it, here's the code:
const { MessageEmbed,ButtonInteraction} = require('discord.js');
const Fame = require('../../schemas/fame');
module.exports = {
data: {
name: `yes-fame`
},
async execute (interaction, client) {
const user = require('../../commands/entertainment/givefame')
const fameProfile = await client.createFame(user)
try {
await Fame.findOneAndUpdate({ _id: fameProfile._id}, { $inc: { amount: 1 } });
} catch (error) {
console.log(error);
}
const userEmbed = new MessageEmbed()
.setTitle(`<:fame:952026535756435536> Fame Point Given`)
.setDescription(`${interaction.user} has given 1 fame point to ${user} `)
.setTimestamp()
.setColor("#00FF00")
.setFooter(client.user.tag, client.user.displayAvatarURL());
await interaction.reply({ embeds: [userEmbed]});
}
};
(the cooldown is low because I'm not entirely sure how long to make it yet)
Here is the code for the Fame Schema.
const mongoose = require('mongoose');
const fameSchema = new mongoose.Schema ({
_id: mongoose.Schema.Types.ObjectId,
guildId: String,
memberId: String,
amount: { type: Number, default: 0}
});
module.exports = mongoose.model('Fame', fameSchema, 'fame-points');
and here's the code for the const "user", it's either the user mentioned or if none, the one using the slash command.
const user = interaction.options.getUser("user") || interaction.user;
And here's the createFame function
const Fame = require('../schemas/fame');
const mongoose = require('mongoose');
module.exports = (client) => {
client.createFame = async (member) => {
let fameProfile = await Fame.findOne({ memberId: member.id, guildId: member.guild.id });
if (fameProfile) {
return fameProfile;
} else {
fameProfile = await new Fame({
_id: mongoose.Types.ObjectId(),
guildId: member.guild.id,
memberId: member.id,
});
await fameProfile.save().catch(err => console.log(err));
return fameProfile;
}
};
};
I thought that maybe there was an error in the user const itself or when importing it but I made the bot send a test message using that const and it is getting the user no problem so idk what's wrong.
it shows the error:
TypeError: Cannot read properties of undefined (reading 'id')
at Client.client.createFame (C:\Users\xxx\OneDrive\desktop\bot\src\functions\createFame.js:6:89)
at Object.execute (C:\Users\xxx\OneDrive\desktop\bot\src\buttons\info\yes-fame.js:10:46)
at Object.execute (C:\Users\xxx\OneDrive\desktop\bot\src\events\interactionCreate.js:25:26)
at Client. (C:\Users\xxx\OneDrive\desktop\bot\src\functions\handleEvents.js:8:58)
There is a $inc property/method/wtv in mongoose model. Try this-
await Fame.findOneAndUpdate({ _id: fameProfile._id}, { $inc: { amount: 1 } });

TypeError: Cannot read properties of null (reading 'id')

So I was updating my bot to discord.js v13 and apparently my logging system has now broke, for some reason it can't read the ID of the guild where this log is occurring.
banAdd.js
const { MessageEmbed} = require("discord.js");
const {red_light} = require("../../other/colors.json");
const Channel = require('../../models/ModerationModel.js');
module.exports = async (bot, guild, user) => {
const guildDB = await Channel.findOne({
guildId: guild.id
}, async (err, guild) => {
if(err) console.error(err)
if (!guild) {
const newGuild = new Channel({
guildId: guild.id,
modChannel: null,
msgChannel: null
});
await newGuild.save().then(result => console.log(result)).catch(err => console.error(err));
}
});
const modChannel = guild.channels.cache.get(guildDB.modChannel);
if (!modChannel) {
return console.log(`No message channel found`);
}
let mEmbed = new MessageEmbed()
.setAuthor(`Member Unbanned`, user.displayAvatarURL({dynamic : true}))
.setColor(red_light)
.setDescription(`${user} ${user.tag}`)
.setThumbnail(`${user.displayAvatarURL({dynamic : true})}`)
.setFooter(`ID: ${user.id}`)
.setTimestamp()
modChannel.send({embeds:[mEmbed]});
}
Error
/home/runner/switch-beta-test/events/guild/banRemove.js:13
guildId: guild.id,
^
TypeError: Cannot read properties of null (reading 'id')
at /home/runner/switch-beta-test/events/guild/banRemove.js:13:27
at /home/runner/switch-beta-test/node_modules/mongoose/lib/model.js:5074:18
at processTicksAndRejections (node:internal/process/task_queues:78:11)
I have no idea why this is not working as it works in previous versions but updating to discord.js V13 completely broke this system. I tried looking at any possible solution but I can't find a single solution.
The cause of this error was because guild can no longer be defined during a users ban or unban, guild and user should be replaced with ban in both the unban and ban logs.
CODE
const { MessageEmbed} = require("discord.js");
const {red_light} = require("../../other/colors.json");
const Channel = require('../../models/ModerationModel.js');
module.exports = async (bot, ban) => {
const guildDB = await Channel.findOne({
guildId: ban.guild.id
}, async (err, guild) => {
if(err) console.error(err)
if (!guild) {
const newGuild = new Channel({
guildId: ban.guild.id,
modChannel: null,
msgChannel: null
});
await newGuild.save().then(result => console.log(result)).catch(err => console.error(err));
}
});
const modChannel = ban.guild.channels.cache.get(guildDB.modChannel);
if (!modChannel) {
return console.log(`No message channel found`);
}
let mEmbed = new MessageEmbed()
.setAuthor(`Member Unbanned`, ban.user.displayAvatarURL({dynamic : true}))
.setColor(red_light)
.setDescription(`${ban.user} ${ban.user.tag}`)
.setThumbnail(`${ban.user.displayAvatarURL({dynamic : true})}`)
.setFooter(`ID: ${ban.user.id}`)
.setTimestamp()
modChannel.send({embeds:[mEmbed]});
}
After this the error should no longer show.
The error says that the guild variable is empty doesn't have a value null and when you do guild.id you're trying to access a property that don't exist
Make sure that the guild variable is assigned to a value
Probably they add some changes to the new version of npm package go check the docs

Discord.js 13 channel.join is not a function

I recently installed Discord.js 13.1.0 and my music commands broke because, apparently, channel.join(); is not a function, although I have been using it for months on 12.5.3...
Does anybody know a fix for this?
Some parts of my join command:
const { channel } = message.member.voice;
const voiceChannel = message.member.voice.channel;
await channel.join();
It results in the error.
Discord.js no longer supports voice. You need to use the other package they made (#discordjs/voice). You can import joinVoiceChannel from there.
//discord.js and client declaration
const { joinVoiceChannel } = require('#discordjs/voice');
client.on('messageCreate', message => {
if(message.content === '!join') {
joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
})
}
})

How to transfer reaction to original message, discord.js

I am trying to make a suggestion feature for one of my bots. I have searched online but nothing really helps with it. The suggestion part is working but I want to add a feature where if i react to the message in the log channel it sends the reaction to the original message. Here is my code:
bot.on('message', message => {
if (message.content.startsWith("/suggest")){
message.reply(`Your response has been recorded.`)
var yes = message.content
const channel1 = bot.channels.cache.get('722590953017442335');
channel1.send(`${message.author} suggests: ${yes.slice(9)}`)
if (chanell1.reaction.emoji.name === '✅'){
const channel2 = bot.channels.cache.get('722595812462297139');
channell2.react.author.message('✅')
}
}
})
I am using v12 of node.
You can use the awaitReactions() function:
bot.on("message", (message) => {
if (message.content.startsWith("/suggest")) {
message.reply(`Your response has been recorded.`);
var yes = message.content;
bot.channels.cache
.get("722590953017442335")
.send(`${message.author} suggests: ${yes.slice(9)}`)
.then(async (msg) => {
msg
.awaitReactions((reaction) => reaction.emoji.name === "✅", {
time: 15000,
})
.then((collected) => message.react("✅"))
.catch(console.error);
});
}
});
Please read the official documentation at https://discord.js.org/#/docs/main/v12/general/welcome for v12 help. You ought to use the Client#messageReactionAdd event to track reactions - your code isn't too far off, however it is missing that key event. Please note that to track reactions you'll need persistent storage if you want the reactions to work after restart. Alternatively, you could try awaiting the reactions or using a reaction collector if only short term.
Try this instead:
const { Client } = require('discord.js');
const bot = new Client({ partials: ['REACTION', 'USER'] });
const prefix = '/';
const suggestionsCache = {};
bot.on('message', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.split(' '),
command = args.shift().slice(prefix.length);
if (command == 'suggest') {
const suggestion = args.join(' '),
suggestionMessage = `${message.author} suggests: ${suggestion}`,
suggestionChannel = bot.channels.cache.get('722590953017442335'),
logChannel = bot.channels.cache.get('722595812462297139');
if (!suggestionChannel || !logChannel) return message.reply('Oops! Something went wrong.');
try {
const suggestionMessage = await suggestionChannel.send(suggestionMessage);
const logMessage = await logChannel.send(suggestionMessage);
suggestionsCache[logMessage.id] = suggestionMessage.id; // Save the ID for later.
message.reply('Your response has been recorded.');
} catch {
message.reply('Oops! Something went wrong.');
};
};
});
bot.on('messageReactionAdd', async (reaction, user) => {
if (reaction.partial) {
try {
await reaction.fetch();
} catch {}
}
const messageID = suggestionsCache[reaction.message.id];
if (!messageID || reaction.emoji.name !== '✅') return; // If not found in cache, ignore and if the emoji isn't the check, ignore it.
try {
const channel = await client.channels.fetch('722590953017442335');
if (!channel) return;
const message = channel.messages.fetch(messageID);
if (!message) return; // Message deleted.
message.react('✅');
} catch {
return;
};
});
Please note that I am new to v12 and normally use v11! The code above is not tested and may contain bugs as a result. Please feel free to edit/update the code.

How can a Discord bot reply to only certain users?

I am looking for a way to make a Discord bot which either reacts or replies to only certain users. It can choose the user by either role or ID, but I can not seem to get it working. This is what I have tried:
if (message.author.id === 'myDiscordID') {
message.reply('hello!').then(r => {
});
}
I am coding in Discord JS, if that helps. This is the entire index.js file:
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
if (message.author.id === 'myDiscordID') {
message.reply('hello!').then(r => {
});
}
});
client.login(token);
The file runs fine, the bot comes online, and then it prints 'Ready!' to the console, however, the rest of the code doesn't seem to work.
I`ts look like this must work.
Are you sure bot in your server and have permissions to read message ?
Try this ready block
client.once('ready', () => {
console.log('Ready!');
const guildList = client.guilds.cache.map(guild => guild.name)
console.join(`Bot go online in ${guildList.length}`)
console.log(guildList.join('\n'))
});
And some solutin to check user.id or roles includes:
console.log(message.content) for check is this event triggeret.
client.on('message', message => {
console.log(message.content)
if (message.author.id === '') {
message.reply('author contain')
}
if (message.member.roles.cache.has('ROLE ID')) {
message.reply('role contain')
}
if(message.member.roles.cache.some(role => ['ID1', 'ID2'].includes(role.id)) {
message.reply('some role contain')
}
});
I was also having a problem with that. Here is the solution that worked for me.
const userID = "The_user's_id";
bot.on("message", function(message) {
if(message.author.id === userID) {
message.react('emoji name or id');
}
});
Note: to find the id of a user, just right click him and press "copy ID".

Resources