Start here · Examples

Edit this page on GitHub

Practices

A continuación encontrará diferentes ejemplos que muestran la implementación en diferentes casos de uso. Estos ejemplos han sido compilados en base a la comunidad, siéntete libre de publicar un ejemplo que te guste o que creas que sería útil para gente nueva.


My first bot

El siguiente código representa el uso rápido de un bot que cuando escribes la palabra hola, te saluda con un mensaje de bienvenida y te pregunta tu nombre y luego devuelve una imagen divertida

app.ts

import { createBot, createProvider, createFlow, addKeyword, MemoryDB } from '@builderbot/bot'
import { BaileysProvider } from '@builderbot/provider-baileys'

const welcomeFlow = addKeyword<BaileysProvider, MemoryDB>(['hi'])
    .addAnswer('Ey! welcome')
    .addAnswer('Your name is?', { capture: true }, async (ctx, { flowDynamic }) => {
        await flowDynamic([`nice! ${ctx.body}`,'I will send you a funny image'])
    })
    .addAction(async(_ , {flowDynamic}) => {
        const dataApi = await fetch(`https://shibe.online/api/shibes?count=1&urls=true&httpsUrls=true`)
        const [imageUrl] = await dataApi.json()
        await flowDynamic([{body:'😜', media: imageUrl}])
    })


const main = async () => {
    const adapterDB = new MemoryDB()
    const adapterFlow = createFlow([welcomeFlow])
    const adapterProvider = createProvider(BaileysProvider)

    adapterProvider.initHttpServer(3000)

    await createBot({
        flow: adapterFlow,
        provider: adapterProvider,
        database: adapterDB,
    })
}

main()

state

Conversational history

A menudo, necesitaremos administrar conversaciones y mantener el contexto en una memoria llamada state que es volátil y accesible desde cualquier función ejecutada en una secuencia.

  const welcomeFlow = addKeyword(['hello'])
      .addAnswer(
          "¿What's your name?",
          {capture: true},
          async (ctx, { flowDynamic, state }) => {
              await state.update({ name: ctx.body })
              await flowDynamic('Thanks for giving me your name!')
          }
      )
      .addAnswer(
          '¿How old are you?',
           {capture: true},
          async (ctx, { flowDynamic, state }) => {
              const name = state.get('name')
              await state.update({ age: ctx.body })
              await flowDynamic(`Thanks for sharing your age! ${name}`)
          }
      )
      .addAnswer('Here is your data:', null, async (_, { flowDynamic, state }) => {
          const myState = state.getMyState()
          await flowDynamic(`Name: ${myState.name} Age: ${myState.age}`)
      })

flowDynamic

Dynamic Messages

En otras ocasiones necesitamos enviar mensajes de forma dinámica de datos que pueden ser variables, a continuación puedes ver un ejemplo de cómo debes hacerlo y cómo NO.

let name = ''

const flow = addKeyword('hello')
    .addAnswer(`What is your name?`, { capture: true }, async (ctx) => {
        name = ctx.body
    })
    .addAnswer(`Your name is: ${name}`)

Si quieres enviar un mensaje dinámico usa flowDynamic.

const flow = addKeyword('hello')
    .addAnswer(`What is your name?`, { capture: true }, async (ctx, { state }) => {
        await state.update({ name: ctx.body })
    })
    .addAction(async (ctx, { state, flowDynamic }) => {
        const name = state.get('name')
        await flowDynamic(`Your name is: ${name}`)
    })

Send File

Cuando quieras enviar una imagen, audio, archivo o cualquier otro archivo puedes hacerlo de esta manera. Es important para tener en cuenta que la URL debe ser publicly accessible.

const flow = addKeyword('hello')
    .addAnswer(`Send image from URL`, 
        { media: 'https://i.imgur.com/0HpzsEm.png' }
    )
    .addAnswer(`Send video from URL`, 
        { media: 'https://media.giphy.com/media/KWZKwdBC2ODWlQ8kgt/giphy.mp4' }
    )
    .addAnswer(`Send file from URL`, 
        { media: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf' }
    )

Otras formas de usar cuando la ruta proviene de una fuente de datos dinámica

const flow = addKeyword('hello')
    .addAction(async (_,{flowDynamic}) => {
        // ...db get source...
        await flowDynamic([
            {body:'This is an image', media:'https://i.imgur.com/0HpzsEm.png'}
        ])
        await flowDynamic([
            {body:'This is a video', media:'https://media.giphy.com/media/KWZKwdBC2ODWlQ8kgt/giphy.mp4'}
        ])
    })

Si necesita enviar un archivo almacenado localmente, también puede hacerlo. El uso de join se recomienda para garantizar una correcta concatenación de directorios.

const flow = addKeyword('hello')
    .addAction(async (_,{flowDynamic}) => {
        const pathLocal = join('assets','doc.pdf')
        // pathLocal = c:/doc.pdf
        await flowDynamic([
            {body:'This is a video', media: pathLocal }
        ])
    })

gotoFlow

Switch to another flow

Si desea desviar un flujo conversacional a otro flujo lógico en función de una entrada de respuesta, puede hacerlo de esta manera:


const flowToA = addKeyword(EVENTS.ACTION).addAnswer('Here we have Option A!')
const flowToB = addKeyword(EVENTS.ACTION).addAnswer('Here we have Option B!')
const flowToC = addKeyword(EVENTS.ACTION).addAnswer('Here we have Option C!')

const flowDefault = addKeyword(EVENTS.ACTION).addAnswer("We don't have that Option 🤔")

const flow = addKeyword('order')
    .addAnswer(
        [
            `Which one is the best option for you?`,
            `Type **A**`,
            `Type **B**`,
            `Type **C**`,
        ], 
        { capture: true }
    )
    .addAnswer(`Thanks for you answer`,async (ctx, {gotoFlow})=> {
        const userAnswer = ctx.body
        if(userAnswer === 'A'){
            return gotoFlow(flowToA)
        } 
        if(userAnswer === 'B'){
            return gotoFlow(flowToB)
        } 
        if(userAnswer === 'C'){
            return gotoFlow(flowToC)
        } 
        return gotoFlow(flowDefault)

    })
    .addAnswer(`this message will not be sent`)

//...Previous code...
    ....addAnswer(`Thanks for you answer`,async (ctx, {gotoFlow})=> {
        gotoFlow(flowToA)

    })
    .addAnswer(`this message will not be sent`)

Esto no funciona.


//...Previous code...
    ....addAnswer(`Thanks for you answer`,async (ctx, {gotoFlow})=> {
        return gotoFlow(flowToA)

    })
    .addAnswer(`this message will not be sent`)

state

Turn off bot a certain user

A veces necesitaremos apagar el barco para un determinado usuario, para que podamos tener una conversación con el cliente sin que el bot interfiera.

const flow = addKeyword<BaileysProvider>('magic keyword')
  .addAction(async (_, { state, endFlow }) => {
      const botOffForThisUser = state.get<boolean>('botOffForThisUser')
      if(botOffForThisUser) return endFlow()
  })
  .addAnswer('Hello!')

state

Turn off for everyone

A veces necesitaremos deshabilitar el bot para todas las personas, sin necesidad de apagar el servidor o detener el script.

const flow = addKeyword<BaileysProvider>('botoff')
  .addAction(async (_, { globalState, endFlow }) => {
      const botOffForEveryOne = globalState.get<boolean>('botOffForEveryOne')
      if(botOffForEveryOne) return endFlow()
  })
  .addAnswer('Hello!')

Guides

My first chatbot

Learn how build your first chatbot in few minutes

Read more

Concepts

Understand the essential concepts for building bots

Read more

Add Functions

The key to learning how to write flows is add-functions.

Read more

Plugins

Unlimitate and start implementing the community plugins.

Read more

Resources

Modularize

Learn how to modularise flows so that you can have a more maintainable bot.

Send Message

How to send a message via HTTP to start conversations, you can send multimedia as well.

Dockerizer

A good practice is to dockerise your bots to make them more maintainable and effective.

Events

Learning about events will make us more fluent when creating chatbots.