npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

discord-message-handler

v2.1.1

Published

Message and command handler for discord.js bots and applications.

Downloads

26

Readme

About

discord-message-handler is a module written to simplify message and command handling for discord.js bots and applications.

Table of Contents

Installation

Simply navigate to your project's folder and type npm install discord-message-handler --save on the command line.

Usage

To start using the module you must require it into you script like this (changed in 2.0)

Old style require:

const MessageHandler = require('discord-message-handler').MessageHandler;
const handler = new MessageHandler();

ES2015:

const { MessageHandler } = require('discord-message-handler');
const handler = new MessageHandler();

Typescript:

import { MessageHandler } from 'discord-message-handler';
const handler = new MessageHandler();

Define rules for the message handler (shown later in the next sections) then parse messages in the as they arrive:

client.on('message', message => {
    handler.handleMessage(message);
});

Simple message handlers

handler.whenMessageContainsWord("shrug").reply("¯\\_(ツ)_/¯");
handler.whenMessageContains("lol").sometimes(33).reply("kek"); // 33% chance
handler.whenMessageContainsExact("dota").replyOne(["volvo pls", "rip doto"]);
handler.whenMessageContainsOne(["br", "brazil"]).reply("huehue");
handler.whenMessageStartsWith("help").then(message => doSomething(message));

Command handler

handler.onCommand("/doit").do((args, rawArgs, message) => {
    message.channel.send(`Doing something for ${message.author}...`)
});

Commands with alias

handler.onCommand("/information").alias("/info").alias("/i").do((args) => {
    doSomething(args[0]);
});

Commands with usage info

handler 
    .onCommand("/info")
    .minArgs(2)
    .whenInvalid("Invalid command. Usage: /info <a> <b>")
    .do((args) => {
        doSomething(args[0]);
        doSomethingElse(args[1]);
    });

Commands with regex validation

handler
    .onCommand("!roll")
    .minArgs(1)
    .matches(/(\d+)?\s?d(6|20|100)/g)
    .whenInvalid("Invalid command. Usage: `!roll <number of dices> d<type of dice>`. Valid dices: d6, d20, d100")
    .do((args) => {
        // Dice roll logic
    })

Command invocation deletion

You can automatically delete the message that triggered a command using the deleteInvocation method. The time argument is optional, and if absent the message will be deleted imediatelly.

// User's message will be deleted after 1500ms
handler.onCommand("/afk").deleteInvocation(1500).then((message) => {
    message.channel.send(`${message.author} is now AFK.`);
});

Example handling messages across multiple files

Consider you have the following structure:

├── commands
│   ├── greetings.js
│   └── helper.js
└── index.js

greetings.js:

module.exports.setup = function(handler) {
    handler.onCommand("/help").reply("<some helpful message>");
    handler.onCommand("/ping").reply("<actually calculate ping>");
}

helper.js:

const { MessageHandler } = require('discord-message-handler');

module.exports.setup = function(handler) {
    /* [Optional] You can recreate the handler using the parent context so your IDE will properly give out suggestions for the handler */
    const myhandler = new MessageHandler(handler);
    myhandler.whenMessageContainsWord("hey").reply("yo!");
    myhandler.whenMessageContainsWord("hi").reply("oh hi there :)");
}

index.js:

const { MessageHandler } = require('discord-message-handler');
const greetingsCommands = require('./commands/greetings');
const helperCommands = require('./commands/helper')

const handler = new MessageHandler();
greetingsCommands.setup(handler);
helperCommands.setup(handler);

// (...) code continues

Case sensitivity

In case you want message filters to be case sensitive you just need to call this function once:

handler.setCaseSensitive(true);

By default all message filters are case insensitive. (false)

Logging

To enable logging call handler.enableLogging() and pass a function to handle logs.

handler.enableLogging((filterType, filter, message) => {
    console.log(`${new Date().toISOString()} ${filterType}: ${filter} - "${message.content}"`);
});

Contributing

Feel free to send a pull request or open an issue if something is not working as intended or you belive could be better.