All Projects → crisboarna → fb-messenger-bot-api

crisboarna / fb-messenger-bot-api

Licence: MIT license
NodeJS Facebook Messenger API for bots to send messages and setup events to Facebook.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to fb-messenger-bot-api

Facepy
Facepy makes it really easy to use Facebook's Graph API with Python
Stars: ✭ 845 (+2813.79%)
Mutual labels:  facebook, api-client
lpconnector
Python client for syncing LastPass Enterprise with a remote directory over LDAP
Stars: ✭ 14 (-51.72%)
Mutual labels:  api-client
meta-tag-gen
Generate HTML code optimal for social media, SEO, mobile. Uses web standards from Open Graph (Facebook) and Twitter to provide optimal results. Also generates social media posts.
Stars: ✭ 24 (-17.24%)
Mutual labels:  facebook
fs-pochta-api
Библиотека для работы с API Почты России
Stars: ✭ 15 (-48.28%)
Mutual labels:  api-client
python-sonarqube-api
Python wrapper for the SonarQube (Community Edition and Enterprise Edition) and SonarCloud API.
Stars: ✭ 107 (+268.97%)
Mutual labels:  api-client
AIRFacebook-ANE
Native extension for Adobe AIR providing cross-platform API to Facebook SDK 4
Stars: ✭ 19 (-34.48%)
Mutual labels:  facebook
pyinaturalist
Python client for iNaturalist
Stars: ✭ 68 (+134.48%)
Mutual labels:  api-client
facebook-video-downloader
Facebook Video Downloader Website Script written in PHP
Stars: ✭ 22 (-24.14%)
Mutual labels:  facebook
FacebookTrackingRemoval
Browser extension that removes ads and the user interaction tracking from content on Facebook
Stars: ✭ 88 (+203.45%)
Mutual labels:  facebook
clickupython
A client for working with the ClickUp API V2
Stars: ✭ 30 (+3.45%)
Mutual labels:  api-client
facebook-bot-autoresponder
Facebook bot that automatically responds to the comments of a certain post
Stars: ✭ 90 (+210.34%)
Mutual labels:  facebook
CoinGecko
A C++20 library for CoinGecko--a cryptocurrency data service.
Stars: ✭ 69 (+137.93%)
Mutual labels:  api-client
AlphaVantage.Net
.Net client library for Alpha Vantage API
Stars: ✭ 65 (+124.14%)
Mutual labels:  api-client
zoho-crm-php
An API wrapper library for Zoho CRM, written in PHP.
Stars: ✭ 15 (-48.28%)
Mutual labels:  api-client
adyen-python-api-library
Adyen API Library for Python
Stars: ✭ 41 (+41.38%)
Mutual labels:  api-client
bitmex-client-websocket
🛠️ C# client for Bitmex websocket API
Stars: ✭ 60 (+106.9%)
Mutual labels:  api-client
Yandex.Music.Api
Client Yandex.Music.Api for Yandex.Music
Stars: ✭ 53 (+82.76%)
Mutual labels:  api-client
FrameBot
An open source template to kickstart your own facebook framebot!
Stars: ✭ 89 (+206.9%)
Mutual labels:  facebook
Skeleton
Skeleton is a Social Engineering tool attack switcher
Stars: ✭ 44 (+51.72%)
Mutual labels:  facebook
AutoMeter-API
AutoMeter-API是一款针对分布式服务,微服务API功能和性能一体的自动化测试平台,一站式解决应用,服务,API,环境管理,用例,条件,测试场景,计划,测试报告,功能/性能测试兼容支持的一体化工作平台
Stars: ✭ 105 (+262.07%)
Mutual labels:  api-client

fb-messenger-bot-api

NodeJS Facebook Messenger API

version travis build codecov coverage dependency status Known Vulnerabilities Codacy Badge MIT License semantic-release Commitizen friendly stability-stable Greenkeeper code style

Installation

npm install fb-messenger-bot-api

Table of Contents

Documentation

You can find documentation here

Features

  • Near complete Typescript types for all incoming/outgoing Facebook Messaging API payloads & webhooks
  • Builders for all types of buttons/templates
  • Incoming Message Parser & Extractor
  • Webhook Validation logic
  • Page posting
  • Profile interactions
  • Promises and callback support on all functions, if no callback provided, promise returned, allows you to manage flow as you desire AND to ensure message ordering
  • Supports proxying
  • Typescript code with exported types for every end-point input/output
  • Using latest Facebook API v3.1

Setup

Import

const facebook = require('fb-messenger-bot-api');

or

import { FacebookMessagingAPIClient, etc... } from 'fb-messenger-bot-api';

Sending Messages

Initialize

const messageClient = new facebook.FacebookMessagingAPIClient(process.env.PAGE_ACCESS_TOKEN);

or

const messageClient = new FacebookMessagingAPIClient(process.env.PAGE_ACCESS_TOKEN);

Using proxy

const messageClient = new facebook.FacebookMessagingAPIClient(process.env.PAGE_ACCESS_TOKEN, { hostname:process.env.PROXY_HOST, port: process.env.PROXY_PORT });

or

const messageClient = new FacebookMessagingAPIClient(process.env.PAGE_ACCESS_TOKEN, { hostname:process.env.PROXY_HOST, port: process.env.PROXY_PORT });

Defaults to http if no protocol provided

Text Message

messageClient.sendTextMessage(senderId, <MESSAGE>)
    .then((result) => ...)

or

await messageClient.sentTextMessage(senderId, <MESSAGE>);

Image Message

messageClient.sendImageMessage(senderId, <IMAGE_URL>)
    .then((result) => ...)

or

const result = await messageClient.sendImageMessage(senderId, <IMAGE_URL>)

This method will have the image cached by facebook so every receiver after the first will get it quickly.

Buttons Message

messageClient.sendButtonsMessage(senderId, <BUTTONS TEXT> [<ARRAY OF BUTTONS>])
    .then((result) => ...)

or

const result = await messageClient.sendButtonsMessage(senderId, <BUTTONS TEXT> [<ARRAY OF BUTTONS>])

Buttons format

Quick Reply Message

messageClient.sendQuickReplyMessage(senderId, <TEXT>, [<QUICK_REPLIES>])
    .then((result) => ...)

or

const result = await messageClient.sendQuickReplyMessage(senderId, <TEXT>, [<QUICK_REPLIES>])

Quick Reply format

Generic Template Message ( Horizontal Scroll List )

messageClient.sendGenericTemplate(senderId, [ELEMENTS])
    .then((result) => ...)

or

const result = await messageClient.sendGenericTemplate(senderId, [ELEMENTS])

Generic Template element format

List Message ( Vertical Scroll List )

messageClient.sendListMessage(senderId, [ELEMENTS], <firstElementStyle>, [FINAL_BUTTONS])
    .then((result) => ...)

or

const result = await messageClient.sendListMessage(senderId, [ELEMENTS], <firstElementStyle>, [FINAL_BUTTONS])

firstElementStyle is optional. If not provided defaults to large

List Template element format

Mark as Seen

messageClient.markSeen(senderId);

As per all methods, callback can be provided. If no callback provided returns promise. Recommended to send and continue processing without waiting for reply.

Toggle writing bubble

messageClient.toggleTyping(senderId, <true/false>);

As per all methods, callback can be provided. If no callback provided returns promise. Recommended to send and continue processing without waiting for reply. Defaults to false if no boolean parameter provided.

User Profile

messageClient.getUserProfile(senderId,[<PROPERTIES>])
    .then((result) => ...)

or

const result = await messageClient.getUserProfile(senderId,[<PROPERTIES>])

Valid properties: first_name,last_name,profile_pic,locale,timezone,gender,is_payment_enabled,last_ad_referral If none are given defaults to first_name only.

Incoming Message Parser

Extracts all relevant & known message types that can be found here. Returns array with all objects of interest. Left flexibility to user to filter out message types of interest per use case instead of returning dictionary object with each message type as a separate list for optional performance saving in case of usage on time sensitive platforms (AWS Lambda, AF, GCF, etc).

import {FacebookMessageParser} from 'fb-messenger-bot-api';
const messages = FacebookMessageParser.parsePayload(incomingPayload);

Setting Messenger Profile

Initialize

const profileClient = new facebook.FacebookProfileAPIClient(process.env.PAGE_ACCESS_TOKEN);

or

import {Profile} from 'fb-messenger-bot-api';
const profileClient = new FacebookProfileAPIClient(process.env.PAGE_ACCESS_TOKEN);

Using proxy

const profileClient = new facebook.FacebookProfileAPIClient(process.env.PAGE_ACCESS_TOKEN, { hostname:process.env.PROXY_HOST, port: process.env.PROXY_PORT });

Setting Greeting Message

profileClient.setGreetingMessage('Message that will be visible first thing when opening chat window with your bot/page')
.then((result) => ...)

or

const result = await profileClient.setGreetingMessage('Message that will be visible first thing when opening chat window with your bot/page');

Setting Get Started button

profileClient.setGetStartedAction(senderId, payload)
    .then((result) => ...)

or

const result = await profileClient.setGetStartedAction(senderId, payload)

payload is the value that will be first sent when new user sends first message, once per user interaction

Setting Persistent Menu

profileClient.setPersistentMenu(senderId, [<MENU_ENTRIES>])
    .then((result) => ...)

or

const result = await profileClient.setPersistentMenu(senderId, [<MENU_ENTRIES>])

This is a burger menu appearing next to the chat input field where users can click and get direct interaction shortcuts to specific functionality of the bot. Persistent menu format

Sending Facebook Page Posts

Initialize

const pageClient = new facebook.FacebookPageAPIClient(process.env.PAGE_ID, process.env.PAGE_ACCESS_TOKEN);

or

import {FacebookPageAPIClient} from 'fb-messenger-bot-api';
const pageClient = new FacebookPageAPIClient(process.env.PAGE_ID, process.env.PAGE_ACCESS_TOKEN)

Using proxy

const pageClient = new facebook.FacebookPageAPIClient(process.env.PAGE_ID, process.env.PAGE_ACCESS_TOKEN, { hostname:process.env.PROXY_HOST, port: process.env.PROXY_PORT });

Defaults to http if no protocol provided

Requires a never expiring publishing_actions token that can be obtained by following this guide.

Page Image Posts

pageClient.imageUrl(`<URL>`).imageCaption(`<CAPTION>`).sendImage(`<CALLBACK>`);

<URL> is the url of the image being posted

<CAPTION> is the text you want on top of the image

<CALLBACK> is optional callback otherwise promise is returned

Page Link Posts

pageClient.postUrl(`<URL>`).postMessage(`<MESSAGE>`).sendPost(`<CALLBACK>`);

<URL> is the url of the link being posted

<MESSAGE> is the text you want on top of the link

<CALLBACK> is optional callback otherwise promise is returned

Validating Facebook Webhook

Server Validation

const facebook = require('fb-messenger-bot-api');
const router = require('express').Router();
router.get('/api/webhook',(req, res) => facebook.ValidateWebhook.validateServer(req,res));

Example based on usage with Express Router, can use any other middleware which passes in the req and response objects. Assumes verification token set under process.env.FB_VERIFICATION_TOKEN.

Alternatively, if you want to pass in your set token in a different manner or under different name you can use

ValidateWebhook.validateServer(req, res, <TOKEN>);

This allows you to obtain the value as you wish and still use it as above with the help of currying.

...
const validateWebhook = function validateWebhook(token) {
  return (req, res) => facebook.ValidateWebhook.validateServer(req, res, token);
}
const validator = validateWebhook(<TOKEN>);
router.get('/api/webhook/',validator);

Lambda Validation

Alternatively, you can use this when running on AWS Lambda to take advantage of the serverless paradigm as follows:

import {ValidateWebhook} from 'fb-messenger-bot-api';
const handler = (event, context, callback: Function) => {
    ...
    if(event.httpMethod === 'GET') {
        ValidateWebhook.validateLambda(event, callback);
    }
    ...
}

Both validateLambda and validateServer support passing in verification token as third parameter. Otherwise will check process.env.FB_VERIFICATION_TOKEN for value.

Validating Message Integrity

Validates the integrity of the message received from Facebook platform using the provided signature signed with Facebook Application Secret.

The Facebook application secret can be provided either as second optional parameter to ValidateWebhook.validateMessageIntegrity(<X-HUB-SIGNATURE>, <FB_APPLICATION_SECRET>) or by setting process.env.FB_APPLICATION_SECRET.

Compatible with both server/less paradigms as part of single line middleware function to Express or as Lambda first check before callback or remainder or programme.

import {ValidateWebhook} from 'fb-messenger-bot-api';
const messageIntegrityChecker = (req, res) => {
    const validMessage = ValidateWebhook.validateMessageIntegrity(req.headers["x-hub-signature"]);
    ...
}
router.post('/api/webhook/',messageIntegrityChecker);

Complete example

const router = require('express').Router();
const facebook = require('fb-messenger-bot-api');
const messagingClient = new facebook.FacebookMessagingAPIClient(process.env.PAGE_ACCESS_TOKEN);
const messageParser = facebook.FacebookMessageParser;
...
router.get('/api/webhook',facebook.ValidateWebhook.validateServer);
router.post('/api/webhook', (req, res) => {
    const incomingMessages = messageParser.parsePayload(req.body);  
    ...
    messagingClient.markSeen(senderId)
        .then(() => client.toggleTyping(senderId,true))
        .catch((err) => console.log(error));
    ...
    //promise based reaction on message send confirmation
    messagingClient.sendTextMessage(senderId, 'Hello')
        .then((result) => console.log(`Result sent with: ${result}`));
    ...
    //callback based reaction on message confirmation
    messagingClient.sendTextMessage(senderId, 'Hello',(result) => console.log(`Result sent with: ${result}`));
    ...
    //silent message sending
    messagingClient.sendTextMessage(senderId,'Hello');
})

or

import {FacebookMessagingAPIClient, ValidateWebhook, FacebookMessageParser} from 'fb-messenger-bot-api';
import {Router} from 'express';
...
router.get('/api/webhook',facebook.ValidateWebhook.validateServer);
router.post('/api/webhook', (req, res) => {
    try {
    const incomingMessages = messageParser.parsePayload(req.body);  
        ...
        await messagingClient.markSeen(senderId);
        await messagingClient.toggleTyping(senderId,true));
        ...
        //promise based reaction on message send confirmation
        const result = await messagingClient.sendTextMessage(senderId, 'Hello');
        console.log(`Result sent with: ${result}`));
        ...
    } catch(e){...}
    //callback based reaction on message confirmation
    messagingClient.sendTextMessage(senderId, 'Hello',(result) => console.log(`Result sent with: ${result}`));
    ...
    //silent message sending
    messagingClient.sendTextMessage(senderId,'Hello');
});

Creating Facebook app

See Facebook Guide

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].