How do I specify options for commands? - javascript

I want to specify choices for an option for my command in Discord.js. How do I do that?
The command:
module.exports = {
name: 'gifsearch',
description: 'Returns a gif based on your search term.',
options: [{
name: 'type',
type: 'STRING',
description: 'Whether to search for gifs or stickers.',
choices: //***this is the area where I have a question***
required: true
},
{
name: 'search_term',
type: 'STRING',
description: 'The search term to use when searching for gifs.',
required: true,
}],
async execute(interaction) {
let searchTerm = interaction.options.getString('search_term')
const res = fetch(`https://api.giphy.com/v1/gifs/search?q=${searchTerm}&api_key=${process.env.giphyAPIkey}&limit=1&rating=g`)
.then((res) => res.json())
.then((json) => {
if (json.data.length <= 0) return interaction.reply({ content: `No gifs found!` })
interaction.reply({content: `${json.data[0].url}`})
})
},
};
I have read the discord.js documentation/guide and I know about the .addChoice() method, but it doesn't look like that will be compatible with my bot's current code.

The discord.js api describes this as ApplicationCommandOptionChoices.
So you basically just insert an array of this in your choices.
module.exports = {
...
choices: [
{
name: "name to display",
value: "the actual value"
},
{
name: "another option",
value: "the other value"
}
]
...
};

Related

How can I exit Inquirer prompt based on answer?

I’m working on an application that sets a series of questions to generate an employee profile. As it is intended to be recursive, the user will be asked at the beginning and the end of the prompt to exit and terminate the enquire.
const employeeQuestions = [
// Role of employee
{
type: 'rawlist',
name: 'role',
message: 'What is the role of the employee?',
choices: [
'Engineer',
'Intern',
new inquirer.Separator(),
'Finish building the team', <=== THIS IS THE ANSWER THAT SHOULD TERMINATE THE PROMPT
],
default: 3,
},
// Employee questions
{
type: 'input',
name: `employee_name`,
message: answer => `Enter name of the ${answer.role}`,
},
{
type: 'number',
name: `employee_id`,
message: answer => `Enter ${answer.role} ID`,
validate(answer) {
const valid = !isNaN(parseFloat(answer));
return valid || 'Please enter a number';
},
filter: Number,
},
{
type: 'input',
name: `employee_email`,
message: answer => `Enter ${answer.role} Email address`,
},
// Engineer questions
{
when(answer) {
return answer.role === 'Engineer';
},
type: 'input',
name: `engineer_github`,
message: 'Enter GitHub username',
},
// Intern questions
{
when(answer) {
return answer.role === 'Intern';
},
type: 'input',
name: `intern_school`,
message: 'Enter intern school',
},
// add more employees
{
type: 'confirm',
name: `add_more`,
message: 'Do you want to add another employee?', <=== THIS IS THE QUESTION THAT SHOULD TERMINATE THE PROMPT
default: true,
},
];
// # Functions
// * Inquires all over if add_more = true
function inquireAgain() {
inquirer.prompt(employeeQuestions).then(answers => {
employeesInfo.push(answers);
if (answers.add_more) {
inquireAgain();
} else {
console.log(JSON.stringify(employeesInfo, null, ' '));
}
});
}
// * Initialize the inquirer prompts
async function init() {
const inquireManager = await inquirer.prompt(managerQuestions);
employeesInfo.push(inquireManager);
inquireAgain();
}
// # Initialisation
init();
this is the closest thing I found related to terminate the prompt, but is not working for me, Thanks in advance.

Undefined value

i have a problem
i entered Unturned or any other game but in output it says about other game
const { ApplicationCommandType } = require('discord.js');
const fetch = require("node-fetch");
const pop = require('popcat-wrapper')
module.exports = {
name: 'steam',
description: "get info about games",
type: ApplicationCommandType.ChatInput,
cooldown: 3000,
options: [
{
name: 'gameinfo',
description: 'get info about a game',
type: 1,
options: [
{
name: 'game',
description: 'Game name',
type: 3,
required: true
}
]
}
],
run: async (client, interaction) => {
const game = interaction.options.get('game')
const gameinfo = await pop.steam(game)
console.log(gameinfo)
}
}
what i got (this is not that game that i entered)
{
type: 'game',
name: 'Touhou Seirensen ~ Undefined Fantastic Object.',
thumbnail: 'https://cdn.akamai.steamstatic.com/steam/apps/1100160/capsule_231x87.jpg?t=1591411698',
description: 'アレは何だ? 鳥か? 妖精か? 謎に満ちた未確認幻想物体が、君を未知の世界に誘う! ファンタスティックでレトロな弾幕シューティング幻想',
website: 'http://www16.big.or.jp/~zun/',
banner: 'https://cdn.akamai.steamstatic.com/steam/apps/1100160/header.jpg?t=1591411698',
developers: [ '上海アリス幻樂団' ],
publishers: [ 'Mediascape Co., Ltd.' ],
price: '12,49€'
}
I'm new to Javascript. And English its not my main language sorry for errors if there's any
i fix it
i added .value:
const game = interaction.options.get("game").value;

MongoDB not saving correct ID | Discord.js 13

So this may just be me being stupid and forgetting a semicolon or something, but I can't seem to resolve this. For my ticket command, I make it so when someone uses the command /ticketsetup and it saves the data of the inputted channels as ID's to then be referenced later. But for some reason, one of them just saves a completely random ID that isn't related to the inputted channel (Transcript)
const {MessageEmbed, CommandInteraction, MessageActionRow, MessageButton} = require('discord.js')
const DB = require('../../Structures/Schemas/TicketSetup')
module.exports = {
name: "ticketsetup",
usage: "/ticketsetup (Admin only)",
description: "Setup your ticketing message.",
permission: "ADMINISTRATOR",
options: [
{
name: "channel",
description: "Select the ticket creation channel.",
required: true,
type: "CHANNEL",
channelTypes: ["GUILD_TEXT"]
},
{
name: "category",
description: "Select the ticket channel's category.",
required: true,
type: "CHANNEL",
channelTypes: ["GUILD_CATEGORY"]
},
{
name: "transcripts",
description: "Select the transcripts channel.",
required: true,
type: "CHANNEL",
channelTypes: ["GUILD_TEXT"]
},
{
name: "handlers",
description: "Select the ticket handler's role.",
required: true,
type: "ROLE"
},
{
name: "description",
description: "Set the description of the ticket creation channel.",
required: true,
type: "STRING"
}
],
/**
*
* #param {CommandInteraction} interaction
*/
async execute(interaction) {
const {guild, options} = interaction
try {
const Channel = options.getChannel("channel")
const Category = options.getChannel("category")
const Transcripts = options.getChannel("transcripts")
const Handlers = options.getRole("handlers")
const Description = options.getString("description")
await DB.findOneAndUpdate({GuildID: guild.id},
{
ChannelID: Channel.id,
Category: Category.id,
Transcripts: Transcripts.id,
Handlers: Handlers.id,
Everyone: guild.id,
Description: Description,
},
{
new: true,
upsert: true
}
);
const Embed = new MessageEmbed().setAuthor({
name: guild.name + " | Ticketing System",
iconURL: guild.iconURL({dynamic: true})
})
.setDescription(Description)
.setColor("#36393f")
const Buttons = new MessageActionRow()
Buttons.addComponents(
new MessageButton()
.setCustomId("ticket")
.setLabel("Create Ticket!")
.setStyle("PRIMARY")
.setEmoji("🎫")
)
await guild.channels.cache.get(Channel.id).send({embeds: [Embed], components: [Buttons]})
interaction.reply({content: "Done", ephemeral: true})
} catch (err) {
const ErrEmbed = new MessageEmbed().setColor("RED")
.setDescription(`\`\`\`${err}\`\`\``)
interaction.reply({embeds: [ErrEmbed]})
}
}
}
Schema Model:
const {model, Schema} = require('mongoose')
module.exports = model("TicketSetup", new Schema({
GuildID: String,
Channel: String,
Category: String,
Transcripts: String,
Handlers: String,
Everyone: String,
Description: String,
}))

How to rename a field in mongoose?

I have a database in which the schema was originally set as follows;
const productSchema = new mongoose.Schema({
supplier: {
type: String,
required: 'Supplier is required',
ref: 'Supplier'
},
name: {
type: String,
required: 'Name is required'
},
price: {
type: Number,
required: 'Price is required'
}
})
But now I want to rename the field name to product like so;
const productSchema = new mongoose.Schema({
supplier: {
type: String,
required: 'Supplier is required',
ref: 'Supplier'
},
product: {
type: String,
required: 'Product is required'
},
price: {
type: Number,
required: 'Price is required'
}
})
The result I am getting from my client isn't updating to show the product instead of name;
Result:
[
{
"_id": "5df7baa7acf4ed3897d8d4c9",
"supplier": "Old Co Ltd",
"name": "Small Woggle",
"price": 6
}
]
and finally here is my database where I populate the fields in mongoose;
mongoose.connect(dbURI, (err, db) => {
db.dropDatabase()
.then(() => Product.create([{
supplier: 'Old Co Ltd',
product: 'Small Woggle',
price: 6
}]))
.then(products => console.log(`${products.length} products created`))
.catch(err => console.log(err))
.finally(() => mongoose.connection.close())
})
Please help me to rename this field
You can't just rename the field in your schema. You need to actually run an update.
Example:
productSchema.update({}, { $rename: { name: 'product' } }, { multi: true }, (err) => {
if(err) { throw err; }
console.log('complete');
});
https://docs.mongodb.com/manual/reference/operator/update/rename/
The answer above works, but I also found an alternative without adding anything to your code.
Just use the following steps like so;
1. In terminal run mongod
2. Navigate to db and drop database db.dropDatabase()
3. Then initialize your database by running node on the file.

Returning a value with node inquirer package

I'm attempting to use the node.js inquirer package to run a simple flashcard generator. I'm having trouble getting the syntax to return the checkbox the user clicked. So, once the user makes a choice, I'd like to be able to log the result of that choice. Currently this console.log() returns "undefined".
Any help appreciated!
inquirer.prompt ([
{
type: "checkbox",
name: "typeOfCard",
message: "Select an action.",
choices: [
{
name: "Create a Basic Card"
},
{
name: "Create a Cloze Card"
},
{
name: "Run the flashcards!"
}
]
}
]).then(function(answers){
console.log(answers.typeOfCard[0])
});
const inquirer = require('inquirer');
inquirer.prompt ([
{
type: "checkbox",
name: "typeOfCard",
message: "Select an action.",
choices: [
"Create a Basic Card",
"Create a Cloze Card",
"Run the flashcards!"
]
}
]).then(function(answers){
console.log(answers.typeOfCard);
});
choices should just be an array of strings. You will then be returned an array containing the selected items, ex:
[ 'Create a Cloze Card', 'Run the flashcards!' ]
Hope that helps!
const inquirer = require("inquirer");
console.clear();
const main = async() => {
const readCardChoise = () => {
const read = new Promise((resolve, reject) => {
inquirer.prompt ([
{
type: "checkbox",
name: "typeOfCard",
message: "Select an action.",
choices: [
{
name: "Create a Basic Card"
},
{
name: "Create a Cloze Card"
},
{
name: "Run the flashcards!"
}
],
validate(answer) {
if (answer.length < 1) {
return 'You must choose at least one card.';
}
return true;
},
}])
.then((answers) => {
resolve(answers.typeOfCard);
});
});
return read;
}
const cadSelect = await readCardChoise();
console.log(cadSelect)
}
main();

Categories

Resources