How To Code Your Own ‘Watson’ AI Bot In 50 Lines Of Code

 

How To Code An IBM Watson AI Bot?

Setting up Watson for your AI Bot:

To get started, you need to sign up for 30 days Watson trial that will give you access to 2GB of runtime and container memory to run apps and unlimited IBM services and APIs.
After you are done with the sign-up and setting up your region and company, go ahead and explore the web UI as you’ll be needing it.
After this step, follow this easy to grasp documentation and create your speech-to-text service using the command line.
Now come back to the web interface, find the newly created service and obtain the credentials.

Setting up a Telegram bot in 50 lines of code:

This step is very simple and you need to start by adding the BotFather to you contacts. Now use /newbot command and follow the instructions like adding your name and username.
Make sure that you write down your API token. For more help, you can visit Telegram’s Bot guide.
After all is done, here is the open source code that you can use to create your own bot. Take a look:

var Bot = require('node-telegram-bot-api')
var watson = require('watson-developer-cloud');
var request = require('request');
var config = require('./config');

var speech_to_text = watson.speech_to_text({
  username: config.watson.username,
  password: config.watson.password,
  version: 'v1',
  url: 'https://stream.watsonplatform.net/speech-to-text/api'
});

var params = {
  content_type: 'audio/ogg;codecs=opus',
  continuous: true,
  interim_results: false
};

var bot = new Bot(config.telegram.token, { polling: true });
bot.on('message', function (msg) {
 if(msg['voice']){ return onVoiceMessage(msg); }
});

function onVoiceMessage(msg){
  var chatId = msg.chat.id; 
  bot.getFileLink(msg.voice.file_id).then(function(link){ 
   //setup new recognizer stream
   var recognizeStream = speech_to_text.createRecognizeStream(params);
 recognizeStream.setEncoding('utf8');
   recognizeStream.on('results', function(data){
  if(data && data.results && data.results.length>0 && data.results[0].alternatives && data.results[0].alternatives.length>0){
   var result = data.results[0].alternatives[0].transcript;
   console.log("result: ", result);
   //send speech recognizer result back to chat
   bot.sendMessage(chatId, result, {
    disable_notification: true,
    reply_to_message_id: msg.message_id
   }).then(function () {
       // reply sent!
   });
  }

 });
 ['data', 'error', 'connection-close'].forEach(function(eventName){
     recognizeStream.on(eventName, console.log.bind(console, eventName + ' event: '));
 });
 //pipe voice message to recognizer -> send to watson
   request(link).pipe(recognizeStream);
  });
}
 
 
 
You can also try out this bot on Telegram by adding @speech2textbot
(https://telegram.me/speech2textbot) to you contacts or any chat. 

Comments