I have a few commands that follow this same code, just some things changed, the code is for -dog command, which works fine within moderation (not spamming the command, maybe running it every 5 seconds) but when it does get spammed it will often spit a odd error into the terminal, I was wondering if there is anyway to fix this or improve it. Thanks!
Language: Discord.js V12
const Discord = require('discord.js');
const url = 'https://www.reddit.com/r/lookatmydog/hot/.json?limit=100'
module.exports = {
name: 'dog',
description: 'sends a dog!',
execute(message, args) {
https.get(url, (result) => {
var body = ''
result.on('data', (chunk) => {
body += chunk
})
result.on('end', () => {
var response = JSON.parse(body)
var index = response.data.children[Math.floor(Math.random() * 99) + 1].data
if (index.post_hint !== 'image') {
var text = index.selftext
const textembed = new Discord.MessageEmbed()
.setTitle(subRedditName)
.setColor('RANDOM')
.setDescription(`[${title}](${link})\n\n${text}`)
.setURL(`https://reddit.com/${subRedditName}`)
message.channel.send(textembed)
}
var image = index.preview.images[0].source.url.replace('&', '&')
var link = 'https://reddit.com' + index.permalink
var subRedditName = index.subreddit_name_prefixed
if (index.post_hint !== 'image') {
const textembed = new Discord.RichEmbed()
.setTitle(subRedditName)
.setColor('RANDOM')
.setDescription(`[${title}](${link})\n\n${text}`)
.setURL(`https://reddit.com/${subRedditName}`)
message.channel.send(textembed)
}
console.log(image);
const imageembed = new Discord.MessageEmbed()
.setTitle('Here is a dog, how nice!')
.setImage(image)
.setColor('RANDOM')
message.channel.send(imageembed)
}).on('error', function (e) {
console.log('Got an error: ', e)
})
})
},
}```
The error I got writing this was:
```C:\Users\-\Desktop\Corn Flakes\commands\Fun\dog.js:26
.setDescription(`[${title}](${link})\n\n${text}`)
^
ReferenceError: title is not defined
at IncomingMessage.<anonymous> (C:\Users\manof\Desktop\Corn Flakes\commands\Fun\dog.js:26:45)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (internal/streams/readable.js:1327:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)```
Related
This probably has a very simple fix, but I'm a very beginner programmer so I have no clue what to do. I am trying to delete an embed after 5 seconds, and the error is saying "msg.delete is not a function" This is my code. (I am using slash commands).
const { SlashCommandBuilder, ActionRowBuilder, ButtonBuilder, EmbedBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('br')
.setDescription('Battle to the death with your friends'),
async execute(message) {
const row = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId('joinbutton')
.setLabel('JOIN BATTLE ROYALE')
.setStyle(1),
);
var embed = new EmbedBuilder()
.setTitle(`BATTLE ROYALE STARTING`)
.setColor("0090FF")
.setDescription(`<#${message.user.id}> is starting a battle royale match. Use the button below to join!`)
.setFooter({text: message.user.username, iconURL: message.user.avatarURL()})
.setTimestamp()
message.reply({ embeds: [embed], components: [row] }).then(msg => msg.delete({timeout: 5000}))
},
};
I also have code in my index.js which I don't think could be the problem but I'm just gonna send it anyway.
var brdb = require('./models/br')
if(interaction.isButton())
{
if(interaction.customId == 'joinbutton')
{
var data = {
userid: interaction.user.id,
hp: 100
}
console.log(data)
}
}
This is because "message" is a CommandInteraction, not a Message. You should instead use message.deleteReply() as mentioned in the docs.
Here's the code currently that i'm using
it logs the picture in the console but not on the embed itself but it doesn't actually put the image from the log itself to the embed is there anything that i can do to change it?
i want it to keep it as an embed
} else if (message.content.startsWith('"meme')) {
https.get(url, (result) => {
var body = ''
result.on('data', (chunk) => {
body += chunk
})
result.on('end', () => {
var response = JSON.parse(body)
var index = response.data.children[Math.floor(Math.random() * 99) + 1].data
if (index.post_hint !== 'image') {
var text = index.selftext
const textembed = new Discord.MessageEmbed()
.setTitle(subRedditName)
.setColor(9384170)
.setDescription(`[${title}](${link})\n\n${text}`)
.setURL(`https://reddit.com/${subRedditName}`)
message.channel.send(textembed)
}
var image = index.preview.images[0].source.url
var title = index.title
var link = 'https://reddit.com' + index.permalink
var subRedditName = index.subreddit_name_prefixed
if (index.post_hint !== 'image') {
const textembed = new Discord.RichEmbed()
.setTitle(subRedditName)
.setColor(9384170)
.setDescription(`[${title}](${link})\n\n${text}`)
.setURL(`https://reddit.com/${subRedditName}`)
message.channel.send(textembed)
}
console.log(image);
const imageembed = new Discord.MessageEmbed()
.setTitle(subRedditName)
.setImage(image)
.setColor(9384170)
.setDescription(`[${title}](${link})`)
.setURL(`https://reddit.com/${subRedditName}`)
message.channel.send(imageembed)
}).on('error', function (e) {
console.log('Got an error: ', e)
})
})
return;
The preview image url returns 403 forbidden for some reason. To get the real image url use this:
var image = index.url;
Then it should work. I use it my discord.js reddit bot and it works pretty well.
I am working on a music and I would like to know how to add a queue system to the command; I have been looking around for hours and not been able to find anything on it,
If anyone can help that would be great and I don't need a queue command but I do need to add a queue system so it would really help I will be checking back in an hour to see if anyone has given me or an idea or the answer to my problem
This is my code so far:
const Discord = require('discord.js');
const ytdl = require('ytdl-core');
const YoutubeSearcher = new QuickYtSearch({
YtApiKey: '',
});
module.exports={
name: 'play',
category: 'music',
description: 'Joins and plays the song',
aliases: ['p'],
usage: '.play <song name or URL>',
run: async(client, message, args)=>{
try{
if (message.member.voice.channel) {
let args = message.content.split(' ').slice(1).join(' ');
if (!args) {
const error = new Discord.MessageEmbed()
.setTitle(`🔴 Looks like there is an Issue!`)
.setColor(0x2f3136)
.setDescription(`You have to provide me at least, the name or the url.\n\nExample :
\`\`\`fix
.play <url>
OR
.play <name>\`\`\``)
return message.channel.send(error);
};
message.member.voice.channel.join()
.then(connection => {
if (YoutubeSearcher.isVideoUrl(args) === false) {
YoutubeSearcher.getVideo(args).then(video => {
const volume = { volume: 10 };
const dispatcher = connection.play(ytdl(video.url, { filter: 'audioonly' }, volume));
const play1 = new Discord.MessageEmbed()
.setTitle('Song info')
.setURL(video.url)
.setDescription(`Name: ${video.title}, By: ${video.channelTitle}`)
.setThumbnail(video.highThumbnail)
message.channel.send(play1);
dispatcher.on("finish", () => {
dispatcher.end();
message.reply('End of the song.');
message.member.guild.me.voice.channel.leave();
});
});
} else {
const volume = { volume: 10 };
const dispatcher = connection.play(ytdl(args, { filter: 'audioonly' }, volume));
message.reply('Now playing ' + args);
dispatcher.on("finish", () => {
dispatcher.end();
message.reply('End of the song.')
message.member.guild.me.voice.channel.leave();
});
};
});
} else {
message.reply('You need to join a voice channel.');
};
}catch(err) {
console.log(err)
return message.channel.send(`Error: ${err.message}`)
}
}
}
In theory you could use the queue data structure (the last element is taken out and when a new one is added it is added to the start) and in the queue hold the music that is requested to be played. This is how it might roughly look like:
client.on("message", (msg) => {
var arrOfMusic = [];
if(msg.content.startsWith("!queue")){
msg.channel.send(arrOfMusic.join(" , ")
}
if(msg.content.startsWith("!play")){
arrOfMusic.push(msg.content.slice(6))
// you don't need to play the music
}
// your code to play the end of the array all you do is play the last element you also //need to check once it is over and use pop to remove last element
if(msg.content.startsWith("clear")){
arrOfMusic = []
}
})
Here is my entire code for my ban command. Good to note I am using Discord.JS Commando as well I have been struggling with this error but literally cannot figure out why I am getting it everything looks fine unless I have used a deprecated function. Would really appreciate someone to help me on this one I've been getting along quite well creating a rich featured bot before this happened.
const { Command } = require('discord.js-commando');
const { MessageEmbed } = require('discord.js');
const db = require('quick.db');
module.exports = class banCommand extends Command {
constructor(client) {
super(client, {
name: 'ban',
memberName: "ban",
group: 'moderation',
guildOnly: true,
userPermissions: ['BAN_MEMBERS'],
description: 'Bans the mentioned user from the server with additional modlog info.'
});
}
async run(message, args) {
if (!args[0]) return message.channel.send('**Please Provide A User To Ban!**')
let banMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.members.cache.find(ro => ro.displayName.toLowerCase() === args[0].toLocaleLowerCase());
if (!banMember) return message.channel.send('**User Is Not In The Guild**');
if (banMember === message.member) return message.channel.send('**You Cannot Ban Yourself**')
var reason = args.slice(1).join(' ');
if (!banMember.bannable) return message.channel.send('**Cant Kick That User**')
banMember.send(`**Hello, You Have Been Banned From ${message.guild.name} for - ${reason || 'No Reason'}**`).then(() =>
message.guild.members.ban(banMember, { days: 7, reason: reason })).catch(() => null)
message.guild.members.ban(banMember, { days: 7, reason: reason })
if (reason) {
var sembed = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned for ${reason}`)
message.channel.send(sembed)
} else {
var sembed2 = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned`)
message.channel.send(sembed2)
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (channel == null) return;
if (!channel) return;
const embed = new MessageEmbed()
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.setColor('#ff0000')
.setThumbnail(banMember.user.displayAvatarURL({ dynamic: true }))
.setFooter(message.guild.name, message.guild.iconURL())
.addField('**Moderation**', 'ban')
.addField('**Banned**', banMember.user.username)
.addField('**ID**', `${banMember.id}`)
.addField('**Banned By**', message.author.username)
.addField('**Reason**', `${reason || '**No Reason**'}`)
.addField('**Date**', message.createdAt.toLocaleString())
.setTimestamp();
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(embed)
}
};
The reason you are getting the TypeError: args.slice(...).join is not a function error is because the slice method creates a new array of the sliced data, and so can not join(' ') since there is no space to join with. (i.e. it is not a string)
What you are looking for is args.slice(1).toString().replace(",", " ")
This removes the 2nd part of the args array object, then converts it to a string, then removes the commas in the string and replaces them with spaces.
const Discord = require("discord.js");
var osu = require('node-os-utils')
var cpu = osu.cpu
var drive = osu.drive
var mem = osu.mem
var netstat = osu.netstat
module.exports.run = async (bot, message, args) => {var count = cpu.count()
cpu.usage()
.then(cpuPercentage => {
console.log(cpuPercentage)
})
drive.info()
.then(dinfo => {
console.log(dinfo)
})
mem.info()
.then(minfo => {
console.log(minfo)
})
netstat.stats()
.then(ninfo => {
console.log(ninfo)
})
let systemEmbed = new Discord.RichEmbed()
.setColor("RANDOM")
.setTitle("Urban Bot System Stats")
.addField("CPU Cores", count, true)
.addField("CPU Usage", osu.cpu, true)
.addField("Drive Usage", osu.drive, true)
.addField("Memory Usage", osu.mem, true)
.addField("Network Stats", osu.netstat, true)
.addField("Logged In User", "Administrator", true)
.addField("Operating System", "Windows Server 2016 Standard", true)
message.channel.send(systemEmbed)
}
module.exports.help = {
name: "system"
}
What the Embed Appears Like
I am trying to do a command that shows system stats. However once it is run on all of the fields it displays "object Object" could anyone help?
Please see the embed for more on what it looks like. It is in a file called system.js in the command handler. The main entry is index.js.