Git Product home page Git Product logo

whatsappinfobot's Introduction

WhatsappInfoBot - A framework to build bots generally, but specifically on WhatsApp.

The framework uses natural (implemented by @actuallysoham) to perform the natural language processing part. It can Baileys to interact with WhatsApp or with SendMammy webhooks.

Install

  1. Edge version: yarn add github:adiwajshing/WhatsappInfoBot
  2. Stable version: yarn add @adiwajshing/whatsapp-info-bot

Building Intents

The library follows a modular design. For example, a simple intent to answer queries about timings could look look like this:

timings.json

{
    "keywords": ["timings","time","when","timing","schedule","open","close"], // the keywords to identify an intent
    "answer": "*Timings for {{entity.key}} are:*\n {{entity.value}}", // the answer for this intent
    "entities": { // list of things the bot can answer for the `timings` intent
        "piano room": "6:00AM-12:00AM",
        "lunch": "12:15PM-02:30PM",
        "breakfast": "08:00AM-10:30AM",
        "snacks": "04:45PM-06:15PM",
        "dinner": "07:30PM-10:15PM",
        "laundry": "dropoff: Mon & Thu 08:00AM-02:00PM\npickup: Wed & Sat 04:30PM-06:00PM",
        "library": "all the time fren, except friday",
        "salon": {
            "alternates": ["parlour", "parlor", "saloon"], // alternate names for the same entity
            "value": "11:00AM-7:00PM, closed on tuesdays"
        },
        "asg": "shuts at 11:30PM"
    },
    "meta": { // some optional metadata to maybe create user facing documentation, see Example/intents/help.js
        "userFacingName": ["timings"],
        "description": "Timings for facilities",
        "examples": ["mail room timings", "timing 4 dinner", "yo bro, when can i get lunch"]
    }
}

And use this intent like this:

import timings from './timings.json'
import { createLanguageProcessor } from '@adiwajshing/whatsapp-info-bot/LanguageProcessor'

createLanguageProcessor([ timings ]).chat() // will start chat in terminal

So, if somebody asks the bot ayy, till when does the parlour stay open?, the bot will reply with: Timings for salon: 11:00AM-7:00PM, closed on tuesdays

Here, {{entity.key}} maps onto the key, salon & {{entity.value}} maps onto the value, 11:00AM-7:00PM, closed on tuesdays. Note: The syntax for these is the Mustache templating system. Here are the docs for the same.

Moreover, because parlour is an alternate name for salon, the library maps parlour back to the true name salon and then responds.

Sometimes, statically typing intents like this is too much of a pain or impossible to do. What if one wants to fetch the weather? Then, one could use a js class to describe the intent.

For example, weather.js could look like the following:

export default async () => {
    const entities: {[_: string]: string} = {}

    const fetchCities = async() => {
        // fetch the cities you can answer for, possibly using a REST API
        // fetch weather.com/rest or something
        // then call this function to finally update the entities, you can leave the values blank because the answer will be fetched
        entities = {"new york": "", "sf": "", "new delhi": "", "tokyo": ""}
    }
    await fetchCities()
    return {
        keywords: ['weather', 'like'],
        entities: entities,
        answer: (entities: string[], user: string) => {
            // fetch the cities you can answer for, possibly using a REST API
            // fetch weather.com/rest or something
            return "lol I dont know"
        },
        meta: {
            userFacingName: ["weather"],
            description: "Ask about the weather in different cities",
            examples: ["weather in SF?", "new york weather", "listen fren, you better tell me what its like in Bombay"]
        }
    }
}

This class intent can be used very similarly, like:

import timings from './timings.json'
import weather from './weather'
import { createLanguageProcessor } from '@adiwajshing/whatsapp-info-bot/LanguageProcessor'

(async () => {
    createLanguageProcessor(
        [ 
            timings,
            await weather()
        ],
        {
            parsingFailedText: 'I dont understand {{input}}'
        }
    ).chat() // will start chat in terminal
})()

Regexp based intents

Sometimes, you require more precise intent parsing that requires regular expressions. You can add that as well.

Example for a document access intent:

export default {
	regexps: [
		/(?:i want to  |)access doc(?:ument|) ([a-z0-9]*)(?: and ([a-z0-9]*)|)/
	],
	entities: { },
	answer: entities => {
		return 'I see you want to access docs ' + entities.join(', ')
	},
	meta: {
		userFacingName: [ 'documents', 'document access' ],
		description: 'Access a document by ID. Of course, this is a test',
		examples: [
			'I want to access document 1234 and 5678',
			'access doc 1234'
		]
	}
}

Usage over WhatsApp:

With Baileys

import timings from './timings.json'
import weather from './weather'
import { createLanguageProcessor, createBaileysResponder } from '@adiwajshing/whatsapp-info-bot/LanguageProcessor'

(async () => {
    const languageProcessor = createLanguageProcessor(
        [ 
            timings,
            await weather()
        ],
        {
            parsingFailedText: 'I dont understand {{input}}'
        }
    )

    createBaileysResponder(
        languageProcessor,
        {
            authFile: './auth_info.json'
            respondToPendingMessages: false // will respond to unread messages
        }
    ).start() // will connect and start responding to messages
})()

The first time you run the bot on WhatsApp, you will have to scan the QR code to enable WhatsApp Web. Once you run this code, the responder will now connect to WhatsApp & it'll print out a QR code for you to scan with WhatsApp on your phone. Once you scan it with your phone, the bot will start recieving & responding to messages.

whatsappinfobot's People

Contributors

adiwajshing avatar dependabot[bot] avatar usptech 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

whatsappinfobot's Issues

Help Create intent in js

Hi, i want to create weather.js intent that return current weather from city
for example, when user type "weather new york" it return current temperature, humidity, wind, cloud.
I'm using your example code but got the following error

D:\Pproject\WAbot\whatsbot\computed_intents\weather.js:13
fetchCities ()
^

ReferenceError: fetchCities is not defined
at new module.exports (D:\Pproject\WAbot\whatsbot\computed_intents\weather.js:13:9)
at LanguageProcessor.loadIntent (D:\Pproject\WAbot\LanguageProcessor.js:64:55)
at D:\Pproject\WAbot\LanguageProcessor.js:50:37
at Array.forEach ()
at LanguageProcessor.loadIntents (D:\Pproject\WAbot\LanguageProcessor.js:50:15)
at new LanguageProcessor (D:\Pproject\WAbot\LanguageProcessor.js:37:14)
at Object. (D:\Pproject\WAbot\bot.js:11:19)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
[nodemon] app crashed - waiting for file changes before starting...

this is my code

const got = require('got');

module.exports = class {
    constructor (processor) {
        this.processor = processor // the instance of LanguageProcessor.js that created this instance
        this.keywords = ["weather", "like"] // keywords to identify the intent
        this.entities = {}
        this.meta = { // set some metadata
            "userFacingName": ["weather"],
            "description": "Ask about the weather in different cities",
            "examples": ["weather in SF?", "new york weather", "listen fren, you better tell me what its like in Bombay"]
        }
        fetchCities ()
    }
    async fetchCities () {
        const url = `http://api.openweathermap.org/data/2.5/weather?q=dhaka&units=metric&appid=060a6bcfa19809c2cd4d97a212b19273&language=tr`;
        const response = await got(url).then(async ok => {
            const resp = JSON.parse(ok.body)
            temp = resp.main.temp_max
            humi = resp.main.humidity
            wind = resp.wind.speed
            clou = resp.clouds.all
            desc = resp.weather[0].description
            console.log(temp, humi, wind, clou, desc)
          })
        // this.processor.updateEntities ("weather", {"new york": "Rainy", "sf": "Bright", "new delhi": "Sunny", "tokyo": "Heavy Rain"})
    }
    /**
     * Async function that is called when somebody calls the `weather` command
     * @param {string[]} entities - what city?
     * @param {string} user - ID of the user
     */
    async answer (entities, user) {
        // fetch the cities you can answer for, possibly using a REST API
        // fetch weather.com/rest or something
        return entities
        //console.log(entities)
    }
}

I have successfully fetch the data from openweathermap.org API and test it using repl.it
this is the code that i use to fetch the data

const got = require('got');

const url = `http://api.openweathermap.org/data/2.5/weather?q=dhaka&units=metric&appid=060a6bcfa19809c2cd4d97a212b19273&language=tr`;

(async () => {
  const response = await got(url).then(async ok => {
    const resp = JSON.parse(ok.body)
    temp = resp.main.temp_max
    humi = resp.main.humidity
    wind = resp.wind.speed
    clou = resp.clouds.all
    desc = resp.weather[0].description
    console.log(temp, humi, wind, clou, desc)
  })
})();

it return this in repl.it
https://prnt.sc/wbxhmd

you can check the code here
https://repl.it/@AbdulAziz27/FloweryMindlessBytecode?lite=true

Thanks

Login never works

I have run it and the QRCode appears, but when it is scanned with WA, the login process only appears continuously

404 while installing

I'm getting an error while trying to install this package:

➜  whatsapp-bot git:(master) ✗ npm i @adiwajshing/whatsapp-info-bot -D
npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@adiwajshing%2fwhatsapp-info-bot - Not found
npm ERR! 404 
npm ERR! 404  '@adiwajshing/whatsapp-info-bot@*' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404 
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

BAILEYS

IS END OF WHATSAPP OT ERA ELSE BAILEYS REPO GOT PRIVATE OR DELETE

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.