How to add typing delay in botkit conversations with facebook adapter

457 views Asked by At

We are building a facebook messenger bot with Botkit version 4.

We have tried different ways to add typing delay with the messages but none of them is working properly.

As we are using the conversations we are unable to use this format in middleware

bot.reply(message, { type: "typing" });

So we are using something like the following:

Solution 1

controller.middleware.send.use(async function (bot, message, next) {
    if (bot._config && bot._config.activity && bot._config.activity.conversation && bot._config.activity.conversation.id) {
        await typingIndicator(bot,bot._config.activity.conversation.id)
        setTimeout(async () => { next(); }, 2000);
    } else {
        next();
    }
});

async function typingIndicator(bot, id) {
    await bot.api.callAPI('/me/messages', 'post', {
        recipient: { id: id }, sender_action: 'typing_on'
    })
}

But this implementation is not working as expected.

I have around 200 - 300 threads so I tried adding the delay using convo.before() But even this is breaking in between

Solution 2

let dialog = new BotkitConversation('dialog', controller);

dialog.addMessage({text: 'Message 1', action: 'thread_2'}, 'thread_1');
dialog.addMessage({text: 'Message 2', action: 'thread_3'}, 'thread_2');
dialog.addMessage({text: 'Message 3', action: 'thread_4'}, 'thread_3');
dialog.addMessage({text: 'Message 4'}, 'thread_4');

for (let key in dialog.script) {
    dialog.before(`${key}`, async (convo, bot) => {
        return new Promise((resolve, reject) => {
            setTimeout(resolve, 2000);
        });
    });
}

Any help will be appreciated.

1

There are 1 answers

3
Ben De Greef On

I solved it like this now:

async function middlewareTest(bot, message, next) {
  if(message.text.length > 0){
    let time = message.text.length * 30;
    await setTimeout(async ()=> {await next();}, time);
  } else {
    await next();
  } 
}

controller.middleware.send.use(middlewareTest);

I check if the messages text that is going to be sent has more than 0 characters. If thats the case I do a timeout.

Hope this helps.