snocord

A Discord.js framework, used by SnoBot.

Usage no npm install needed!

<script type="module">
  import snocord from 'https://cdn.skypack.dev/snocord';
</script>

README

SnoCord

A Discord.js framework used by SnoBot.

Usage Docs:

Classes

Bot

Main class which everything starts from.

Command

Child class of Response - Provides additional functionality for commands. Default priority: 5

Response

Generic class which handles responses to user messages.

Functions

parseCommand(bot, message, prefixOverride)

Parses a message object into command objects.

isCommandSyntax(bot, message, prefixOverride)

Checks if the message is syntaxically a command. Does not check if it is an existing command.

isCommand(bot, message, prefixOverride, commandName)

Checks if the message is a given command.

capitaliseFirstLetter(string)

Capitalise first letter of text.

sortJson(obj)

Sorts keys of object alphabetically

msToTime(duration)string

convert ms to time string

Bot

Main class which everything starts from.

Kind: global class

new Bot()

Creates a new Bot instance.

bot.mention

Gets a regular expression that will match a message mention directed at this bot

Kind: instance property of Bot

bot.init(token, [callback]) ⇒ Promise.<void>

Intializes the Bot instance.

Kind: instance method of Bot

Param Type Description
token string The Discord token to log in with.
[callback] Object An object defining functions to call before or after the bot connects to the discord API

Example

new Bot(options).init({
    async preInit() {
        // Do stuff before connecting to the API
    },
    async postInit() {
        // Do stuff after connecting to the API
    }
});

bot.setConfig(config)

Set the config object for the bot.

Kind: instance method of Bot

Param Type Description
config object Config object.

bot.tryResponses(message) ⇒ Array.<Response>

Loops through each response, attempting to find one that will trigger on the given message.

Kind: instance method of Bot
Returns: Array.<Response> - - Array of all matching responses.

Param Type Description
message Message The message

bot.addResponse(trigger, funct, priority)

Adds Response object to the bot's set of responses.

Kind: instance method of Bot

Param Type Default Description
trigger RegExp | function The RegExp pattern to match to trigger this response OR Custom checking function which takes the message object and returns boolean.
funct function Code to run when triggered. Will pass an object containing message (Discord#Message), respond function, messageOptions.
priority integer 0 (Optional) The priority value for the response. When two or more responses match, only those with the highest priority value will run. Defaults to 0.

Example

bot.addResponse(() => {return true;}, (r) => {
     r.respond("I like responding.")
  }, -1);

 bot.addResponse(/^(hello bot)/i, (r) => r.respond("hi human"));

bot.addCommand(commandWord, aliases, info, funct, priority)

Kind: instance method of Bot

Param Type Description
commandWord string The word which will execute the command.
aliases Array.<string> Array of all command aliases.
info object Info metadata object for command.
funct function Code to run when triggered. Will pass an object containing message (Discord#Message), respond function, messageOptions.
priority integer (Optional) The priority value for the response. When two or more responses match, only those with the highest priority value will run. Defaults to 0.

Example

bot.addCommand("help",(r)=>{r.respond(`I won't help you, ${r.message.author}`)})

bot.addCommandClass(commandClass)

Add a command using a command class, similar to what the command handler does.

Kind: instance method of Bot

Param Type Description
commandClass Command Class for this command

Example

bot.addCommandClass(require('./commands/SomeCommand.js'));
bot.addCommandClass(SomeCommandClass);

bot.addCommandHandler(path)

Add a command handler to a specified directory.

Kind: instance method of Bot

Param Type Description
path string The local path to the directory containing only command class files.

Example

bot.addCommandHandler('./commands/');

bot.addCustomResponse(response)

Add a custom response object to the list. (Not recommended for standard response types)

Kind: instance method of Bot

Param Type Description
response Response Object of Response or class which extends response.

bot.getAllCommands() ⇒

Get all added commands.

Kind: instance method of Bot
Returns: array of Command instances.

bot.addHelpCommand()

Adds the core help command to the commands.

Kind: instance method of Bot

bot.addPrefixCommands()

Adds the core 'prefix' and 'resetprefix' commands to the commands.

Kind: instance method of Bot

bot.addCoreCommands()

Enables all of the built-in core commands.

Kind: instance method of Bot

bot.setCustomGuildPrefix(guildId, prefix) ⇒ Promise

Set custom prefix for a specific guild.

Kind: instance method of Bot
Returns: Promise - if the setting is successful.

Param Type Description
guildId string ID of Discord guild.
prefix string custom prefix for this guild or false for no custom prefix.

bot.getPrefix(guildId) ⇒ Promise

Get the custom prefix if the guild has one, else return default prefix.

Kind: instance method of Bot
Returns: Promise - promise resolving to the guild's prefix.

Param Type Description
guildId string ID of the guild in which the command is run.

bot.setPresence(presence)

Set the bot's presence (status). Refereshed every hour.

Kind: instance method of Bot

Param Type Description
presence Discord#PresenceData Data for presence

Bot.defaultConfigOptions

Default options to fall back on if the config object exists but doesn't have a given option.

Kind: static property of Bot

defaultConfigOptions.commandCooldown

Prefixing the message with a ping to the bot will work the same as using the bot's prefix.

Kind: static property of defaultConfigOptions

Command

Child class of Response - Provides additional functionality for commands. Default priority: 5

Kind: global class

command.run(message)

Run the response code to a message.

Kind: instance method of Command

Param Type Description
message Discord#Message Message object to respond to.

command.isRunnableBy(member)

Check if the member has the required permissions to run this command.

Kind: instance method of Command

Param Type Description
member Discord#GuildMember Guild member to check.

command.runCooldown(message, bot, cooldownStamp)

Send message if user on cooldown

Kind: instance method of Command

Param Type Description
message Discord#message message
bot Bot bot
cooldownStamp number stamp of time after cooldown is over

Response

Generic class which handles responses to user messages.

Kind: global class

new Response(trigger, funct)

Creates Response object.

Param Type Description
trigger RegExp | function The RegExp pattern to match to trigger this response OR Custom checking function which takes the message object and returns boolean.
funct function Code to run when triggered. Will pass response object.

response._respond(message, response, messageOptions)

Kind: instance method of Response

Param Type Description
message Discord#Message Message object to respond to.
response string String text to send in response.
messageOptions Discord#MessageOptions Options provided when sending or editing a message.

response.run(message)

Run the response code to a message.

Kind: instance method of Response

Param Type Description
message Discord#Message Message object to respond to.

response.isTriggered(message)

Checks whether the trigger pattern matches the message.

Kind: instance method of Response

Param Type Description
message Discord#Message The message object to check.

response.runCooldown(message, bot, cooldownStamp)

Do nothing if user on cooldown

Kind: instance method of Response

Param Type Description
message Discord#message message
bot Bot bot
cooldownStamp number stamp of time after cooldown is over

parseCommand(bot, message, prefixOverride)

Parses a message object into command objects.

Kind: global function

Param Type Description
bot Bot The bot instance.
message Discord#Message The message object to parse.message
prefixOverride string Optional custom prefix.

isCommandSyntax(bot, message, prefixOverride)

Checks if the message is syntaxically a command. Does not check if it is an existing command.

Kind: global function

Param Type Description
bot Bot The bot instance.
message Discord#Message The message object to parse.message
prefixOverride string Optional custom prefix.

isCommand(bot, message, prefixOverride, commandName)

Checks if the message is a given command.

Kind: global function

Param Type Description
bot Bot The bot instance.
message Discord#Message The message object to parse.message
prefixOverride string Optional custom prefix.
commandName string Name of command.

capitaliseFirstLetter(string)

Capitalise first letter of text.

Kind: global function

Param Type Description
string String text

sortJson(obj) ⇒

Sorts keys of object alphabetically

Kind: global function
Returns: sorted object

Param Type Description
obj object object to sort

msToTime(duration) ⇒ string

convert ms to time string

Kind: global function
Returns: string - time

Param Type Description
duration number time in ms

Examples

Sample command using the command handler:

class ExampleCommand
{
    constructor()
    {
        this.metadata = {
            commandWord: 'sample',
            aliases: [],
            description: 'Adds num1 and num2 and pings you in return that many times. Requires ban permission for no reason!',
            usage: 'num1 num2',
            permissions: ['BAN_MEMBERS'],
            ownerOnly: false
        };
    }

    run(sno)
    {
        //sno contains { bot, message, command, args, argsText, respond }
        let num1 = sno.args[0] * 1;
        let num2 = sno.args[1] * 1;
        let sum = Math.floor(num1 + num2);
        if(sum > 0){
            if (sum > 1000){sum = 1000;}
            let message = "";
            for(let i = 0; i < sum; i++){
                message += sno.message.author + " "; 
            }
            sno.respond(message);
        }else{
            sno.respond("I can't ping you less than 0 times!");
        }

    }
}
module.exports = ExampleCommand;

Sample config file:

{
    "name": "Some Bot",
    "owner": "Some User",
    "ownerID": "000000000000000000",
    "description": "A SnoCord bot",
    "token": "",
    "prefix": "!",
    "mentionAsPrefix": true,
    "commandCooldown": 2000
}