PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label discord.js. Show all posts
Showing posts with label discord.js. Show all posts

Thursday, October 20, 2022

[FIXED] What is the best way of figuring out when someone reacts to a message (discord.js)

 October 20, 2022     discord.js, javascript, node.js     No comments   

Issue

I am trying to figure out if someone reacted to a message sent by the bot. I have tried reactions.awaitReactions() but you must select a time and I just want to respond after they react. Is there any way of doing this? I have tried a few different ways of getting this but none have worked in way I wanted.

enter image description here


Solution

The way I got this to work is by adding the below. This is the best way I could find because all other ways you must select a time and that just makes this all pointless.

 client.on('messageReactionAdd', async (reaction, user) => {
              console.log(user.id == message.author.id)
            if(user.bot) return 
            if(!user.id == message.author.id) return
            console.log(reaction.emoji)
            if(reaction.emoji.name == '👍'){
                message.reply("Good")
            
            }else if(reaction.emoji.name == '👎'){
                message.reply("Bad")
            }
    
        })


Answered By - Thebeston123
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 24, 2022

[FIXED] How to get determine a variable from another variable

 July 24, 2022     constants, discord.js, javascript, json, node.js     No comments   

Issue

I have a trivia game in discord.js and need to be able to fetch questions and answers from a json file from a random number since i have multiple lists of questions that it would pick based off like 1.json, 2.json based of a random number gen but every time i try to fetch a question (trivia.QX) it says that trivia is not defined when the code calls for it if the number is 1 it goes for const trivia = require(./game/trivia/1.json) same with 2 and any others i have no clue why it wont work. (sorry about me forgetting to add .'s)


Solution

require takes a string input, meaning the file path needs to be in quotes.

const trivia = require('./game/trivia/1.json');


Answered By - Ryan Pattillo
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 23, 2022

[FIXED] How to get a single value and value name from an JSON file without knowing the value name

 July 23, 2022     arrays, discord.js, javascript, json, node.js     No comments   

Issue

I have a discord bot and it saves achievements in a JSON file. The JSON structure is like this:

{
  "784095768305729566": {
    "coins": 14598,
    "achievements": {
      "taking_inventory": true
    }
  },
}

The command should give you an overview of what achievements you already have.

I want to create an embed and run a for loop for every sub-thing of achievements. If the value is true, the for loop should take the value name and the value and add a field to the embed where the field title is the value name.

I have multiple problems there.

  1. I don't know how to get value names and values. I already tried Object.keys(...) but that gives all keys and not one by one. I don't know how to get the values.
  2. I don't know how to make the for loop as long as all sub-things of achievements.

I tried:

for(var i = 0; i<datafile[id].achievements.length; i++){...}

but that didn't work wither.


Solution

You can get an array of an object's entries (keys and values) from Object.entries. You can filter that array for the value to be true You can map the result to the key. This gives you an array of achievement keys which had the value "true".

const datafile = {
  "784095768305729566": {
    "coins": 14598,
    "achievements": {
      "taking_inventory": true,
      "other_achievement": false
    }
  },
};

const id = "784095768305729566";

const achievements = Object.entries(datafile[id].achievements)
  .filter(([k, v]) => v)
  .map(([k, v]) => k);

// do something with achievements
console.log(achievements);



Answered By - James
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, July 11, 2022

[FIXED] How to send this kind of messages?

 July 11, 2022     bots, discord.js, message     No comments   

Issue

I want my bot to send messages in such bubbles, but I do not know the code.
ATTACHMENT


Solution

Those "bubbles" are embeds, types of messages that can be sent only by bots. To send them, you'll need to use the RichEmbed class: you can create an instance of the class and then edit it with the methods you find in the docs. Here's an example with the image you sent:

let embed = new Discord.RichEmbed()
  .setColor([66, 134, 244])
  .setTitle("Zhontroly' si zprávy")
  .setDescription(":mailbox_with_mail: | Odeslal jsem ti do zpráv napovedu s příkazy!");

channel.send({embed});

Here's a more in-depth example, from "An Idiot's Guide"

const embed = new Discord.RichEmbed()
  .setTitle("This is your title, it can hold 256 characters")
  .setAuthor("Author Name", "https://i.imgur.com/lm8s41J.png")
  /*
   * Alternatively, use "#00AE86", [0, 174, 134] or an integer number.
   */
  .setColor(0x00AE86)
  .setDescription("This is the main body of text, it can hold 2048 characters.")
  .setFooter("This is the footer text, it can hold 2048 characters", "http://i.imgur.com/w1vhFSR.png")
  .setImage("http://i.imgur.com/yVpymuV.png")
  .setThumbnail("http://i.imgur.com/p2qNFag.png")
  /*
   * Takes a Date object, defaults to current date.
   */
  .setTimestamp()
  .setURL("https://discord.js.org/#/docs/main/indev/class/RichEmbed")
  .addField("This is a field title, it can hold 256 characters",
    "This is a field value, it can hold 1024 characters.")
  /*
   * Inline fields may not display as inline if the thumbnail and/or image is too big.
   */
  .addField("Inline Field", "They can also be inline.", true)
  /*
   * Blank field, useful to create some space.
   */
  .addBlankField(true)
  .addField("Inline Field 3", "You can have a maximum of 25 fields.", true);

  message.channel.send({embed});


Answered By - Federico Grandi
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] When checking invites is the following

 July 11, 2022     discord, discord.js, javascript, message, node.js     No comments   

Issue

If I create a new express invitation to the server when the bot is turned on, an error occurs. In other cases, it works

const invites = {};
const wait = require('util').promisify(setTimeout);
client.on('ready', () => {
  wait(1000);
    g.fetchInvites().then(guildInvites => {
      invites[g.id] = guildInvites;
    });
  });
});
client.on('guildMemberAdd', member => {
   member.guild.fetchInvites().then(guildInvites => {
     const ei = invites[member.guild.id];
     invites[member.guild.id] = guildInvites;
     const invite = guildInvites.find(i => ei.get(i.code).uses < i.uses);
     const inviter = client.users.get(invite.inviter.id);
     const logChannel = member.guild.channels.find(channel => channel.name === "join-logs");
     logChannel.send(`${member.user.tag} joined using invite code ${invite.code} from ${inviter.tag}. Invite was used ${invite.uses} times since its creation.`);
   });
 });

Errors:

2019-07-07T09:49:20.363359+00:00 app[worker.1]: Unhandled Rejection: 
2019-07-07T09:49:20.363377+00:00 app[worker.1]:  TypeError: Cannot read property 'uses' of undefined
2019-07-07T09:49:20.363378+00:00 app[worker.1]:     at guildInvites.find.i (./bot.js:398:57)
2019-07-07T09:49:20.363380+00:00 app[worker.1]:     at Map.find (./node_modules/discord.js/src/util/Collection.js:160:13)
2019-07-07T09:49:20.363381+00:00 app[worker.1]:     at member.guild.fetchInvites.then.guildInvites (./bot.js:398:33)
2019-07-07T09:49:20.363382+00:00 app[worker.1]:     at process._tickCallback (internal/process/next_tick.js:68:7)

398 deadline

const invite = guildInvites.find(i => ei.get(i.code).uses < i.uses);

Solution

The invite used is new, and isn't yet in the cache. However, ei.get(i.code).uses assumes it is, and tries to use a property of it when it doesn't exist.

This revised predicate function will return the invite that isn't cached, or the invite that increased in uses.

const invite = guildInvites.find(i => !ei.get(i.code) || ei.get(i.code).uses < i.uses);


Answered By - slothiful
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why am I getting an error fetching messages?

 July 11, 2022     discord.js, edit, fetch, message     No comments   

Issue

there is an error calling the script. Can you ask for help?

Below I paste the code and the error.

let chn = client.channels.find(channel => channel.id === '717019301357420554');
let msg = chn.fetchMessage('717369584801546273');
msg.edit(embedit);
TypeError: msg.edit is not a function

Solution

Is this v11?

Regardless fetching something is async, so you need to wait for msg to resolve.

https://discord.js.org/#/docs/main/11.1.0/class/TextChannel?scrollTo=fetchMessage

Here's how you can go about it:

First one is using await which needs to be inside of an async function

let chn = client.channels.find(channel => channel.id === '717019301357420554');
let msg = await chn.fetchMessage('717369584801546273');
msg.edit(embedit);

Second is .then

let chn = client.channels.find(channel => channel.id === '717019301357420554');
chn.fetchMessage('717369584801546273').then(msg => msg.edit(embedit));

If you want to save it in a variable

let chn = client.channels.find(channel => channel.id === '717019301357420554');
let msg;
chn.fetchMessage('717369584801546273').then(m => msg = m);
//note you will have to wait for the promise to resolve to use 
//the variable msg correctly
//any code beyond this isn't guranteed to have access to 

These are some bad variable names btw, you shouldn't use abbreviations like chn rather channel, and embedit => embEdit. But up to you



Answered By - user13429955
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to make a bot send a message to a specific channel after receiving a reaction from a certain message

 July 11, 2022     async-await, discord.js, message     No comments   

Issue

So I'm trying to develop a bot for a very small project (I'm not a programmer or anything, just need to do this one thing). All I need it to do is to collect reactions from a specific message I sent and send another message to a channel as soon as it detects a reaction. The message would contain the reactor's tag and some text. I would need it to be activelly collecting reactions all the time, without any limit. I tried looking through the documentation but I don't really know how to implement the .awaitmessageReactions or whatever it's called. Can you help me out?


Solution

You can use method createReactionCollector for this. But when bot go down, this collector will stop.

const Discord = require('discord.js');
const bot = new Discord.Client();
let targetChannelId = '1232132132131231';
bot.on('ready', () => {
    console.log(`${bot.user.tag} is ready on ${bot.guilds.cache.size} servers!`);
});

bot.on('message', (message) => {
    if (message.content === 'test') {
        message.channel.send(`i\`m await of reactions on this message`).then((msg) => {
            const filter = (reaction, user) => !user.bot;
            const collector = msg.createReactionCollector(filter);
            collector.on('collect', (reaction, user) => {
                let channel = message.guild.channels.cache.get(targetChannelId);
                if (channel) {
                    let embed = new Discord.MessageEmbed();
                    embed.setAuthor(
                        user.tag,
                        user.displayAvatarURL({
                            dynamic: true,
                            format: 'png',
                        }),
                    );
                }
                embed.setDescription(`${user} (${user.tag}) has react a: ${reaction.emoji}`);
                channel.send(embed);
            });
            collector.on('end', (reaction, reactionCollector) => {
                msg.reactions.removeAll();
            });
        });
    }
});

bot.login('token');

Or you can use emitter messageReactionAdd and handle reaction on specific message.

const Discord = require('discord.js')
const token = require('./token.json').token
const bot = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] });

bot.once('ready', () => {
    console.log(`${bot.user.tag} is ready on ${bot.guilds.cache.size} guilds`)
})

let targetChannelId = '668497133011337224'

bot.on('messageReactionAdd', async (reaction, user) => {
    if (reaction.partial) {
        // If the message this reaction belongs to was removed the fetching might result in an API error, which we need to handle
        try {
            await reaction.fetch();
        } catch (error) {
            console.log('Something went wrong when fetching the message: ', error);
            // Return as `reaction.message.author` may be undefined/null
            return;
        }
    }

    if (reaction.message.id === '730000158745559122') {
        let channel = reaction.message.guild.channels.cache.get(targetChannelId);
        console.log(reaction.emoji)
        if (channel) {
            let embed = new Discord.MessageEmbed();
            embed.setAuthor(
                user.tag,
                user.displayAvatarURL({
                    dynamic: true,
                    format: 'png',
                }),
            );
            embed.setDescription(`${user} has react a: ${reaction.emoji}`);
            channel.send(embed);
        }
    }
});

bot.login(token)


Answered By - Cipher
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how do i DM the bot which puts direct messages into a public channel without spamming messages

 July 11, 2022     bots, discord, discord.js, javascript, message     No comments   

Issue

so what i'm using here is a discord bot that should put down the same message (that i DMed it to) as the one in a public channel within the guild / discord server. but my problem here is that for some reason it spams 6 messages each second.

Down below i described pretty much everything i have done. i bet i'm like BABY steps away from correctly writing the code but i am struggling with it for alot longer that it should have taken.

i've been looking for lots of solutions and tried many variations that i came across and it just confused me more and more on the client.on('ready') or bot.on()

When I used client.on() i got a ReferenceError: msg is not defined error all the time. i couldn't find where the problem was. and when i used bot.on() it said ''ReferenceError: bot is not defined''. which i googled and some said you put down ''client.on()'' etc.

So i got frustrated and decided to ask someone here that can put down a code for me that i can't seem to fix myself idk. i just wasted too much time with it. i'll greatly appreciate for any helping hand out there! thanks in advance!

so anyway here's my code:

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

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', msg => {
    console.log('Message received: ' + msg.content);

    const channel = client.channels.cache.get('CHANNEL ID');
    if (msg.content) {
        channel.send(msg.content);
    }
});

client.login('BOT TOKEN');

Solution

Your bot is simply responding to itself. It replies to your message, then replies to the reply to your message, then replies to the reply to the reply to the reply to your message, etc. You can prevent this by checking if the message author is a bot with User.bot.

You should also check if the message was sent in a dm so that it doesn't trigger on every single random message.

client.on('message', (msg) => {
 if (msg.author.bot || msg.channel.type !== 'dm') return;
 console.log('Message received: ' + msg.content);

 const channel = client.channels.cache.get('CHANNEL ID');
 if (msg.content) {
  channel.send(msg.content);
 }
});


Answered By - Lioness100
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to make a bot edit its own message on Discord

 July 11, 2022     discord, discord.js, edit, javascript, message     No comments   

Issue

My friend wrote this amazing code for me but it doesn't seem to work. It's meant to send a message on a command then edit the message over and over again. But when I run the code my terminal says

DiscordAPIError: Cannot edit a message authored by another user method: 'patch', path: '/channels/808300406073065483/messages/811398346853318668', code: 50005, httpStatus: 403

Is there a way to fix this problem?

client.on('message', userMessage => 
{
    if (userMessage.content === 'hi') 
    {
        botMessage = userMessage.channel.send('hi there')
        botMessage.edit("hello");
        botMessage.edit("what up");
        botMessage.edit("sup");
        botMessage.react(":clap:")
    }
});

Solution

The Channel#send() method returns a promise, meaning you must wait for the action to finish before being able to define it. This can be done using either .then() or async and await. From personal preference, I regularly use the second option, although I have laid both options out for you.

Final Code

client.on('message', async userMessage => {
  if (userMessage.content === 'hi') 
    {
        /*
          botMessage = await userMessage.channel.send('hi there')
        */
        userMessage.channel.send('hi there').then(botMessage => {
          await botMessage.edit("hello");
          await botMessage.edit("what up");
          botMessage.edit("sup");
          botMessage.react(":clap:")
        })
    }
});


Answered By - Itamar S
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I fetch a message from a channel? discord.js

 July 11, 2022     discord, discord.js, fetch, message, node.js     No comments   

Issue

I reused a snipe command code to make this fetch command but that's not really my issue here.

I'm trying to fetch a message from a channel and post it in a designated channel, for example: Grab the message in X, and post it in Y. If that makes sense, all I have so far are:

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

module.exports = class FetchCommand extends BaseCommand {
  constructor() {
    super('fetch', 'fun', []);
  }

  async run(client, message, args) {
    const msg = client.snipes.get(message.channel.id);
    if (!msg) return message.channel.send('There are no messages to fetch.');
    
    const fetchEmbed = new Discord.MessageEmbed()
      .setAuthor(msg.author.tag, msg.author.displayAvatarURL())
      .setDescription(msg.content)
      .setTimestamp()

    message.channel.send(fetchEmbed);
  }
}

Help is very appreciated!

PS: As of right now, it fetches the messages from the channel it is running the command it. If I sent a message in X channel, and run the command in X channel it would fetch the message in the X channel. My goal is trying to fetch a message from a channel and post it in another channel.


Solution

If you have the channel ID and message ID: await message.guild.channels.cache.get('channel-id').messages.fetch('message-id') (async functions only)

If you just have the channel ID and want the last message that wasn't the command: (await message.guild.channels.cache.get('channel-id').messages.fetch({ count: 2 })).first()



Answered By - 0xLogN
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing