discord.js api request command - discord

const config = require(`${process.cwd()}/botconfig/config.json`)
var ee = require(`${process.cwd()}/botconfig/embed.json`)
const fetch = require("node-fetch");
const { MessageEmbed } = require(`discord.js`);
module.exports = {
//definition
name: "glifestats", //the name of the command
category: "⌨️ Programming", //the category this will be listed at, for the help cmd
aliases: [""], //every parameter can be an alias
cooldown: 4, //this will set it to a 4 second cooldown
usage: "glifestats <id>", //this is for the help command for EACH cmd
description: "check stats", //the description of the command
};
run: async (client, message, args, cmduser, text, prefix) => {
await interaction.deferReply();
const term = interaction.options.getString('term');
const query = new URLSearchParams({ term });
const { list } = await fetch(`https://api.gtaliferp.fr:8443/v1/extinction/profiles/main/${query}`)
.then(response => response.json());
}
When i try to do this command, it does nothing.
It needs to get the query from the user message and post it to the url, example:
.command 4443
bot returns the https://api.gtaliferp.fr:8443/v1/extinction/profiles/main/4443 data and postes it.
And also, i wanted to make the different data on an embed like this: data 1: data data 2: data .... but i cant do it, ( check the url provided for the data titles if you want to help with that)

So you seperated your module from the rest of the command with this line marked below
module.exports = {
//definition
name: "glifestats", //the name of the command
category: "⌨️ Programming", //the category this will be listed at, for the help cmd
aliases: [""], //every parameter can be an alias
cooldown: 4, //this will set it to a 4 second cooldown
usage: "glifestats <id>", //this is for the help command for EACH cmd
description: "check stats", //the description of the command
} //here
Also term is reqesting an option that is not defined
const term = interaction.options.getString('term');
Interaction is not defined
run: async (client, message, args, cmduser, text, prefix) => {
await interaction.deferReply();
const term = interaction.options.getString('term');
Try this
const config = require(`${process.cwd()}/botconfig/config.json`) // is this needed if not, delete
var ee = require(`${process.cwd()}/botconfig/embed.json`) // is this needed if not, delete
const fetch = require("node-fetch");
const {
MessageEmbed
} = require(`discord.js`); // is this needed if not, delete
module.exports = {
name: "glifestats", //the name of the command
category: "⌨️ Programming", //the category this will be listed at, for the help cmd
aliases: [""], //every parameter can be an alias
cooldown: 4, //this will set it to a 4 second cooldown
usage: "glifestats <id>", //this is for the help command for EACH cmd
description: "check stats", //the description of the command
options: [{
name: "term",
description: "Code to search",
required: true,
type: "STRING",
}],
run: async (client, interaction) => {
await interaction.deferReply();
const term = interaction.options.getString('term');
const url = `https://api.gtaliferp.fr:8443/v1/extinction/profiles/main/${term}`
const list = await fetch(url).then(response => response.json())
// Do something with list
console.log(list)
return interaction.followUp({
content: `List has been logged but can't be sent yet because it is an object and need to be further worked to get specific elements from it`
})
// Above seemed cleaner to me
/*
const query = new URLSearchParams({
term
});
const {
list
} = await fetch(`https://api.gtaliferp.fr:8443/v1/extinction/profiles/main/${query}`)
.then(response => response.json());
*/
}
}

Related

Trying to add a warning system to my mongodb, it works but says application didn't respond

const {Client, CommandInteraction, MessageEmbed} = require("discord.js");
const db = require("../../Structures/Schemas/InfractionDB");
module.exports = {
name: "warnings",
description: "Give a warning",
permission: "ADMINISTRATOR",
options: [
{
name: "target",
description: "Select a target.",
type: "USER",
required: true
},
{
name: "reason",
description: "Provide a reason.",
type: "STRING",
required: true
},
{
name: "evidence",
description: "Provide evidence.",
type: "STRING",
required: false
},
],
/**
*
* #param {CommandInteraction} interaction
* #param {Client} client
*/
execute(interaction, client) {
const{guild, member, options} = interaction
const Target = options.getMember("target");
const Reason = options.getString("reason");
const Evidence = options.getString("evidence") || "None provided";
const Response = new MessageEmbed()
.setColor("RED")
.setAuthor({name: "MOD BOT", iconURL: guild.iconURL()});
db.findOne({GuildID: guild.id, UserID: Target.id}, async (err,data)=> {
if(err) throw err;
if(!data || !data.WarnData) {
data = new db({
GuildID: guild.id,
UserID: Target.id,
WarnData: [
{
ExecuterID: member.id,
ExecuterTag: member.user.tag,
TargetID: Target.id,
TargetTag: Target.user.tag,
Reason: Reason,
Evidence: Evidence,
Date: parseInt(interaction.createdTimestamp / 1000)
}
],
})
} else {
const WarnDataObject ={
ExecuterID: member.id,
ExecuterTag: member.user.tag,
TargetID: Target.id,
TargetTag: Target.user.tag,
Reason: Reason,
Evidence: Evidence,
Date: parseInt(interaction.createdTimestamp / 1000)
}
data.WarnData.push(WarnDataObject)
}
data.save()
});
Response.setDescription(`Warning Added: ${Target.user.tag} | ||${Target.id}||\n**Reason**: ${Reason}\n**Evidence**:${Evidence}`);
guild.channels.cache.get("946217387336818699").send({embeds:[Response]});
}}
originally this was routed to a different collection in my db. I've tried to convert it so I can see everything in one place. but it's taken me hours and don't seem to be getting anywhere. Like I said, the data is being stored on the db, but the Response is failing. Any ideas how to fix this? There are no errors in terminal
The error i think is that your application is taking too long to respond.
you have only 3 seconds to respose.
for this i would suggest that you execute you interaction as a async function
and you should use await before trying to find it in the database. because it can take some time to find the data in the database.
The data is store in database because it has no concern with the response time but the discord api wants a reply in 3 seconds or it will fail.
I have read your code. it seems okay.
i would suggest you to use the easier way instead of using the object or json form to create the commands.
SlashCommandBuilder from #discordjs/builders
its easy to use and simple.
here is an example of how easy it is if you use SlashCommandBuilder
const { SlashCommandBuilder } = require('#discordjs/builders');
const data = new SlashCommandBuilder()
.setName('gif')
.setDescription('Sends a random gif!')
.addStringOption(option =>
option.setName('category')
.setDescription('The gif category')
.setRequired(true)
.addChoice('Funny', 'gif_funny')
.addChoice('Meme', 'gif_meme')
.addChoice('Movie', 'gif_movie'));
you can install all the dependencies using
npm install discord.js #discordjs/rest discord-api-types

discord.js canvas image manipulation

I wan't to make a command that put the user avatar in my wanted image
const { createCanvas, loadImage } = require('canvas')
const { MessageAttachment } = require('discord.js');
const Command = require('../../structures/Command')
module.exports = class extends Command {
constructor(client) {
super(client, {
name: 'wanted',
description: 'Coloca a cabeça de um usuário valendo $2000.',
options: [
{
name: 'user',
description: 'Usuário que terá a cabeça posta num cartaz de procurado',
type: 'USER',
required: true
}
]
})
}
run = async (interaction) => {
const canvas = createCanvas(239, 338)
const ctx = canvas.getContext('2d')
const wantedImg = await loadImage("imgs/wanted.png")
const userAv = interaction.options.getUser('user')
const Avatar = userAv.avatarURL()
interaction.reply(wantedImg)
}
}
I put the wantedImg in interaction.reply to see if the client return in chat the wanted image, but it's getting error...
Cannot find module
'C:\Users\pulse\OneDrive\Documentos\Cynthia\JS\src\commands\imgs\imgs'
I would recommend using jimp instead:
const user = message.mentions.users.first() //get The first user mentioned
if (!user) return message.reply("Who is wanted?")//return if no user was mentioned
var wantedImage = "wanted image url goes here"
var pfp = user.avatarURL({ format: 'png', dynamic: true, size: 128 }) //Get link of profile picture
var image = await Jimp.read(pfp)//read the profile picture, returns a Jimp object
//Composite resized bars on profile picture
image.composite((await Jimp.read(bars)).resize(128, 128), 0, 0)
//Create and attachment using buffer from edited picture and sending it
var image = new Discord.MessageAttachment(await image.getBufferAsync(Jimp.MIME_PNG))
message.reply(image) //replies to original command with image
It has far more options than canvas.
Make sure your path is correct, it seems that the path won't get resolved correctly. To be sure about your paths, consider using.
const {join} = require("path");
const wantedImg = loadImage(join(__dirname, "imgs/wanted.png"));

How To Make Queue System - Discord.js

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 = []
}
})

Call Exports.run async from a member phrase

Please help me understand how can i call that ping.js from user input, like if a user type ping it will Trigger cuz of the aliases but if a user types a full phrase it won't trigger.
Or in a non headic question how can i implent this to work -> if (message.content.includes('ping'))
Sorry in advance and thanks a lot
ping.js
const Discord = require('discord.js')
const colors = require('../lib/colors.json')
exports.run = async (client, message, args, level) => {
try {
const pingEmbed = new Discord.RichEmbed()
.setColor(colors.default)
.setFooter('ping)
.addField(`${message.author.id}`, 'hey')
const msg = await message.channel.send(pingEmbed)
const embed = new Discord.RichEmbed()
.setColor(colors.default)
.addField('...',
`${msg.createdTimestamp - message.createdTimestamp}ms`)
msg.edit(embed)
} catch (err) {
message.channel.send('There was an error!\n' + err).catch()
}
}
exports.conf = {
enabled: true,
aliases: ['ping'],
guildOnly: false,
permLevel: 'User'
}
exports.help = {
name: 'ping,
category: 'tools,
description: 'ping pong',
usage: 'ping'
}
If you want to check whether a message contains any of the aliases you can just use Array.some() like this:
let aliases = ['your', 'command', 'aliases']
client.on('message', message => {
if (aliases.some(trigger => message.content.includes(trigger))) {
// The message includes at least one of your keywords
}
})
In this example is just declared aliases, but you can use the array from your command and integrate this method in your normal command handler.

discord.js say command actually says "say"

I've never had a problem with the say command until I start using modules and cleaned up my code but since I have few my commands have bugged. I'm trying to figure out why it is saying the command.
const commandFiles = fs
.readdirSync("./commands/")
.filter(file => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
bot.commands.set(command.name, command);
}
bot.on("message", async message => {
if (!message.content.startsWith(PREFIX)) return;
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case "say":
bot.commands.get("say").execute(message, args);
break;
const Discord = require("discord.js");
module.exports = {
name: "say",
description: "Show's avatar",
async execute(message, args){
const sayMessage = args.join(" ");
message.delete().catch(O_o => {});
message.channel.send(`${sayMessage} - ${message.author}`);
}
}
Thanks in advance!
The code is doing exactly what you programmed it to, be it not intended.
let args = message.content.substring(PREFIX.length).split(" "); // args = ['say', 'Hello', 'World']
bot.commands.get("say").execute(message, args); // Passing in the entire args array
const sayMessage = args.join(" "); // sayMessage = 'say Hello World'
One solution of many:
let args = message.content.substring(PREFIX.length).split(" ");
const command = args.splice(0, 1); // args now only contains the arguments
switch (command) {
...
}
Here you go this is using the anidiots guidebot boiler plate i highly recommend using it to help you better understand incorporating a command handler into your discord bot.
your going to want to download the repo from here https://github.com/AnIdiotsGuide/guidebot/
extract it
run npm install
in the commands folder add say.js using the code below this is how to properly execute what your trying todo
by default the prefix is ~ to change it in discord chat run ~conf edit prefix Example: ~conf edit prefix !
run !say hello world
exports.run = async (client, message, args) => {
const sayMessage = args.join(" ");
message.delete();
message.channel.send(sayMessage + ' - ' + message.author)
};
exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: "User"
};
exports.help = {
name: "say",
category: "Miscelaneous",
description: "say command",
usage: "say"
};```

Resources