javascript – How to check if a string is included in an array? discord.js

Basically I am trying to make a discord bot to make trivia questions by showing an embed and awaiting the answer, I have put the answers in an array in a separate file, the possibleAnswersF is the array that includes the answers that give you 5 points, and the possibleAnswersT is the array that includes the answers that give you 10, and possibleAnswers is the array that includes all of the answers, I tried to use possibleAnswersF.includes(collected) but it wouldn’t work, I tried to make collected an array and use includes() the other way but it jumped to catch() instead.

const { MessageEmbed } = require('discord.js');
//const talkedRecently = new Set();
const Characters = require('../../triviacharacterlist');
const points = require('../../points.json');
const fs = require('fs');

module.exports = {
    commands : ('trivia', 't'),
    minArgs : 0,
    maxArgs : 0,
    callback : (msg, arguments, text) => {
      function TriviaGuess(possibleAnswers, possibleAnswersF, possibleAnswersT, CharacterImgDir) {
        const guessCharacterString = "Guess character bo3";
        let pointAmt1 = 5;
        let pointAmt2 = 10;

        const triviaEmbed = new MessageEmbed()
            .setColor('#008fff')
            .setTitle(guessCharacterString)
            .setImage(CharacterImgDir)

        msg.channel.send(triviaEmbed)

        const filter = m => possibleAnswers.some(answer => m.content.toLowerCase().includes(answer));
        msg.channel.awaitMessages(filter, { max: 1, time: 15000, errors: ('time') })
            .then(collected => {
                    const fivePoint = `**Congrats**, ${collected.first().author} you got **5** points for guessing the character only!`;
                    const tenPoint = `**Congrats**, ${collected.first().author} you got **10** points for also guessing the series/game!`;
                        if (possibleAnswersF.includes(collected)) {
                            msg.channel.send(fivePoint);
                            points(msg.author.id) = {
                                points: points(msg.author.id).points + pointAmt1
                            };
                            fs.writeFile('./points.json', JSON.stringify(points), (err) => {
                                if (err) {
                                    console.log(err)
                                }
                            });
                        }
                        if (possibleAnswersT.includes(collected)) {
                            msg.channel.send(tenPoint);
                            points(msg.author.id) = {
                                points: points(msg.author.id).points + pointAmt2
                            };
                            fs.writeFile('./points.json', JSON.stringify(points), (err) => {
                                if (err) {
                                    console.log(err)
                                }
                            });
                        }
            })
            .catch(collected => msg.channel.send('too bad u took too long ya 3am'));
      }
      var characterRandom = 0;//Math.floor(Math.random() * 0);
      
      if (characterRandom == 0) {
        TriviaGuess(Characters.CreeperVariants, Characters.CreeperVariantsF, Characters.CreeperVariantsT, Characters.CharacterImgs.creeperimg);
      }
  }
}

The other file that has the arrays:

const CreeperVariants = (
    'creeper',
    'creeper minecraft',
    'creeper mc'
)

const CreeperVariantsF = (
    'creeper'
)

const CreeperVariantsT = (
    'creeper minecraft',
    'creeper mc'
)

javascript – Need Help Updating Bot to Discord.js v12

I’m trying to update this code to work with Discord.js v12. I am encountering an error and I’m kinda stumped on how I could fix this error. I have already updated some of the code to work with Discord.js v12.

TypeError: client.channels.fetch(…).send is not a function

at Client. (/home/runner/Log/index.js:44:40)
at Client.emit (events.js:314:20)
at Client.EventEmitter.emit (domain.js:483:12)
at MessageCreateAction.handle (/home/runner/Log/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports (as MESSAGE_CREATE) (/home/runner/Log/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/Log/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/home/runner/Log/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/home/runner/Log/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/home/runner/Log/node_modules/ws/lib/event-target.js:132:16)

const Discord = require('discord.js');
const client = new Discord.Client();
const { prefix, token, logsChannel } = require('./config.json');

client.once('ready', () => {
    console.log('I am alive!');
});

// Messages log
client.on('message', message => {
    // Function
    function isEmpty(collection) {
        for(var arg in collection) {
            if(collection.hasOwnProperty(arg))
                return false;
        }
        return true;
    }
    // Logs
    if(message.author.bot) return;
    let username = message.author.tag;
    let channel = message.channel.name;
    let server = message.channel.guild;
    var serverAvatarURL = message.guild.iconURL;
    var attachment = (message.attachments).array();
    if(isEmpty(attachment)) {
        var img = "";
    } else {
        var img = attachment(0).url;
    }
    let embed_send = new Discord.MessageEmbed()
        .setAuthor(username, message.author.avatarURL)
        .setColor('23c115')
        .setTitle("Message sent!")
        .setDescription(message.content + " " + img)
        .setImage(img)
        .setFooter("#" + channel)
        .setTimestamp();
    client.channels.fetch(logsChannel).send(embed_send);
});

// Message edit log
client.on("messageUpdate", async(oldMessage, newMessage) => {
    // Function
    function isEmpty(collection) {
        for(var arg in collection) {
            if(collection.hasOwnProperty(arg))
                return false;
        }
        return true;
    }
    // Logs
    if (oldMessage.content === newMessage.content) {
        return;
    }

    var attachment = (oldMessage.attachments).array();
    if(isEmpty(attachment)) {
        var img = "";
    } else {
        var img = attachment(0).url;
    }

    let embed_edit = new Discord.MessageEmbed()
        .setAuthor(oldMessage.author.tag, oldMessage.author.avatarURL)
        .setColor('2615c1')
        .setTitle("Message edited!")
        .addField("Old", oldMessage.content + " " + img, true)
        .addField("New", newMessage.content + " " + img, true)
        .setFooter("#" + oldMessage.channel.name)
        .setTimestamp();
    client.channels.fetch(logsChannel).send(embed_edit);
});

// Message delete log
client.on("messageDelete", async message => {
    // Function
    function isEmpty(collection) {
        for(var arg in collection) {
            if(collection.hasOwnProperty(arg))
                return false;
        }
        return true;
    }
    // Logs
    var attachment = (message.attachments).array();
    if(isEmpty(attachment)) {
        var img = "";
    } else {
        var img = attachment(0).url;
    }

    let embed_delete = new Discord.MessageEmbed()
    .setAuthor(message.author.tag, message.author.avatarURL)
    .setColor('c11515')
    .setTitle("Message deleted!")
    .setDescription(message.content + " " + img)
    .setImage(img)
    .setFooter("#" + message.channel.name)
    .setTimestamp();    
    client.channels.fetch(logsChannel).send(embed_delete);
});

client.login(token);

The Original Code:

const Discord = require('discord.js');
const client = new Discord.Client();
const { prefix, token, logsChannel } = require('./config.json');

client.once('ready', () => {
    console.log('I am alive!');
});

// Messages log
client.on('message', message => {
    // Function
    function isEmpty(collection) {
        for(var arg in collection) {
            if(collection.hasOwnProperty(arg))
                return false;
        }
        return true;
    }
    // Logs
    if(message.author.bot) return;
    let username = message.author.tag;
    let channel = message.channel.name;
    let server = message.channel.guild;
    var serverAvatarURL = message.guild.iconURL;
    var attachment = (message.attachments).array();
    if(isEmpty(attachment)) {
        var img = "";
    } else {
        var img = attachment(0).url;
    }
    let embed_send = new Discord.RichEmbed()
        .setAuthor(username, message.author.avatarURL)
        .setColor('23c115')
        .setTitle("Message sent!")
        .setDescription(message.content + " " + img)
        .setImage(img)
        .setFooter("#" + channel)
        .setTimestamp();
    client.channels.get(logsChannel).send(embed_send);
});

// Message edit log
client.on("messageUpdate", async(oldMessage, newMessage) => {
    // Function
    function isEmpty(collection) {
        for(var arg in collection) {
            if(collection.hasOwnProperty(arg))
                return false;
        }
        return true;
    }
    // Logs
    if (oldMessage.content === newMessage.content) {
        return;
    }

    var attachment = (oldMessage.attachments).array();
    if(isEmpty(attachment)) {
        var img = "";
    } else {
        var img = attachment(0).url;
    }

    let embed_edit = new Discord.RichEmbed()
        .setAuthor(oldMessage.author.tag, oldMessage.author.avatarURL)
        .setColor('2615c1')
        .setTitle("Message edited!")
        .addField("Old", oldMessage.content + " " + img, true)
        .addField("New", newMessage.content + " " + img, true)
        .setFooter("#" + oldMessage.channel.name)
        .setTimestamp();
    client.channels.get(logsChannel).send(embed_edit);
});

// Message delete log
client.on("messageDelete", async message => {
    // Function
    function isEmpty(collection) {
        for(var arg in collection) {
            if(collection.hasOwnProperty(arg))
                return false;
        }
        return true;
    }
    // Logs
    var attachment = (message.attachments).array();
    if(isEmpty(attachment)) {
        var img = "";
    } else {
        var img = attachment(0).url;
    }

    let embed_delete = new Discord.RichEmbed()
    .setAuthor(message.author.tag, message.author.avatarURL)
    .setColor('c11515')
    .setTitle("Message deleted!")
    .setDescription(message.content + " " + img)
    .setImage(img)
    .setFooter("#" + message.channel.name)
    .setTimestamp();    
    client.channels.get(logsChannel).send(embed_delete);
});

client.login(token);

javascript – Como criar um canal de voz temporário Discord.JS

Boa noite, estou tentando deixar os usuário com um cargo especifico no meu Discord criar um canal temporário através de comando pelo chat.

Eu gostaria que quando o canal estivesse vazio, o canal fosse excluído, justamente para deixar temporário, porem não estou obtendo êxito, podem me auxiliar?

Também não consigo limitar para 2 cargos específicos, conseguem me ajudar?

index.js:

const Discord = require("discord.js"); //baixar a lib
const client = new Discord.Client(); 
const config = require("./config.json"); 
const comando = require("./comando.js");

client.on('ready', () => {
    console.log('O aplicativo Começou!')
  
    comando(client, 'criarcanal', (message) => {
      const name = message.content.replace('!Canal de Voz: ', '')
      if (message.member.hasPermission('ADMINISTRATOR')) {
      message.guild.channels
        .create(name, {
          type: 'voice',
        })
        .then((channel) => {
          const categoryId = '816397760072646757'
          channel.setParent(categoryId)
          channel.setUserLimit(10)
        })
      }
    })
})

client.login(config.token)

comando.js:

const {prefix} = require("./config.json");

module.exports = (client, aliases, callback) => {

    if (typeof aliases === 'string'){
        aliases = (aliases);
    }

    client.on('message', (message) =>{
        const {content} = message;

        aliases.forEach((alias) => {
            const comando = `${prefix}${alias}`

            if (content.startsWith(`${comando}`) || content === comando){
                console.log(`Digite o seu Comando: ${comando}`)
                callback(message)
            }
        })
    })
}

node.js – Discord.JS getting all attachments from a message

Hi I’m tying to make a say command that sends attachments that was sent while using the command for example someone uses !say while attaching 3 attachment and it sends the 3 attachments last time I tried to do it I could only get the first attachment but I want to get all the attachments that was attached with the message

javascript – how can i make this command loop? [Discord.js]

I have this command but i dont have idea how to make it loop until i turn off the bot. I will be really grateful if you can help me.
the code i want to loop is this:

module.exports = {
name: 'spam',
description: 'face spam',
execute(message, args){
    let messages = (
        "Ghg&gjhgTF55$FGjhuc$%",
        "ggt6rjhf*r8rfhgo(gFT&",
        "F^v 6r796GIGYv6rcKUYg",
        "g7v%C75C&TOHbgv*C^ruk",
        "hgC^%4x7vV(P&v0b87&^C",
        "hguiv^&vr675rXC&5vvv6",
        "78v tv8976r9uyv ci y6",
        "b87%687*V8V*v7UYVOUYV",
        "bt8787V5V9&^v*&5Xdiov",
        " *^&t*^&V&cr(R5kjYGBk",
    )
    const message = messages(Math.floor(Math.random() * (messages.length)));
    message.channel.send(message);

}   

}

javascript – (Discord.JS) Como enviar uma mensagem somente depois do timeout de message.delete()?

Basicamente o que eu quero é executar a linha message.channel.send('Send me after timeout'); somente depois do timeout de message.delete().

const Discord = require('discord.js');

module.exports = {
    name: 'coin',
    description: 'Toss Coin!',
    aliases: 'toss',
    execute(message, args) {
        message.delete().catch(O_o => {});

        const embed = new Discord.MessageEmbed()

        .setTitle(`${message.author.username}`)
        .setColor('#6d00c1')
        .setImage('https://i.pinimg.com/originals/8f/06/04/8f0604aedc34d33d2f41113c312a588d.gif');
        
        message.channel.send(embed)
        .then(message => { message.delete({ timeout: 4000 })}).catch(O_o => {});

        message.channel.send('Send me after timeout');
    },
};

javascript – Canvas not drawing image in js. (discord.js)

I want to create an inventory system. First it is drawing the basic inventory without items.
After that it is check if the user has got item, then draw it on the empty squares.
The items are located in ./cdn/items/ .

I have an item in my database, but the code is only drawing the empty inventory without items.

  const canvas = Canvas.createCanvas(700, 250);
  const ctx = canvas.getContext('2d');
  const logo = await Canvas.loadImage('./cdn/atransparent.png');
  //item id
  const item = (
    await Canvas.loadImage('./cdn/items/key.jpg')

  )

  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "black";
  ctx.fillStyle = "#2c2f33";

  for (var i = 0; i < 40; i++) {
    ctx.fillRect(55+(i%10)*60, (((((Math.floor(i/10)+1)-1)*6)+1)*10), 50, 50);
  }

  ctx.globalAlpha = 0.4;
  ctx.drawImage(logo, 250, 25, 200, 200);
  ctx.globalAlpha = 1.0;

  ctx.translate(10,250);
  ctx.rotate(-0.5*Math.PI);
  ctx.font = "30px Arial";
  ctx.fillStyle = "#FFF";
  ctx.textAlign = "center";
  ctx.fillText(message.author.username , 125, 27.5);
  ctx.restore();

  db.query(`SELECT * FROM economy WHERE member_id = ${message.author.id}`, (err, rows) => {
    console.log(`(INVENTORY) Adatok lekérdezése ${message.author.id} számára...`)
    let items = rows(0).items.trim().split(',');
    console.log(`(INVENTORY) ${message.author.id} inventoryjának tartalma: ${items}`);

      for (var i = 0; i < items.length; i++) {
        ctx.drawImage(item(items(i)), 55+(i%10)*60, (((((Math.floor(i/10)+1)-1)*6)+1)*10), 50, 50);
        }

      }
    )

  const attachment = new Discord.MessageAttachment(canvas.toBuffer(), 'welcome-image.png');
  message.channel.send(`${message.author.username} Inventory-ja`, attachment);

  }

In the array there is one item with the item(0) variable, my item id in th database is 0, so it need to draw it out.
my id is 3
Idk what is the problem…

Thanks, and Happy New Year!
Mark

javascript – Cannot read property ‘length’ of undefined discord.js V12

const client = new Discord.Client();
const fs = require('fs');
const config = require('./json/config.json');

client.commands = new Discord.Collection();
client.aliases = new Discord.Collection();
client.config = config;
fs.readdir("./events", (err, files) => { 
   if(err) return console.error(`(Foxy Internal Error) - Ocorreu um erro ao ler o path ./events`);
   files.forEach(file => {
       const foxyevent = require(`./events/${file}`);
       const foxyeventname = file.split(".")(0);
       console.log(`(EVENTS) - Loaded event ${foxyeventname}.`);
       client.on(foxyeventname, foxyevent.bind(null, client));
   });
});

fs.readdir('./commands', (err,files) => {
   console.log('(COMMANDS)', `Loaded ${files.length} commands`)
     if(err) console.error(err)
     let jsfiles = files.filter(file => file.split(".").pop() === 'js')
     if(!jsfiles || jsfiles.legnth <= 0) console.log(`Comandos não encontrados`)
     jsfiles.forEach((file,i) => {
       let props = require(`./commands/${file}`)
         if(props.run && props.help.name) {
             client.commands.set(props.help.name, props)
             if(props.help.aliases && Array.isArray(props.help.aliases)) {
                 props.help.aliases.forEach(alias => {
                     client.aliases.set(alias, props.help.name)
                 })
             }
         } else {
             console.log(`Comando '${props.help.name}' com erro!`)
         }
       })
   })


client.login(config.token);
Retorna:     


console.log('(COMMANDS)', `Loaded ${files.length} commands`)
                                             ^

TypeError: Cannot read property 'length' of undefined
   at /root/foxy/src/FoxyClient.js:20:47
   at FSReqCallback.oncomplete (fs.js:171:23)

node.js – Erro ao tentar retornar um valor em um forma JSON (express, discord.js)

const express = require('express');
const app = express();

const Discord = require('discord.js');
const client = new Discord.Client();



app.get("/", (req, response) => {
  const ping = new Date();
  ping.setHours(ping.getHours() - 3);
  console.log(`(API) Ping recebido às ${ping.getUTCHours()}:${ping.getUTCMinutes()}:${ping.getUTCSeconds()}`);
  response.sendStatus(200);
})


client.on('ready', ready => {
  console.log('(BOT) Ouvindo a API.')

})

function info(member) {
  let astro = client.guilds.cache.get('734865367385768049');
  let person = astro.members.cache.get(member);
  let avatares = person.user.displayAvatarURL();
  let name = person.user.username;
  let discrim = person.user.discriminator;
  console.log(avatares);
  console.log(name);
  console.log(discrim);
}

app.get("/id=:id_member", (req, response) => {
  console.log('(API) Pegando um member')
  const id = req.params.id_member;
  let i = info(id);
  response.status(200).json({
    foto: `${i.avatares}`,
    nome: `${i.name}`,
    tag: `${i.discrim}`
  })
})



client.login('');
app.listen(process.env.PORT);

Basicamente, estou tentando fazer um API que retorna o avatar (url), nome, e # do Discord. Mas recebo o erro na hora de fazer o request:

TypeError: Cannot read property ‘avatares’ of undefined
   at /home/runner/api-astro/index.js:38:16
   at Layer.handle (as handle_request) (/home/runner/api-astro/node_modules/express/lib/router/layer.js:95:5)
   at next (/home/runner/api-astro/node_modules/express/lib/router/route.js:137:13)
   at Route.dispatch (/home/runner/api-astro/node_modules/express/lib/router/route.js:112:3)
   at Layer.handle (as handle_request) (/home/runner/api-astro/node_modules/express/lib/router/layer.js:95:5)
   at /home/runner/api-astro/node_modules/express/lib/router/index.js:281:22
   at param (/home/runner/api-astro/node_modules/express/lib/router/index.js:354:14)
   at param (/home/runner/api-astro/node_modules/express/lib/router/index.js:365:14)
   at Function.process_params (/home/runner/api-astro/node_modules/express/lib/router/index.js:410:3)
   at next (/home/runner/api-astro/node_modules/express/lib/router/index.js:275:10)

node.js – Error when trying to verify if a string equals to an array value (discordjs)

const Discord = require('discord.js');

module.exports.run = (client, msg, args) => {
    msg.delete();
    let type = args(0);
    let types = ('available', 'idle', 'dnd', 'invisible')
    if(!type === types(0) || types(1) || types(2) || types(3)) return msg.channel.send(new Discord.RichEmbed().setAuthor('Error').setDescription('Sintaxe errada.'))

}

Basically, when I execute the commando with the wrong sintax, it sends the embed, but when i send with the correct sintax, it still sends the embed.

Someone can help? 🙂