Coder Social home page Coder Social logo

muricans / discord-embedbuilder Goto Github PK

View Code? Open in Web Editor NEW
4.0 3.0 2.0 115 KB

npm module to make creating embeds with mutliple pages a little bit easier

License: MIT License

TypeScript 49.66% JavaScript 50.34%
discord-js typescript npm-package embeds

discord-embedbuilder's Introduction

discord-embedbuilder

dependencies Status

NPM

npm module to make creating embeds with mutliple pages a little bit easier

latest version documentation

master documentation

Quick Install

discord-embedbuilder v4.0.0(current stable)

npm install discord-embedbuilder

discord-embedbuilder master (v4.0.0)

npm install muricans/discord-embedbuilder

discord-embedbuilder uses the latest stable version of discord.js (14.6.0)

Methods

All methods that have the same names as the ones from EmbedBuilder do the same actions as those, but applies it to all of the pages, which should override their values.

usePages(use)

If this is set to false, the builder will not use the next, back, last, first, stop emotes.


changeChannel(channel)

Change the current channel.

Warning: This should not be used to set the channel. You can set the channel in the constructor.


setEmbeds(embeds)

The array of EmbedBuilders put here will be the ones that are used to make the pages. You can also add embeds using addEmbed.


addEmbed(embed)

Adds an EmbedBuilder to the array of embeds.


concatEmbeds(embeds)

Puts the array of embeds given at the end of the current embeds array.


setEndColor(color)

When the collection has ended, and no other custom color is being used, this will be the color the embed is set to. Default is 0xE21717


setTime(time)

This will set how long the builder should listen for emotes. Make sure to set your time as milliseconds.


addTime(time)

Use after the embed has been built. Will increase the amount of time the collector is active before it stops.


resetTimer(time?)

Resets the timer to either the time already set, or a new time given.


addTimeOnPage(time)

Whenever the builder changes it's page, it will add specified amount of time (ms) to the current running timer.


resetTimerOnPage()

Whenever the builder changes it's page, it will reset the timer to the current set time.


addEmoji(emoji, (sent, page, builder, emoji))

This will insert the provided emoji into the builder, and when it is clicked it will perform the action that is provided.

builder.addEmoji('❗', (sent, page, emoji) => {
    sent.delete();
    builder.cancel();
    sent.channel.send(`A new message${emoji}\nThe page you were on before was ${page}`);
});

addEmojis(emojis)

Add multiple emojis to do different actions.

builder.addEmojis([{
    '❗': (sent, page, emoji) => {
        builder.cancel();
        sent.delete();
        sent.channel.send(`A new message${emoji}\nThe page you were on before was ${page}`);
    },
}]);

deleteEmoji(emoji)

Deletes an emoji from the list of emojis.


cancel(callback?)

Cancels the builder before the timer ends.

If a callback is provided, it will execute after the builder has canceled.


showPageNumber(use)

If set to true (by default it is true), it will show the current page on the footer of the embed. (Page x/y)


setPageFormat(format)

If showing page numbers, this is the format that will be used.

By default format is %p/%m which converts to current/max.


calculatePages(data, dataPerPage, insert)

This calculates pages for the builder to work with.

/*
This will generate a builder with a data length set to an array.
It will have 10 fields per page, which will all be inline, containing username and points data.
*/
embedBuilder.calculatePages(users.length, 10, (embed, i) => {
    embed.addField(users[i].username, users[i].points, true);
});

calculatePagesAsync(data, dataPerPage, insert)

Async version of calculatePages

Makes the page calculator wait for operations to finish.

await embedBuilder.calculatePagesAsync(users.length, 10, async (embed, i) => {
    const user = await getSomeUser(users[i]);
    embed.addField(user.username, user.points, true);
});

updatePage(page)

Updates the current page to the one set there. This checks if the page is valid itself. Make sure the first page of the builder has already gone through before using this.


setPageEmoji(emoji, newEmoji)

Replaces current type of emoji given with the new emoji provided.

Types allowed: back, first, stop, last, next


awaitPageUpdate(user, options)

options

Create an updater to await responses from a user, then set the builders current page to the page given.


defaultReactions(reactions)

The reactions the bot will use. If this method is not used in the builder, the bot will automatically add all reactions.

/*
* This builder will only use the stop and back emojis. 
* Using this also allows you to rearrange the order in which the bot will react with the emojis.
*/
embedBuilder.defaultReactions(['stop', 'back']);

Events

Emitted from build() when the first page has finished building.

Emitted from build() when the timer has run out, or the collector is canceled in any way.

Emitted from from build() when the builder has changed pages. Sets the new page for the bot.

Emitted from build() before the first embed page has been sent in Discord.

PageUpdater

PageUpdater documentation can be found here.

Example

First import discord-embedbuilder into your project.

const {
    PageEmbedBuilder,
 } = require('discord-embedbuilder');

Create a command or some way to get a channel to pass through the builder. If you are unsure on how to make a command, checking this out might be helpful.

Next make your PageEmbedBuilder.

client.on('message', message => {
    const builder = new PageEmbedBuilder()
        .setChannel(message.channel)
        .setTime(60000); // Time is in milliseconds
    const myEmbedArray = [
        new Discord.EmbedBuilder().addFields({name:'1st', value:'page'}),
        new Discord.EmbedBuilder().addFields({name:'2nd', value:'page'}), 
        new Discord.EmbedBuilder().addFields({name:'3rd', value:'page'}),
    ];
    builder
        .setEmbeds(myEmbedArray)
        .setTitle('This title stays the same on all pages!')
        .build(); // No need to send a message, building it will automatically do it.
});

Here's an example taken from my bot rolesbot

const rolebot = require('../rolebot');
const fs = require('fs');
const {
    PageEmbedBuilder,
} = require('discord-embedbuilder');

module.exports = {
    name: 'list',
    description: 'Refreshes and lists all currently active role react messages.',
    permissions: ['MANAGE_GUILD'],
    async execute(message) {
        rolebot.refreshActiveMessagesFor(message.guild.id);
        const messages = JSON.parse(fs.readFileSync('./messages.json', 'utf-8'));
        const list = messages.ids.filter(v => v.guildId === message.guild.id);
        if (list.length > 0) {
            const builder = new PageEmbedBuilder(message.channel);
            const guild = await message.guild.fetch();
            builder.calculatePages(list.length, 8, async (embed, i) => {
                    const channelName = guild.channels.cache.get(list[i].channelId);
                    const roleName = guild.roles.cache.get(list[i].roleId);
                    embed.addField("Message ID", list[i].messageId, true);
                    embed.addField("Channel", `${channelName}`, true);
                    embed.addField("Role", `${roleName}`, true);
                })
                .setTitle("List of All Active Messages")
                .build();
        } else {
            message.channel.send(`${message.author} No messages are currently registered in this guild!`);
        }
    },
};

discord-embedbuilder's People

Contributors

experibass avatar felanbird avatar mrzillagold avatar muricans avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

discord-embedbuilder's Issues

Add support for .addFields()

Describe the bug
When trying to use .addFields() for attaching an Field array we get an error.
It seems that this feature is not implemented in the library.

Screenshots
If applicable, add screenshots to help explain your problem.
image

Documentation .addFields()

Add method to change default reactions

Is your feature request related to a problem? Please describe.
At the moment, the builder is constantly adding 5 certain default reactions, we cannot affect them in any way if we do not need them.

Describe the solution you'd like
Add a new method in which we can list the default reactions we need, if this method is not used add all the default reactions

new Builder().defaultActions(["stop", "back"]);

This approach will also allow us to change the default arrangement of reactions.

Error - Cannot send an empty message

Discord now throws an error - Cannot send an empty message

using addFields command with an array of fields, but now can't see this command anywhere in description.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.