yea hello I'm making a discord.js bot and I have this code currently and it REFUSES to send a message (it doesn't error either
let chx = db.get(`welchannel_${member.guild.id}`);
if (chx === null) {
return;
}
let data = await canva.welcome(member, { link: "https://i.pinimg.com/originals/f3/1c/39/f31c39d56512dc8fbf30f9d0fb3ee9d3.jpg" })
const attachment = new discord.MessageAttachment(
data,
"welcome-image.png"
);
client.channels.cache.get(chx).send("Welcome to our Server " + member.user.username, attachment);
});
and then i have welcome.js with this code but it aint sending and i cant figure out why ...
const db = require("quick.db")
module.exports = {
name: "setwelcome",
category: "moderation",
usage: "setwelcome <#channel>",
description: "Set the welcome channel",
run: (client, message, args) => {
let channel = message.mentions.channels.first()
if(!channel) {
return message.channel.send("Please Mention the channel first")
}
//Now we gonna use quick.db
db.set(`welchannel_${message.guild.id}`, channel.id)
message.channel.send(`Welcome Channel is set to ${channel}`)
}
}```
just a guess that your not checking for undefined on CHX
if (chx === null && chx === undefined) {
return;
}
This is my modified code from my discord bot (just to keep it general).
this.client.on('ready', () => {
if(botChannelID){
this.client.channels.fetch(botChannelID).then(ch => {
ch.send(`Welcome message here.`);
}).catch(e => {
console.error(`Error: ${e}`);
});
}
//Other stuff. Blah blah blah...
});
Related
I'm trying to make an eval command for my bot. It doesn't error, but it doesn't send a message to the console or the discord channel. Heres my eval code:
const clean = async (client, text) => {
if (text && text.constructor.name == "Promise")
text = await text;
if (typeof text !== "string")
text = require("util").inspect(text, { depth: 1 });
text = text
.replace(/`/g, "`" + String.fromCharCode(8203))
.replace(/#/g, "#" + String.fromCharCode(8203));
text = text.replaceAll(client.token, "[REDACTED]");
return text;
}
client.on("messageCreate", async (message) => {
const args = message.content.split(" ").slice(1);
if (message.content.startsWith(`${p}eval`)) {
if (message.author.id !== 821682594830614578) {
return;
}
try {
const evaled = eval(args.join(" "));
const cleaned = await clean(client, evaled);
message.channel.send(`\`\`\`js\n${cleaned}\n\`\`\``);
} catch (err) {
message.channel.send(`\`ERROR\` \`\`\`xl\n${cleaned}\n\`\`\``);
}
}
});
Let me know if I have to give you more code.
It seems like you put a number as your ID... Discord.js IDs are in strings so you should put your ID into a string.
if (message.author.id !== "821682594830614578") {
return;
}
Probably your Discord ID is wrong. Tell me your discord username, I will add you as friend and will solve it in DMs.
This is my Discord Username Nishant1500#9735
So I am trying to make my giveaway bot but can't make a create command so the person can add more details about the giveaway! Thus, I need questions but everytime I try it never goes well!
message.channel.send("Please mention the channel you want the giveaway to be in! **e.g #channel**");
try {
let msgs = await message.channel.awaitMessages(u2=>u2.author.id===message.author.id, { time: 15000, max: 1, errors: ["time"]});
if(parseInt(msgs.first().content)==mention.channel) {
const Channel = message.mentions.channels.first();
await Channel.send("HEY")
}
else {
message.channel.send("You did not mentioned a channel!");
}
}catch(e) {
return message.channel.send("Command Cancel!")
}
It either returns to the catch(e) line or "You did not mentioned a channel!"!
This should be what you want i think. (works with mentioning the channel, providing a channel ID or providing a channel name)
message.channel.send("Please mention the channel you want the giveaway to be in! **e.g #channel**");
let channel;
let response;
try {
response = await message.channel.awaitMessages(msg => msg.author.id === message.author.id, { max: 1, time: 1000*60*3, errors: ['time'] })
} catch {
return message.channel.send("Command Cancel!")
}
if (response.first().mentions.channels.first()) {
channel = response.first().mentions.channels.first()
} else if (!isNaN(response.first().content) && message.guild.channels.cache.get(response.first().content)) {
channel = message.guild.channels.cache.get(response.first().content)
} else if (isNaN(response.first().content) && message.guild.channels.cache.find(c => c.name.toLowerCase() === response.first().content.toLowerCase())) {
channel = message.guild.channels.cache.find(c => c.name.toLowerCase() === response.first().content.toLowerCase())
}
if (channel) {
await channel.send("HEY")
} else {
return message.channel.send("You did not mentioned a channel!");
}
When I'm Trying To Make My Discord Music Bot I Get An Error In Discord Not The Command Line Though, It Cannot Tell If I'm In A Voice Channel Or Not
Here's My Code
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const serverQueue = queue.get(message.guild.id);
if (message.content.startsWith(`${prefix}play`)) {
execute(message, serverQueue);
return;
} else if (message.content.startsWith(`${prefix}skip`)) {
skip(message, serverQueue);
return;
} else if (message.content.startsWith(`${prefix}stop`)) {
stop(message, serverQueue);
return;
} else {
message.channel.send('You need to enter a valid command!')
}
});
process.on('unhandledRejection', error => console.error('Uncaught Promise Rejection', error));
async function execute(message, serverQueue) {
const args = message.content.split(' ');
const voiceChannel = message.member.voiceChannel;
if (!voiceChannel) return message.channel.send('You need to be in a voice channel to play music!');
const permissions = voiceChannel.permissionsFor(message.bot.user);
if (!permissions.has('CONNECT') || !permissions.has('SPEAK')) {
return message.channel.send('I need the permissions to join and speak in your voice channel!');
}
const songInfo = await ytdl.getInfo(args[1]);
const song = {
title: songInfo.title,
url: songInfo.video_url,
};
if (!serverQueue) {
const queueContruct = {
textChannel: message.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 5,
playing: true,
};
queue.set(message.guild.id, queueContruct);
queueContruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueContruct.connection = connection;
play(message.guild, queueContruct.songs[0]);
} catch (err) {
console.log(err);
queue.delete(message.guild.id);
return message.channel.send(err);
}
} else {
serverQueue.songs.push(song);
console.log(serverQueue.songs);
return message.channel.send(`${song.title} has been added to the queue!`);
}
}
function skip(message, serverQueue) {
if (!message.member.voiceChannel) return message.channel.send('You have to be in a voice channel to stop the music!');
if (!serverQueue) return message.channel.send('There is no song that I could skip!');
serverQueue.connection.dispatcher.end();
}
function stop(message, serverQueue) {
if (!message.member.voiceChannel) return message.channel.send('You have to be in a voice channel to stop the music!');
serverQueue.songs = [];
serverQueue.connection.dispatcher.end();
}
function play(guild, song) {
const serverQueue = queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
queue.delete(guild.id);
return;
}
const dispatcher = serverQueue.connection.playStream(ytdl(song.url))
.on('end', () => {
console.log('Music ended!');
serverQueue.songs.shift();
play(guild, serverQueue.songs[0]);
})
.on('error', error => {
console.error(error);
});
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
}
I Found It On This Website https://medium.com/free-code-camp/how-to-create-a-music-bot-using-discord-js-4436f5f3f0f8
And When I Start The Code It Says I'm Not In One,
Any Type Of Feedback Would Be Greatly Appreciated!
Try this
if (!message.member.voice.channel)
return message.reply('you are not in a voice channel'),
The problem comes from the fact that you're using the GuildMember.voiceChannel property, which exists only in discord.js#v11. The v12 equivalent is GuildMember.voice.channel, you can use it like this:
// You can use this as before, since it's the same VoiceChannel element
const voiceChannel = message.member.voice.channel
I've been trying to fix a command handler for 3 hours now, but anytime I try to add a custom command nothing happens. It loads the command, but when the command is run it does nothing. Here's some code:
index.js:
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
console.log(`[LOG] Loaded command ${file}`);
client.commands.set(command.name, command);
}
commands/kick.js:
const fs = require('fs');
var moment = require('moment');
var logger = fs.createWriteStream(`./logs/${moment().format('MM-DD-YYYY')}.log`, {
flags: 'a'
});
module.exports = {
name: "kick",
category: "moderation",
description: "Kicks the mentioned user.",
usage: "<imputs>",
run: (client, message, args) => {
let reason = args.slice(1).join(' ');
let user = message.mentions.users.first();
if (message.mentions.users.size < 1) return message.reply('You must mention someone to kick them.').then(msg => { msg.delete(10000) }).catch(console.error);
if (user.id === message.author.id) return message.reply("You cannot kick yourself.").then(msg => { msg.delete(10000) });
if (user.id === client.user.id) return message.reply("You cannot kick me.").then(msg => { msg.delete(10000) });
if (!message.member.hasPermission("KICK_MEMBERS")) return message.reply("You don't have the **Kick Members** permission!").then(msg => { msg.delete(10000) });
if (reason.length < 1) reason = 'No reason supplied';
if (!message.guild.member(user).kickable) return message.reply('I could not kick that member').then(msg => { msg.delete(10000) });
message.delete();
message.guild.member(user).kick();
const embed = new Discord.RichEmbed()
.setColor(0x0000FF)
.setTimestamp()
.addField('Action:', 'Kick')
.addField('User:', `${user.username}#${user.discriminator} (${user.id})`)
.addField('Moderator:', `${message.author.username}#${message.author.discriminator}`)
.addField('Reason', reason)
.setFooter(`© NetSync by Towncraft Developers`);
let logchannel = message.guild.channels.find('name', 'logs');
if (!logchannel){
message.channel.send(`Successfully kicked ${user.username}#${user.discriminator}.`).then(msg => { msg.delete(10000) });
logger.log(`[LOG] [KICK] ${user.username}#${user.discriminator} (${user.id}) was kicked by ${message.author.username}#${message.author.discriminator}.`);
}else{
message.channel.send(`Successfully kicked ${user.username}#${user.discriminator}. I\'ve also logged the kick in <#${logchannel.id}>.`).then(msg => { msg.delete(10000) });
client.channels.get(logchannel.id).send({embed});
}
if(user.bot) return;
return message.mentions.users.first().send({embed}).catch(e =>{
if(e) return
});
}
}
Like I said, been trying to do this for 3 hours now, and I'm stumped. If someone could tell me what I did wrong that'd be awesome, thanks.
You need execute command in you main.js file on bot.on('message' block.
Like this:
client.on('message', message => {
if (message.channel.type === "dm") return;
let prefix = '!'
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
if (!message.content.startsWith(prefix)) return;
let commandfile = client.commands.get(cmd.slice(prefix.length));
if (commandfile) commandfile.run(client, message, args, botconfig);
})
I am making a discord bot for a friend and everything worked until i tried to make an unban command. when i tried to unban someone it did not work. then i looked at the error. it displayed:
TypeError: Cannot read property 'displayName' of undefined
at C:\Users\user\folder_name\commands\unban.js:37:67
at processTicksAndRejections (internal/process/task_queues.js:97:5)
Unhandled promise rejection: TypeError: Cannot read property 'displayName' of undefined
at C:\Users\user\folder_name\commands\unban.js:37:67
at processTicksAndRejections (internal/process/task_queues.js:97:5)
this is my code
const Discord = require('discord.js');
module.exports = {
name: 'unban',
description: 'unban user',
aliases: [],
cooldown: 0,
args: true,
usage: '<mention> [reason]',
guildOnly: true,
execute(message, args, client) {
console.log(message.content);
const embedMsg = new Discord.RichEmbed()
.setColor('#0000ff')
.setAuthor(message.author.username, message.author.displayAvatarURL)
.setThumbnail(message.author.displayAvatarURL)
.setTimestamp()
.setFooter('botname', client.user.displayAvatarURL);
let member = message.mentions.members.first();
if (!message.member.hasPermission('BAN_MEMBERS')) {
embedMsg.setDescription(`You don't have permission to unban!`);
return message.channel.send(embedMsg);
}
if (!args.length >= 1) {
embedMsg.setDescription('^unban takes at least one argument! the proper usage is ^unban <mention> [reason]');
message.channel.send(embedMsg);
}
if (args.length < 2) {
message.guild.unban(member).then(() => {
embedMsg.setDescription(`${member.displayName} has been succesfully unbanned`);
return message.channel.send(embedMsg);
}).catch((err) => {
embedMsg.setDescription(`Could not unban ${member.displayName}`);
console.log(err);
return message.channel.send(embedMsg);
});
return;
}
newargs = "";
for (var i = 1; i < args.length; i++) {
newargs += (args[i] + " ");
}
message.guild.unban(member).then(() => {
embedMsg.setDescription(`${member.displayName} has been succesfully unbanned for reason ${newargs}`);
return message.channel.send(embedMsg);
}).catch((err) => {
embedMsg.setDescription(`Could not unban ${member.displayName}`);
console.log(err);
return message.channel.send(embedMsg);
});
return;
}
}
does anyone know what i am doing wrong?
It says in the discord.js's official docs that the unban method returns a member object https://discord.js.org/#/docs/main/stable/class/Guild?scrollTo=unban
The reason why it says 'undefined' is because the member object you are trying to access is not in the server/guild. So, therefore you need add a reference to the member object that the method returns:
message.guild.unban('some user ID').then((member) => {
embedMsg.setDescription(`${member.username} has been succesfully unbanned for reason ${newargs}`);
return message.channel.send(embedMsg);
}
Unbun method return a user promise, so user dont have property displayName, you need use .username
And you can use user.id for unban, so right way will be let member = message.mentions.members.first() || args[0]
This check doing wrong, because its not stop code execute
if (!args.length < 2) {
embedMsg.setDescription('^unban takes at least one argument! the proper usage is ^unban <mention> [reason]');
return message.channel.send(embedMsg);
}
Amm and whats this part code doing? Why its duplicate?
if (args.length < 2) {
message.guild.unban(member)
.then(() => {
embedMsg.setDescription(`${member.username} has been succesfully unbanned`);
return message.channel.send(embedMsg);
})
.catch((err) => {
embedMsg.setDescription(`Could not unban ${member.username}`);
console.log(err);
return message.channel.send(embedMsg);
});
return;
}
The edited code
const Discord = require('discord.js');
module.exports = {
name: 'unban',
description: 'unban user',
aliases: [],
cooldown: 0,
args: true,
usage: '<mention> [reason]',
guildOnly: true,
execute(message, args, client) {
const embedMsg = new Discord.RichEmbed()
.setColor('#0000ff')
.setAuthor(message.author.username, message.author.displayAvatarURL)
.setThumbnail(message.author.displayAvatarURL)
.setTimestamp()
.setFooter('botname', client.user.displayAvatarURL);
let member = message.mentions.members.first() || args[0]
if (!message.member.hasPermission('BAN_MEMBERS')) {
embedMsg.setDescription(`You don't have permission to unban!`);
return message.channel.send(embedMsg);
}
if (!args.length < 2) {
embedMsg.setDescription('^unban takes at least one argument! the proper usage is ^unban <mention> [reason]');
return message.channel.send(embedMsg);
}
let newargs = args.splice(1,args.length).join(' ')
message.guild.unban(member)
.then(() => {
embedMsg.setDescription(`${member.username} has been succesfully unbanned for reason ${newargs}`);
return message.channel.send(embedMsg);
})
.catch((err) => {
embedMsg.setDescription(`Could not unban ${member.username}`);
console.log(err);
return message.channel.send(embedMsg);
});
}
}