1

I am trying to use viber-bot to send pdf files to a client, but I don't have these files locally or as a url.I get required files from other requests, and I haven't found anything about buffers in viber-bot documentation. Here is my code:

const ViberBot = require('viber-bot').Bot,
  BotEvents = require('viber-bot').Events,
  TextMessage = require('viber-bot').Message.Text,
  FileMessage = require('viber-bot').Message.File,
  express = require('express');
const app = express();

if (!process.env.BOT_ACCOUNT_TOKEN) {
  console.log('Could not find bot account token key.');
  return;
}
if (!process.env.EXPOSE_URL) {
  console.log('Could not find exposing url');
  return;
}

const bot = new ViberBot({
  authToken: process.env.BOT_ACCOUNT_TOKEN,
  name: process.env.BOT_NAME,
  avatar: ''
});
bot.on(BotEvents.SUBSCRIBED, response => {
  response.send(new TextMessage(`Hi there ${response.userProfile.name}. I am ${bot.name}! Feel free to ask me anything.`));
});
bot.onSubscribe(response => console.log(`Subscribed: ${response.userProfile.name}`));
bot.on(BotEvents.MESSAGE_RECEIVED, async (message, response) => {
  try {
//use buffer instead of urls
    await response.send(
new FileMessage('https://upload.wikimedia.org/wikipedia/commons/3/3d/Katze_weiss.png', 2, 'test.png')).catch(err => console.log(err))
  } catch(err) {
    console.log(err);
  }

  response.send(new TextMessage(`Message received.`));
});
const port = process.env.PORT || 3000;
app.use("/viber/webhook", bot.middleware());
app.listen(port, () => {
  console.log(`Application running on port: ${port}`);
  bot.setWebhook(`${process.env.EXPOSE_URL}/viber/webhook`).catch(error => {
    console.log('Can not set webhook on following server. Is it running?');
    console.error(error);
    process.exit(1);
  });
});

1 Answers1

0

What did the trick for me:

  • Viber Bot runs on local server under Node.js
  • Ngrok generates and exposes a specific link that takes ViberBot Live on internet.
  • Generate your .pdf and save it on local path (e.x. ngrokpath/myfiles/mypdf.pdf)

Then inside your bot make use of:

var filename = "MyClientFile.pdf";
var urlstring = expose_url+"/myfiles/"+filename;    
var pdffilesize = 150; //kb                        
response.send(new FileMessage(urlstring, pdffilesize, filename));

expose_url is the url from Ngrok session. pdffilesize is just for reference according viber api. Viber Bot needs to know filesize.

In case you don't want to have a local file stored and directly retrieved from buffer, use pdfmake plugin.

Generate your pdf (base64 string) and then feed to viber message as media.

Hope that works for you too...

Ngrok Link

pdfmake tutorial

George Gotsidis
  • 426
  • 4
  • 15