Coder Social home page Coder Social logo

yoctol / bottender Goto Github PK

View Code? Open in Web Editor NEW
4.2K 93.0 333.0 25.82 MB

⚡️ A framework for building conversational user interfaces.

Home Page: https://bottender.js.org

License: MIT License

JavaScript 0.99% TypeScript 98.35% CSS 0.62% Shell 0.04%
messaging messenger line slack telegram bot chatbot framework viber

bottender's Introduction

Bottender

npm Build Status coverage License: MIT PRs Welcome join chat Gitpod Ready-to-Code Follow @bottenderjs

The readme below is the documentation for the v1 (stable) version of Bottender. To view the documentation:

  • Declarative - Bottender takes care of the complexity of conversational UIs for you. Design actions for each event and state in your application, and Bottender will run accordingly. This approach makes your code more predictable and easier to debug.

  • Native User Experience - Bottender lets you create apps on every channel and never compromise on your users’ experience. You can apply progressive enhancement or graceful degradation strategy on your building blocks.

  • Easy Setup - With Bottender, you only need a few configurations to make your bot work with channels, automatic server listening, webhook setup, signature verification and so much more.

  • Ready for Production - There are thousands of bots powered by Bottender. It has been optimized for real world use cases, automatic batching request and dozens of other compelling features.

Bottender is built on top of Messaging APIs.

Installation

You can create a new Bottender app using the CLI tools:

npx create-bottender-app my-app

Installation may fail on Windows during compilation of the native dependencies with node-gyp. To solve this problem, you can install windows-build-tools or check node-gyp documentation.

Documentation

You can find the Bottender documentation on the website.

Check out the Getting Started page for a quick overview.

Community

join chat

You can discuss anything about Bottender or chatbot development in our Discord Server. Join now!

Examples

We have a bunch of examples in the examples folder. Here is the first one to get you started:

// index.js
const { router, text } = require('bottender/router');

async function SayHi(context) {
  await context.sendText('Hi!');
}

async function Unknown(context) {
  await context.sendText('Sorry, I don’t know what you say.');
}

module.export = function App(context) {
  return router([text('hi', SayHi), text('*', Unknown)]);
};

Notable Features

Messenger

  • Messenger Profile Sync
  • Attachment Upload
  • Handover Protocol
  • Persona
  • Built-in NLP
  • Multiple Pages

LINE

  • Reply, Push, Multicast, Narrowcast
  • Imagemap
  • Rich menu
  • Room, Group Chat
  • Beacon
  • Icon Switch
  • Line Notify
  • LIFF (LINE Front-end Framework)

Slack

  • Channel Chat
  • Interactive Message
  • Slash Command

Telegram

  • Webhook, Long Polling
  • Updating, Deleting Messages
  • Keyboard
  • Group Chat
  • Inline Query
  • Message Live Location
  • Payment

Viber

  • Subscribed, Unsubscribed Event
  • Delivered, Seen Event

Ecosystem

Contributing

Pull Requests and issue reports are welcome. You can follow steps below to submit your pull requests:

Fork, then clone the repo:

git clone [email protected]:your-username/bottender.git

Install the dependencies:

cd bottender
yarn

Make sure the tests pass (including ESLint, TypeScript checks and Jest tests):

yarn test

Make your changes and tests, and make sure the tests pass.

Contribute using the online one-click setup

You can use Gitpod(a free online VS Code-like) for contributing. With a single click it will launch a workspace and automatically:

  • clone the bottender repo.
  • install the dependencies.
  • run yarn run start.

So that you can start straight away.

Open in Gitpod

License

MIT © Yoctol

bottender's People

Contributors

amite avatar bobchao avatar calvin-lin avatar chentsulin avatar darkbtf avatar dependabot[bot] avatar etrex avatar hch903 avatar hcwxd avatar homerchen19 avatar jigsawye avatar kidkcl avatar kpman avatar kutukata avatar littlewhiteya avatar louis70109 avatar lrills avatar mark86092 avatar nisarhassan12 avatar ohaodaio avatar qshiwu avatar roonie007 avatar sigorilla avatar siriustsou avatar storyn26383 avatar suphero avatar tbroadley avatar tigercosmos avatar tw0517tw avatar wtflink 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  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

bottender's Issues

customer chat plugin ref param

i can't catch the Postback ref param in customer chat plugin

<div class="fb-customerchat"
 page_id="<PAGE_ID>"
 ref="<OPTIONAL_WEBHOOK_PARAM>">
</div>

this is my code:

bot.onEvent(async context => {
  await console.log(context.event.postback);
  //await context.sendText('je suis un robot boucle infinie :p');
});

it give me always null.
any suggestion please.

cannot set static verify token for fb messenger

All the time I restart the server new verify token for fb messenger is generated. There is no option to set it static.

Adding verifyToken property to to bottender.config.json does not help.

Add slack access token in runtime

Since i want to make the slack bot installable with oauth2, is there a method that i can use to add the access token after the bot instance is created?

Currently the token is added at SlackBot is run, which means i need to provide it at the constructor. However with oauth the token is given after the constructor is run. So now i just enter an empty string first and then manually change the _token property in SlackOAuthClient.

LifeTime State

Hey guys

I have a suggestion , what about a State that will be destroyed after a fixed given number (not in secondes) , like contexts in DialogFlow(api.ai) , maybe smthng like this

context.setState(Object,lifeTime);

//Will be used like this

// 'nickname' and 'asking' will be destroyed at the end of the next event triggering
context.setState({ nickname: context.event.text, asking: false },1);

// 'nickname' and 'asking' will be destroyed at the end of the third event triggering
context.setState({ nickname: context.event.text, asking: false },3);

keep the good work

[Messenger] - How to update mapPageToAccessToken

Hi,

I have an application that users create their ChatBot. So i want that when they click "Install ChatBot on your Page" the mapPageToAccessToken should be updated for live working. Is there a way to do this, without rebooting the server?

Thanks,

Conversation ID

Hi,

I want to track events using bottender. But i did't find "conversation id". I know that i can concat: "context.event.rawEvent.sender.id + context.event.rawEvent.recipient.id, but i would like to know if is there a conversation id?

Thanks,

Track send messages

Hi,

I saw the exemples with (botanalytics, dashbot etc..) but they only track what User Send. I want to track what bot send to user. How can i do this?

Thanks

accessToken is not required for messenger set webhook

When only using CLI to set webhook, the users don't need to provide accessToken.
They just need to set appId and appSecret in config.

So maybe we should tell the users to provide an empty string as accessToken?

whitelisted_domains must be set before home_url

If set whitelisted_domains and home_url at the same time using one CLI command, Facebook will throw error. Must set whitelisted_domains first and then with home_url the 2nd CLI call.

> bottender messenger profile set
× Failed to set messenger_profile settings
× status: 400
× data: {
  "error": {
    "message": "(#100) The web URL provided is not whitelisted for messenger extensions",
    "type": "OAuthException",
    "code": 100,
    "error_subcode": 2018063,
    "fbtrace_id": "A9EtushnqDU"
  }
}

Direct messages on Slack

Heyo! Very very nice work! Thanks for open-sourcing it! ❤️

I wanted to ask to know whether it's a bug or maybe not a not-implemented-yet feature. Currently, when I talk to my bot (sounds crazy huh?) privately I get:

Unhandled promise rejection (rejection id: 21): Error: Slack API - channel_not_found

I think I've granted everything I should on Slack. Any guidance?

[LINE] how to push message without context

the push function looks like this
await context.client.pushText(userId, 'Goodbye LINE');

but in most usecase, I would like to push message at a specific time, or triggered events other than LINE webhook events.
How should I push messages whenever I like to?
ps: Im currently saved a context object to global scope. so that whenever I need to call .pushText. I can use the global context object.

Slack attachments, buttons & menus

Heyo!

I was wondering how I'd send custom attachments to Slack through the context. I would love some API that allows me to reach postMessage directly.

Also, do you guys have any idea on how to integrate with Slack callbacks? Let's say that I want to send a message with a button that does something.

Not working when verifying webhook URL on LINE platform

Version of Bottender: "bottender": "^0.14.3",
Steps to reproduce:

  1. start the server with any endpoint eg:
    const server = createServer(bot, { path: '/webhook' });
  2. press the Verify on https://developers.line.me/console after changed a new webhook URL
  3. a mock message will be sent from LINE to our server, and it will be something like this eg:
    "events": [
        {
            "replyToken": "00000000000000000000000000000000",
            "type": "message",
            "timestamp": 1512777897980,
            "source": {
                "type": "user",
                "userId": "Udeadbeefdeadbeefdeadbeefdeadbeef"
            },
            "message": {
                "id": "100001",
                "type": "text",
                "text": "Hello, world"
            }
        },
        {
            "replyToken": "ffffffffffffffffffffffffffffffff",
            "type": "message",
            "timestamp": 1512777897980,
            "source": {
                "type": "user",
                "userId": "Udeadbeefdeadbeefdeadbeefdeadbeef"
            },
            "message": {
                "id": "100002",
                "type": "sticker",
                "packageId": "1",
                "stickerId": "1"
            }
        }
    ]
}

  1. internal/process/warning.js:18 (node:16291) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: LINE API - Not found
    this error will be logged, and it is due to the unhandled promise rejection in lib/express/createMiddleware.js:12

Is this a bug or a behavior? If it is a behavior, how can I handle the promise rejection?

updateSession may take too long in SlackConnector

It may take over 3 seconds so Slack will retry and bot will receive 2 repeat events.

Not sure if we should try speeding up SlackConnector.updateSession() or change Bot.handleRequest() behavior to respond earlier.

How to send only once one message?

When I run the examples for messenger, once I send something to the bot, it starts spamming the same thing until I stop the server, how do I send a message only once and wait for the user to respond?
Here is an example of what I'm talking:
img_3630

Example naming

There are so many with-xxx examples, hard to determine what type is it. Maybe we could rearrange them with type. For example,
with-koa => server-koa
with-express => server-express
with memory-session => session-memory
with-now-deployment => deployment-now.
There could still be some can't be renamed well but it'll be much less with-xxx.

Postback not triggering from Messenger

I connected my nodejs chatbot to messenger using ngrok and it works fine except for the postback_messages. Nothing happens when I press the 'start' button or the return to beginning button. What I have to do is click on the button and then send a text message. Everything works just fine after that.
I believe that the postback message is not triggening the "onEvent" function, that's why I need the text message.
Yes, I have the messaging_postbacks event selected on my facebook app.
Does anyone have any ideas? Is there something I have to do with ngrok to make the postback reach the bot?

access token as CLI arguments?

so we can have something like
bottender messenger do something --token=<TOKEN>
and will not throw when there is no bottender.config.js

Add multi-Line bot example

inspired by Add multi-page example #60

Is it possible to support multi-Line bot too?

I'm new to github and dont know how to fork and npm install my forked repo

Viber Support

When will you add Viber to Bottender , it's currently not available .

Remove server dependencies

Good job guys for this library 👍

IMO you should drop the server dependencies (express, koa, restify ,micro, ngrok...) and only expose functions to initialize a new or existing apps. so instead of

const { MessengerBot } = require('bottender');
const { createServer } = require('bottender/express');

const bot = new MessengerBot({
  accessToken: '__FILL_YOUR_TOKEN_HERE__',
  appSecret: '__FILL_YOUR_SECRET_HERE__',
});

bot.onEvent(async context => {
  await context.sendText('Hello World');
});

const server = createServer(bot);

server.listen(5000, () => {
  console.log('server is running on 5000 port...');
});

we can use this library within an existing express app

let bottender = require('bottender')
let express = require('express')
let app = express()

let bot = new MessengerBot({
  accessToken: '__FILL_YOUR_TOKEN_HERE__',
  appSecret: '__FILL_YOUR_SECRET_HERE__'
})

bot.onEvent(async (context) => {
  await context.sendText('Hello World')
})

bot.initExpress(app)

// configure the app

app.listen(5000, () => {
  console.log('server is running on 5000 port...')
})

Error in Facebook app reviewing process

I am using bottender to build a facebook messenger bot.
However, every time I send review request for pages_messages permission in facebook developer console, my server will get some error, so that I cannot pass the review. The full error messages are as following:

(node:14801) UnhandledPromiseRejectionWarning: Error: Messenger API - 100 GraphMethodException Unsupported get request. Object with ID '1838982186136447' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api
    at handleError (/home/goodjob/wei-ming-check-in-bot/node_modules/messaging-api-messenger/lib/MessengerClient.js:94:9)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:160:7)
(node:14801) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)
(node:14801) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'message' of undefined
    at MessengerConnector.getUniqueSessionKey (/home/ming/wei-ming-check-in-bot/node_modules/bottender/lib/bot/MessengerConnector.js:103:18)
    at /home/ming/wei-ming-check-in-bot/node_modules/bottender/lib/bot/Bot.js:96:42
    at /home/ming/wei-ming-check-in-bot/node_modules/bottender/lib/express/createMiddleware.js:12:28
    at Layer.handle [as handle_request] (/home/ming/wei-ming-check-in-bot/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/ming/wei-ming-check-in-bot/node_modules/express/lib/router/route.js:137:13)
    at /home/ming/wei-ming-check-in-bot/node_modules/bottender/lib/express/verifyMessengerSignature.js:8:12
    at Layer.handle [as handle_request] (/home/ming/wei-ming-check-in-bot/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/ming/wei-ming-check-in-bot/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/ming/wei-ming-check-in-bot/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/ming/wei-ming-check-in-bot/node_modules/express/lib/router/layer.j
    at /home/ming/wei-ming-check-in-bot/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/home/ming/wei-ming-check-in-bot/node_modules/express/lib/router/index.js:335:12)
    at next (/home/ming/wei-ming-check-in-bot/node_modules/express/lib/router/index.js:275:10)
    at /home/ming/wei-ming-check-in-bot/node_modules/body-parser/lib/read.js:130:5
    at invokeCallback (/home/ming/wei-ming-check-in-bot/node_modules/raw-body/index.js:224:16)
    at done (/home/ming/wei-ming-check-in-bot/node_modules/raw-body/index.js:213:7)
(node:14801) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 7)

How to repeat the bug

  1. Write a messenger bot without try catch statement and onError handler

  2. In facebook developer console, ask for messages permission in Messenger tab
    2017-12-30 4 56 47

  3. Goto Webhook tab in facebook, press test for messages
    2018-01-02 9 44 06

then server will get same error message

If I need to provide more information, please kindly tell me.

CLI Set Messenger Profile will not overwrite passed setting

For example, there are three properties in my profile config:

persistent_menu
get_started
whitelisted_domains

After successfully set profile, I made some change and there are only two properties in my config.

persistent_menu
get_started

When I set profile again, the whitelisted_domains is still existing. But it should be deleted as expected.

The usage should overwrite the whole profile config, delete and set again.

[Bug] - Context.State is not new if the same user in other [Messenger]

Hi!,

I'm developing a robot that works in multiple pages. But with this #161 i got that the KEY of SessionStore is the userID. I think it should concat with pageId. The code that reproduces the error.

Case:

1 - Send message in Page 1
2 - Send message in Page 2

bot.onEvent(async context => {

    if (!context.state.fbPageId) {
        context.state.fbPageId = context.event.rawEvent.recipient.id
    }
    console.log("F ID:", context.event.rawEvent.recipient.id);
    console.log("S ID:", context.state.fbPageId);

});

Console Log:

F ID: 476947852676691
S ID: 476947852676691
F ID: 131348777471663
S ID: 476947852676691

[bug] ContextSimulator

Hey guys,

setState and resetState do not work in Handler when using ContextSimulator to simulate the Bot.

In my case to solve this problem , we have added an Overlay Module that override those functions, but I hope you can find a solution better than that 😄

Slack url_verification fails

using the restify server, slack url_verification fails for event subscription. restify body parser doesn't parse the body into req.params which is used here

Support Messenger webhook test button

default

  bottender/bot/Bot   "entry": [
  bottender/bot/Bot     {
  bottender/bot/Bot       "changes": [
  bottender/bot/Bot         {
  bottender/bot/Bot           "field": "messages",
  bottender/bot/Bot           "value": {
  bottender/bot/Bot             "page_id": "1067280970047460"
  bottender/bot/Bot           }
  bottender/bot/Bot         }
  bottender/bot/Bot       ],
  bottender/bot/Bot       "id": "0",
  bottender/bot/Bot       "time": 1514862760
  bottender/bot/Bot     }
  bottender/bot/Bot   ],
  bottender/bot/Bot   "object": "page"
  bottender/bot/Bot } +5s

This button will send a request which bottender can't parse.

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.