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

ant-messenger

v0.0.8-c

Published

AntMessenger: small but poweful framework for facebook messenger bots.

Downloads

4

Readme

List of content

About:

Basic features

  • Status-based user dialog stage managment.
  • Easy-to-use.
  • Webhook & polling support.
  • All in one: all API methods, flexible dialog flow control.
  • w/o functional overkill, nothing extra.

Instalation

  • Using NPM:
    npm install ant-messenger
  • Using Yarn:
    yarn add ant-messenger

Basic usage

Ant:Messenger require to provide 2 basic status managment async methods: for getting status to user by messenger user's id, and for setting it.
Feel free to chose storing way (architecture, database etc.). We require next interfaces only:

getStatus(id: string): Promise<string>;
setStatus(id: string, status: string): Promise<any>;

Just put in on Ant:Messenger initialization with access token (how to get token?):

const { AntMessenger } = require('ant-messenger');

const token = '...'; // Your access token

const Ant = new AntMessenger(token, { 
    getStatus: (id) => { ... }, 
    setStatus: (id, status) => { ... },
});

Explore quick start example using MongoDB + mongoose.

Facebook Messenger use webhook for API communication, so you need to configure it:

  1. Create Express server:
const express = require('express');
const app = express();
  1. Add router using webhook url:
const webhookUrl = '/webhook'; // webhook url here
app.get(webhookUrl, Ant.validateServer);
app.post(webhookUrl, (req, res) => {
    const payload = req.body;
    Ant.inspect(payload);
    res.status(200).send();
})
  1. Run your server:
app.listen(port);

Now you ready to use Ant:Messenger.
Let's add start dialog handler (/start command, called either when command was send as text or when new user join to chat with bot):

Ant.command('/start', async id => {
    await Ant.api.sendTextMessage(id, 'Hi!');
})

Your bot ready to start. Run script and make sure it works:

Ant anatomy

Messenger API

See Ant.api

All api methods like

Ant.api.sendQuickReplyMessage(id: string, text: string, buttons?: Button[]): Promise;
Ant.api.toggleTyping(id: string, toggle: boolean): Promise;

... and so on. See full list in fb-messenger-bot-api dependency.

Error handling

Ant.on('error', (err: Error) => { ... })

error will fire on any error. If error caused during user's scenario, error will have sender_id extra field.

Statuses

Set status for user:

await Ant.status(id, 'my_status');

And add listener for this status:

Ant.add('image', 'my_status', (id, image) => { ... })

First argument is user interaction type, second - our status, third - callback.
Callback will invoke every time when user with this status send photo to bot.
Full list of available types and callbacks you can check here.

Commands

Add command handlers using Ant.command:

Ant.command(command, (chat_id, params) => { ... })

Command may contain / if needed (example: /start). Callback will invoke every time when user send this command to chat. Status will be ignored (works with any user's status).

Ant.command support url params for commant that will returns as params in callback. Empty object will returns if params not provided.
For example:

| User input | params value | |------------|----------------| | /cmd | {} | | /cmd?item=apple&amount=2 | { item: 'apple', amount: '2' } |

Notice: all param values are strings. You need to parse params by youself if you need to support other types in command params.

Masks

You can use multi-leveled statuses using level separator (: by default). It can be changed using maskSeparator field in initial config.
For example:

await Ant.status(chat_id, 'buy:fruit:apple')

Provided status has 3 levels: action (buy), category (fruit), item (apple) and can be used during user interaction with shopping cart.
You not need to set listeners using Ant.add for each item on third level. You can use mask (*):

// Mask value (item, in our case) will be provided as third callback parameter.
Ant.add('text_message', 'buy:fruit:*', (id, text, item) => {
    console.log(item) // apple
})

Callback will invoke for any text message send by user with any item in status.

Builders

See Ant.Types

Ant:Messenger simplifies api methods usage with builders.
Let's check an example:

const GenericTemplate = Ant.Types.GenericTemplate;
const GenericElement  = Ant.Types.GenericElement;
const DefaultAction   = Ant.Types.DefaultAction;
const Button          = Ant.Types.Button;
await Ant.api.sendTemplateMessage(id, GenericTemplate([
        GenericElement('Javascript', js_image, 'Reddit: r/javasript', 
            DefaultAction('https://www.reddit.com/r/javascript/'), [
                Button('🔎 To r/javasript', 'site', 'web_url', 'https://www.reddit.com/r/javascript/')
            ]
        ),
        GenericElement('Typescript', ts_image, 'Reddit: r/typescript', 
            DefaultAction('https://www.reddit.com/r/typescript/'), [
                Button('🔎 To r/typescript', 'site', 'web_url', 'https://www.reddit.com/r/typescript/')
            ]
        )
    ]));

Here we are using builders instead of define structure object.
This code will send generic template with two cards:

Native API payload handling

Ant:Messenger handle API payload by itself inside the Ant.inspect method (see basic usage).
You can handle payload by yourself:

  1. Working with native data that was sent on webhook:
app.post(webhookUrl, (req, res) => {
    console.log(req.body); // API data
})
  1. Working with parsed API payload:
app.post(webhookUrl, (req, res) => {
    const payload = Ant.parsePayload(req.body);
    console.log(payload); // parsed API payload
})

Deep linking

Facebook Messenger supports deep linking so you can create link like:

http://m.me/<PAGE_NAME>?ref=<REF_PARAM>

which start user scenario with ref value. You can handle context easily:

// Via http://m.me/yourbot?ref=value
Ant.command('/start', async (id, params) => {
    console.log(params); // { ref: 'value' }
    console.log(params.ref) // 'value'
})

Ant.command listener provide params object as second parameter. It will be empty when user has been connected to bot without deep link.

Config

Ant:Telegram init config contain next fields:

| field | type | description | |-------|------|-------------| | setStatus | | See basic usage | getStatus | | See basic usage | maskSeparator | string | See masks | getStartedToken | string | Payload string that Messenger API will use when new user join to chat with bot. GET_STARTED as default.