GithubHelp home page GithubHelp logo

namvr / discordbot-template Goto Github PK

View Code? Open in Web Editor NEW
306.0 11.0 75.0 178 KB

A boilerplate / template for discord.js v14 bots with 100% coverage of Discord API, command handler, error handler based on https://discordjs.guide/

Home Page: https://djs.docs.namanvrati.cf/

License: Apache License 2.0

JavaScript 100.00%
discord discord-js discord-bot-template discord-bot discordjs nodejs discord-api boilerplate-template command-handler error-handler

discordbot-template's Introduction

Welcome to NamVr Discord Bot Template 👋

Version Documentation Maintenance Twitter: namanvrati

An open source discord.js bot template which is based on official discord.js guide to get started on making your very personal discord bot!

Introduction

NamVr Discord Bot Template is an open source discord.js based bot template to get started on a new bot project. It is classic javascript template, not requiring any external dependencies unlike other famous frameworks. (This is not a framework!) You can scale any kind of bot project using this template. (single server based or multiple server based) It all depends on your creativity!

🛠️ NEW! This template now supports in-built typing (typescript-assistance) support too, which means you will get all typescript-like assistant in vanilla javascipt! (Visual Studio Code tested, working 100% as expected)

Features:

This template comes in with many in-built useful and flexible features, such as

Dynamic Command Handler:

  • My template comes in with a dynamic command handler! Using the command handler, you don't need to indulge in main bot files to create your very own command!
  • You can simply make command groups (categorized as folders) in the commands folder.
  • Your JavaScript commands goes inside respective category folders. A sample command is provided as ping command. You can use the same skeleton for all commands you want!

Dynamic Event Handler:

  • All events goes inside the events folder. You don't need to use client.on() in the main bot.js file to handle events.
  • Using simple skeleton code for events, you can make any amount of events in the events folder using the event handler.

Dynamic Trigger Handler:

  • Triggers occur when a specific "phrase" is said in a message content. For example, if you want your bot to react with ❤️ when someone say welcome in their message, you can do that with this trigger handler!
  • Trigger Handler also has the same skeleton structure as of command handler. The trigger handler is associated with the triggers folder. There are trigger categories, like reactions folder, in the trigger folder.
  • A sample trigger command is given in the hello.js trigger file.

Dynamic Slash Command Handler:

  • My template comes with a dynamic slash command handler with very easy to customize and make slash commands.
  • The commands, in the slashCommands folder, receive an CommandInteraction object. You can see the documentation of discord.js for all the properties and methods available.
  • IMPORTANT: In the template, we are sending the slash commands to discord to be registered only to 1 guild. That is because their are 2 types of slash commands, guild and global. Guild commands are restricted to 1 guild but whenever you update them, they take effect immediately, whereas global commands take upto 1 hour to take effect. So use guild commands in development and global commands for production.

Dynamic Buttons Interaction Handler:

  • This template comes with a dynamic button interaction handler to receive and process button interactions.
  • Buttons can be classified in two category folders.

Dynamic Modals Interaction Handler:

  • Easily handle incoming modal submittions using the template handler!
  • Modals can be categorized in different folders.

Dynamic Context Menu Handler:

  • All new addition to discord API is context menus! You can right click a user or message -> Apps to find these options!
  • This template will register all your context menu options and dynamically interact with them! Worth a try.

[NEW] Dynamic Autocomplete Interaction Request Handler:

  • Easily handle incoming autocomplete requests using the template handler!
  • Perfectly dynamic for all your needs!

Highly Customizable:

Using the template is so easy and fun, you would know. As the template does not rely on any external dependencies and written in javascript, it is highly customizable to any extend. There's no end to your creativity!

Open source and self-hosted:

It's yours, you have full control.

Install

npm install

Configuration

  • Rename config-example.json to config.json and fill the token and other values. Extend config.json according to your needs!

Run your bot

npm start

Support & Documentation

I'm working to make it more professional and easy to use for everyone. There will be a documentation out very soon.

WIP : https://djs.docs.namanvrati.cf/

Author

👤 Naman Vrati

Contributors

👤 Thank you so much to Krish Garg and Thomas Fournier for giving awesome contributions to the project.

🤝 Contributing

Contributions, issues and feature requests are welcome!
Feel free to check issues page. You can also take a look at the contributing guide.

Show your support

Give a ⭐️ if this project helped you! Star-ring the project gives me encouragement to continue it. You can also sponsor the project and get listed as a contributer! Thanks a lot.

📝 License

Copyright © 2021 Naman Vrati.
This project is Apache-2.0 licensed.


discordbot-template's People

Contributors

goudronviande24 avatar krishgarg avatar mr-leonerrr avatar namvr avatar stormpacer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

discordbot-template's Issues

[BUG] Select-Menus don't work

Select Menus don't work, can be fixed by adding the following into bot.js

/**********************************************************************/
// Registration of select-menus Interactions

/**
 * @type {String[]}
 * @description All Context Menu commands.
 */

 const selectMenus = fs.readdirSync("./interactions/select-menus");

 // Loop through all files and store select-menus in slashCommands collection.
 
 for (const folder of selectMenus) {
	 const files = fs
		 .readdirSync(`./interactions/select-menus/${folder}`)
		 .filter((file) => file.endsWith(".js"));
	 for (const file of files) {
		 const menus = require(`./interactions/select-menus/${folder}/${file}`);
		 const keyName = `${menus.id}`;
		 client.selectCommands.set(keyName, menus);
	 }
 }

Yes im too lazy to fork it and PR it

[BUG] guildMemberAdd not emitting

I tried to use the event but the print 'test' did not appear

/**
 * @file Context Interaction Handler
 * @author Krish Garg & Naman Vrati
 * @since 3.0.0
 * @version 3.3.0
 */

module.exports = {
	name: "guildMemberAdd",

	/**
	 * @description Executes when client is ready (bot initialization).
	 * @param {import('../typings').Client} client Main Application Client.
	 */
	execute(client, guild, member) {
        console.log('test')
	},
};

[HELP] Unwanted Slash Interactions Visible

When I run the bot and look at the slash commands through Discord, I see is has commands like /admin embed, /admin say, /info ping, and /info userinfo. I want to get rid of these but I can't find them anywhere in the bots files.
2021-10-17 (2)

[HELP] command permissions

How can you set role permissions for command usage? I'm not able to find it in the example ones except for ownerOnly

thanks

[BUG] Issue utilising trigger based commands when multiple exist

Issue
When attempting to register multiple files within either commands or triggers/reactions (only tested these two), the bot is only regestering the first command it locates within the file strucure (typically alphabetically). The only slash command the bot is capable of executing is the help command for instance.

To reproduce
I am using the repo exactly as is when cloned, except -of course- for adding the config.json file with my details. For testing purposes I provided my bot all bot permissions via the discord develeoper portal, as well as all privileged gateway intents. I figure the only difference between my codebase and yours is my node and npm versions (npm: 9.5.1, node: 18.16.0).

Expected behaviour
I expect copying the hello.js file in triggers/reactions to the same directory and renaming to hello2.js with different names exported from the module.exports would allow each to function when called upon with it's name (I am using unique names). Or even that the provided commands in the /command folder would work. Rather than simply the help command.

Screenshots
Please let me know if you need any!

Additional context
There's a posibility I am doing something wrong here, but I've been bashing my head against a wall trying to sort it out for a few hours and have tried multiple configurations before eventually establishing that it wouldnt even work directly after a git clone.

Slash Commands Permissions

Hi,
Now that we have .setDefaultMemberPermissions to set permissions for commands in SlashCommandBuilder for slash commands. How can I check if check if the user typing the command has the command? I was thinking about the help command to list all commands so I can only display available commands for the user typing the command.

Example if one command has .setDefaultMemberPermissions(PermissionFlagsBits.BanMembers), and a user without that permission types the help command in slash to list all available commands. How can we hide that command from being displayed as the user doesnt have access?

[BUG] Button issue

Describe the bug
I made a command with a button (a prefix command), when i try linking the button or pressing it without even linking it, it crashes and says that command is undefined in slashCreate, thing is, i didn't touch slashCreate while making this, and command is defined in that file, else no slash command would even work.
Error

TypeError: Cannot read properties of undefined (reading 'data')
    at Object.execute (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\events\slashCreate.js:27:30)
    at Client.<anonymous> (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\bot.js:60:35)
    at Client.emit (node:events:526:35)
    at InteractionCreateAction.handle (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\node_modules\discord.js\src\client\actions\InteractionCreate.js:97:12)
    at module.exports [as INTERACTION_CREATE] (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
    at WebSocketManager.handlePacket (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\node_modules\discord.js\src\client\websocket\WebSocketManager.js:355:31)
    at WebSocketManager.<anonymous> (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\node_modules\discord.js\src\client\websocket\WebSocketManager.js:239:12)
    at WebSocketManager.emit (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:282:31)
    at WebSocketShard.<anonymous> (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\node_modules\@discordjs\ws\dist\index.js:1173:51)
    at WebSocketShard.emit (C:\Users\ODHG1\Desktop\new dashybot\frankybot-remake\node_modules\@vladfrangu\async_event_emitter\dist\index.cjs:282:31)
Emitted 'error' event on Client instance at:
    at emitUnhandledRejectionOrErr (node:events:397:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:84:21)

Additional context
Here is my slashCreate (i only added cooldowns following the djs guide):

/**
 * @file Slash Command Interaction Handler
 * @author Naman Vrati
 * @since 3.0.0
 * @version 3.3.0
 */
const {Collection} = require("discord.js");

module.exports = {
	name: "interactionCreate",

	/**
	 * @description Executes when an interaction is created and handle it.
	 * @author Naman Vrati
	 * @param {import('discord.js').CommandInteraction & { client: import('../typings').Client }} interaction The interaction which was created
	 */

	async execute(interaction) {
		
		// Deconstructed client from interaction object.
		const { client } = interaction;

		// Checks if the interaction is a command (to prevent weird bugs)
		const { cooldowns } = interaction.client;
		const command = client.slashCommands.get(interaction.commandName);

		if (!cooldowns.has(command.data.name)) {
			cooldowns.set(command.data.name, new Collection());
		}

		const now = Date.now();
		const timestamps = cooldowns.get(command.data.name);
		const defaultCooldownDuration = 3;
		const cooldownAmount = (command.cooldown ?? defaultCooldownDuration) * 1_000;

		if (timestamps.has(interaction.user.id)) {
			const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount;
		
			if (now < expirationTime) {
				const expiredTimestamp = Math.round(expirationTime / 1_000);
				return interaction.reply({ content: `Please wait, you are on a cooldown for \`${command.data.name}\`. You can use it again <t:${expiredTimestamp}:R>.`, ephemeral: true });
			}
		}
				
		timestamps.set(interaction.user.id, now);
		setTimeout(() => timestamps.delete(interaction.user.id), cooldownAmount);

		if (!interaction.isChatInputCommand()) return;


		// If the interaction is not a command in cache.

		if (!command) return;

		// A try to executes the interaction.

		try {
			await command.execute(interaction);
		} catch (err) {
			console.error(err);
			await interaction.reply({
				content: "There was an issue while executing that command!",
				ephemeral: true,
			});
		}


	},
};

Line 60 in bot.js is async (...args) => await event.execute(...args, client)
Whole loop would be

for (const file of eventFiles) {
	const event = require(`./events/${file}`);
	if (event.once) {
		client.once(event.name, (...args) => event.execute(...args, client));
	} else {
		client.on(
			event.name,
			async (...args) => await event.execute(...args, client)
		);
	}
}

[BUG] guildMemberUpdate not emitting

Hi,

I've placed a guildMemberUpdate.js file under events, with this being the basic code in it:

const { MessageEmbed } = require("discord.js");

module.exports = {
    name: "guildMemberUpdate",

    execute: async (oldMember, newMember) => {
        console.log("test");
    },
};

for some reason, "test" is not being printed in the console whenever i remove or add a role to a member

[BUG] START BOT

Describe the bug
PROBLEM IN START BOT

To reproduce
npm i
nodemon bot.js

Expected behaviour
Problem in start bot

Screenshots
image

image

Add Mongo Support

Suggestion
Not a bug, Maybe add mongo support to the template or please describe how i can do it.

[BUG] The optional field in the help slash command is useless

Describe the bug
When you use the help slash command with the "command" option, it changes nothing and still responds only the "general help".

To reproduce

  • Start the bot
  • Execute /help [anything]
  • Whatever you write, it's still going to answer the same as if you put nothing

Expected behaviour
It should do like the traditional !help command, general help when no options, and help about a specific command when given.

Suggestion: Add sharding

It'd be great if you could add sharding to this! Either auto or manual(like an option for us in config.json to enable/disable sharding).

There is a package I know of, Discord-Hybrid-Sharding, that allows you to save a lot of resources while sharding(up to 60% resources
can be saved!). Maybe it could be used?

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.