Skip to content

Instantly share code, notes, and snippets.

@Max2408
Last active May 31, 2021 09:00
Show Gist options
  • Save Max2408/1b66ebade7eb1de449a2b926f0b60462 to your computer and use it in GitHub Desktop.
Save Max2408/1b66ebade7eb1de449a2b926f0b60462 to your computer and use it in GitHub Desktop.
How to Use Buttons in Discord.js With Discord API

Using Buttons in Discord.js Using Discord API

As you know discord.js will support discord buttons later this year, so it is hard for discordjs bot developers to use buttons in their bots. There are some npm packages but they are not customizable and not reliable.

So i will be showing you how can you create buttons in discord.js using Discord API v9

Setting Everything Up

So before we start making buttons, we have to do some default setup.

  const Discord = require('discord.js')
  const client = new Discord.Client()
  const fetch = require('node-fetch')

  token = "YOUR_SUPER_SECRET_TOKEN"

  client.login(token)

This will setup your bot and make it online.

Fetching API to use it in our bot

Creating a Button Class

  // Create New Button
  class Button {
    constructor() {
      
  }
    new(name, style, buttonId) {
        let component = {
            type: 2,
            label: name,
            style: style,
            custom_id: buttonId
        }

        return component
    }
}

Creating a Fuction To Send Messages Along with Buttons

    // Message Send With Buttons
    async function sendMessagesWithButton(message , channelId , ...buttons) {

    let body = {
        content : message,
        components: [
            {
                type: 1,
                components: buttons
            }
        ]
    }

    let data = await fetch(`https://discordapp.com/api/v9/channels/${channelId}/messages` , {
        method : "POST",
        body : JSON.stringify(body),
        headers : {
            "Authorization" : `Bot ${token}`,
            'Content-Type': 'application/json'
        }
        }).then(res => res.json())
        .then(json => { return json});
}

Creating a Function to send Embeds and Buttons

    // Message Send With Buttons
    async function sendEmbedWithButton(embed, channelId , ...buttons) {

    let body = {
        embed : {
            description : embed.description,
            title : embed.title,
            image : embed.image,
            author : embed.author,
            provider : embed.author,
            files : embed.files,
            fields: embed.fields,
            timestamp : embed.timestamp,
            color: embed.color,
            url: embed.url,
            type : embed.type
        },
        components: [
            {
                type: 1,
                components: buttons
            }
        ]
    }

    let data = await fetch(`https://discordapp.com/api/v9/channels/${channelId}/messages` , {
        method : "POST",
        body : JSON.stringify(body),
        headers : {
            "Authorization" : `Bot ${token}`,
            'Content-Type': 'application/json'
        }
     }).then(res => res.json())
     .then(json => { return json});
}

Creating a Function to Handle Interactions

  // Interaction for Buttons
  async function interaction(buttonId , callback){
    client.ws.on('INTERACTION_CREATE', async interaction => {
        if(interaction.data.custom_id === buttonId){
            callback(interaction)
        }
     })
   }

Creating a Function to send callback messages

  // Send Followup Messages
  async function btnCallbackMessage(message , data) {
    client.api.interactions(data.id, data.token).callback.post({
        data: {
          type: 4,
          data: {
            content: message
          }
        }
     })
   }

Creating a Function to send callback embed

// Send Followup Message Embed
  async function btnCallbackEmbed(embed , data) {

      async function createAPIMessage(interaction, content) {
          const apiMessage = await Discord.APIMessage.create(client.channels.resolve(interaction.channel_id), content)
              .resolveData()
              .resolveFiles();

          return { ...apiMessage.data, files: apiMessage.files };
      }

      client.api.interactions(data.id, data.token).callback.post({
          data: {
            type: 4,
            data:  await createAPIMessage(data, embed)
          }
      })
  }

A Simple Example to use all the above the Functions

  // Creating a Message Listener
  client.on("message" , async(message) => {
      // Creating a Command
      if(message.content.toLowerCase().startsWith(`$btn`)){
         // Creating Buttons (You can create as many buttons you want)
         let button1 = new Button().new("Test" , 1 , "button1") 

         //Sending Message With Buttons 
         sendMessagesWithButton("Testing Buttons" , message.channel.id , button1)

          // Handling Button
         interaction("button1" , (data) => {
             // Responding with a Embed
             let embed = new Discord.MessageEmbed()
             .setDescription(`Hello World!`)

              btnCallbackEmbed(embed , data)
         })
      }
  })

More Examples

coming soon....

If you come across any problem feel free to Dm me on discord </Max>#5589 or join my Discord Server to Contact Me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment