Showing location response in SUSI.AI bots

SUSI.AI has a capability to tell the basic information about a location, it is asked for. Along with the basic information about that place, it shows a map (i.e. open street map) pointing to that location. The task at hand is to inculcate this “location” feature to the SUSI.AI messenger bots. The SUSI Tweetbot and SUSI Fbbot are used as examples in this blog. Let’s first check on what response do we get, when a person asks a query like “where is london” to the SUSI API. Along with the basic information about that location, the result as shown below has the type of reply (i.e. map), latitude, longitude and a link to the open street map. "actions": [ { "type": "answer", "language": "en", "expression": "Ludhiana is a city and a municipal corporation in Ludhiana district in the Indian state of Punjab, and is the largest city north of Delhi." }, { "type": "anchor", "link": "https://www.openstreetmap.org/#map=13/30.912040570244187/75.85379021980509", "text": "Here is a map", "language": "en" }, { "type": "map", "latitude": "30.912040570244187", "longitude": "75.85379021980509", "zoom": "13", "language": "en" } ] The response for a location type query has these 3 main parts: Clickable static map image. A basic information of the place asked about. The link i.e. when the static map image is clicked it should redirect to the corresponding map location. Let’s try to make up with the 1st part of the response i.e. Static map image. The map quest API is used to result in a static map image of the location. We need an API key to access the map quest API, which can be requested from their developer site. Along with that we need the latitude and longitude of the location at hand. The SUSI API’s response helps us to get the latitude value: // if body represents the response object var lat = body.answers[0].actions[2].latitude; And the longitude value: var lon = body.answers[0].actions[2].longitude; Using the three values that are API key, latitude and longitude, the static image is rendered by this link: var static_image_url = "https://open.mapquestapi.com/staticmap/v4/getmap?key=API_KEY&size=600,400&zoom=13&center="+lat+","+lon; The second part is, basic information about the place asked, can be fetched from: // if body is the JSON response object from SUSI API var mapMessage = body.answers[0].actions[0].expression; The link to the map location can be easily fetched from the SUSI API’s response: var link = body.answers[0].actions[1].link; As all the three parts are ready, let’s look on how to render them on the SUSI.AI bot’s screen. Facebook: Sending a generic template message object: message = { "type":"template", "payload":{ "template_type":"generic", "elements":[{ "title": mapMessage, "image_url": static_image_url, "Item_url": link }] } }; sendTextMessage(sender, message, 1); Twitter: The Twitter API does not need a static image of the map to be rendered. It does that work for us. We just need to send an event to the Twitter API with the message data object constituting of the map message, the latitude and longitude values: "message_data": { "text": mapMessage, "attachment": { "type": "location", "location": { "type": "shared_coordinate", "shared_coordinate": { "coordinates": { "type": "Point", "coordinates": [lon, lat] }…

Continue ReadingShowing location response in SUSI.AI bots

Making SUSI Alexa skill as an express app

Previously SUSI Alexa skill was deployed using AWS Lambda service (Refer to this blog). Each SUSI.AI Bot should be deployed on Google cloud using Kubernetes. To accomplish that, we need to remove the dependency of the SUSI Alexa skill from AWS Lambda service. We need to make it an express app, to be able to deploy it to Google cloud. Let’s start with on how to achieve it: SUSI Alexa skill: We require three files to make the skill as an express app. The main entry point for the skill would be server.js file, which will serve the incoming request using two helper files alexa.js and handlers.js. Server.js: This file acts as the main entry point for the incoming request. We handle two type of requests using it, that are: Launch request Intent request Launch request is triggered when a person utters “Alexa, open susi chat” , “Alexa, start susi chat”, “Alexa, launch susi chat” etc. This request is responded with an introductory phrase about SUSI.AI. To catch this request: if (type === "LaunchRequest") { var endpoint = "http://api.susi.ai/susi/chat.json?q="+"Welcome"; // ENDPOINT GOES HERE http.get(endpoint, (response1) => { var body = ""; response1.on("data", (chunk) => { body += chunk; }); response1.on("end", () => { var viewCount; viewCount = JSON.parse(body).answers[0].actions[0].expression; endpoint = "http://api.susi.ai/susi/chat.json?q="+"Get+started"; // ENDPOINT GOES HERE body = ""; http.get(endpoint, (response2) => { response2.on("data", (chunk) => { body += chunk; }); response2.on("end", () => { viewCount += JSON.parse(body);.answers[0].actions[0].expression; response.say(viewCount,false); }); }); }); }); } Intent request gets triggered, when any other phrase is uttered by the user except Launch related phrases. We check if the intent triggered has a corresponding handler to handle the request. If the handler is found in handlers.js file, we call it passing the required arguments to the handler function. Let’s see how handlers make this step possible. Handler.js: This file decides on what function to run when a particular type of intent is triggered. As we have just one intent for our SUSI Alexa skill i.e. callSusiApi, we have just one function in our handlers.js file. During its execution, the first step we do is extract the query value: let query = slots.query.value; Depending upon the query value, we run its corresponding code. For example, in case of a generic query (i.e. any query except stop, cancel and help): var endpoint = "http://api.susi.ai/susi/chat.json?q="+query; // ENDPOINT GOES HERE http.get(endpoint, (response1) => { var body = ""; response1.on("data", (chunk) => { body += chunk; }); response1.on("end", () => { var data = JSON.parse(body); if(data.answers[0].actions[1]){ // handle rss and table type results } else { viewCount = data.answers[0].actions[0].expression; } response.say(viewCount,true); }); }); At the end of the function we respond to the user with an answer to his/her query using: response.say(viewCount,true); Alexa.js: When we get a request from the user, we pass that request and response object to this file. This file helps us wrap the required request properties into an object and return that back to the server file, which was the entry point for the request. Now,…

Continue ReadingMaking SUSI Alexa skill as an express app

Showing sample queries in SUSI.AI Bots

We need to give the user a good start to their chat with SUSI.AI. Engaging the users with some good skills at the start of the conversation, can leave a good impression about SUSI.AI. In SUSI messenger bots, we show up with some sample queries to try, during the conversation with SUSI.AI. In this blog, SUSI_Tweetbot and SUSI_FBbot are used as examples. These queries are shown as quick replies i.e. the user can click on any of these sample queries and get an answer from SUSI.AI.   Facebook: When the user clicks on the “Start chatting” button, we send a descriptive message on what can the user ask to SUSI.AI . Code snippet used for this step is: var queryUrl = 'http://api.susi.ai/susi/chat.json?q='+'Start+chatting'; var startMessage = ''; // Wait until done and reply request({ url: queryUrl, json: true }, function (error, response, body) { if (!error && response.statusCode === 200) { startMessage = body.answers[0].actions[0].expression; } else{ startMessage = errMessage; } sendTextMessage(sender, startMessage, 0); Just a text message is not much engaging. To further enhance the experience of the user, we show some quick reply options to the user. We have finalized some skills to show to the user: Due to the character limit for the text shown on buttons, we try to show short queries as shown in the above picture. This way the user gets an idea about what type of queries can be asked. Generic template, help us achieve this feature in SUSI_FBbot. The code snippet used: var messageT = { "type": "template", "payload": { "template_type": "generic", "elements": [{ "title": 'You can try the following:', "buttons": [{ "type":"postback", "title":"What is FOSSASIA?", "payload":"What is FOSSASIA?" }] }] } }; sendTextMessage(sender, messageT, 1); As seen in the code above, each button has a corresponding postback text. So that whenever that button is clicked the postback text is sent to our chat automatically: This postback text acts as a query to SUSI API which fetches the response from the server and shows it back to the user. Twitter: As SUSI.AI bots must be generic among all the messenger platforms available , we will inculcate the same skills available in SUSI_FBbot to SUSI_Tweetbot. The quick reply feature provided by Twitter devs help us to accomplish this task at hand. As in SUSI_FBbot a descriptive message is shown to the users first and then some quick reply options following it. Message_create event helps in adding quick replies: var msg = { "event": { "type": "message_create", "message_create": { "target": { "recipient_id": senderId }, "message_data": { "text": "You can try the following:", "quick_reply": { "type": "options", "options": [{ "label": "What is FOSSASIA?", "metadata": "external_id_4" }] } } } } }; T.post('direct_messages/events/new', msg, sent); One thing to keep in mind while coding is to send the quick reply message after the initial descriptive message i.e. the code used to send quick replies should be written inside the function, which sends the descriptive message first and aafter that step is complete it runs the code for quick replies.…

Continue ReadingShowing sample queries in SUSI.AI Bots

Making SUSI.AI reach more users through messenger bots

SUSI.AI learns from the queries asked to it by the users. More are the number of queries asked, the better is the learning by SUSI.AI. More are the number of users involved with SUSI.AI, better is the amount of content available to SUSI to learn from. Now, the challenge in front of us is to indulge more users with SUSI.AI. In this blog post, SUSI Tweetbot and SUSI FBbot are used as examples to show how we increase our user base through messenger bots. Twitter: Twitter has a 328 million user base according to this article’s data. Integration of SUSI.AI to just Twitter makes it available to around 300 million users. Even if some percentage of these users start using SUSI.AI, increase in the user base of SUSI.AI could be exponential. Increasing the user base is advantageous as it provides with more training data for SUSI.AI to learn from. Sharing by public tweet: Integrating to it is just the first step towards increasing SUSI.AI’s user base. Next step is to reach the users and indulge them into chatting with SUSI.AI. Suppose a user asked something to SUSI.AI and really liked the reply from it. He/she wants to share it with his/her followers. This can prove to be a golden opportunity for us, to increase the reach of SUSI.AI. This way we can indulge their friends to try SUSI.AI and have an amazing time with it. It becomes clear that sharing messages is an indispensable feature and can help us a lot. Twitter doesn’t provide sharing with friends through direct messages but with a feature much better than it. We can share that message as a public tweet and cover more users including the followers of the user.   To show this button we use Call to action support by twitter: "message_data": { "text": txt, "ctas": [{ "type": "web_url", "label": "Share with your followers", "url": "" }] } The url key in the above code must have a value that redirects to a U.I. that allows to publicly tweet this reply by SUSI.AI. Using this “https://twitter.com/intent/tweet?text=" as the url value shows a new page with an empty tweet message, as the text query in the url has no value. We set the text field with a value such that we end up like this: and after tweeting it: Sending a direct message link with the tweet: Twitter provides with a lot of features when sending direct messages. Shifting a user from tweets to direct messages is beneficial in a way that we can efficiently tell the user about the capabilities of SUSI.AI and show important links to him/her like of its repository, web chat client etc. When a user tweets to the SUSI.AI page with a query, we reply with a tweet back to the user. Along with that, we provide a link to privately message SUSI.AI account if the user wants to. This way if user ends up visiting SUSI.AI in a chat window: To achieve this in SUSI Tweetbot,…

Continue ReadingMaking SUSI.AI reach more users through messenger bots

Advanced functionality in SUSI Tweetbot

SUSI AI is integrated to Twitter (blog). During the initial phase, SUSI Tweetbot had basic UI and functionalities like just “plain text” replies. Twitter provides with many more features like quick replies i.e. presenting to the user with some choices to choose from or visiting SUSI server repository by just clicking buttons during the chat etc. All these features are provided to enhance the user experience with our chatbot on Twitter. This blog post walks you through on adding these functionalities to the SUSI Tweetbot: Quick replies Buttons Quick replies: This feature provides options to the user to choose from. The user doesn’t need to type the next query but rather select a quick reply from the options available. This speeds up the process and makes it easy for the user. Also, it helps developers know all the possible queries which can come next, from the user. Hence, it helps in efficient coding on how to handle those queries.In SUSI Tweetbot this feature is used to welcome a new user to the SUSI A.I.’s chat window, as shown in the image above. The user can select any option among “Get started” and “Start chatting”.The “Get started” option is basically for introduction of SUSI A.I. to the user. While, “Start chatting” when clicked shows the user of what all queries the user can try.Let’s come to the code part on how to show these options and what events happen when a user selects one of the options. To show the Welcome message, we call SUSI API with the query as string “Welcome” and store the reply in message variable. The code snippet used: var queryUrl = 'http://api.susi.ai/susi/chat.json?q=Welcome'; var message = ''; request({ url: queryUrl, json: true }, function (err, response, data) { if (!err && response.statusCode === 200) { message = data.answers[0].actions[0].expression; } else { // handle error } }); To show options with the message: var msg = { "welcome_message" : { "message_data": { "text": message, "quick_reply": { "type": "options", "options": [ { "label": "Get started", "metadata": "external_id_1" }, { "label": "Start chatting", "metadata": "external_id_2" } ] } } } }; T.post('direct_messages/welcome_messages/new', msg, sent); The line T.post() makes a POST request to the Twitter API, to register the welcome message with Twitter for our chatbot. The return value from this request includes a welcome message id in it corresponding to this welcome message. We set up a welcome message rule for this welcome message using it’s id. By setting up the rule is to set this welcome message as the default welcome message shown to new users. Twitter also provides with custom welcome messages, information about which can be found in their official docs. The welcome message rule is set up by sending the welcome message id as a key in the request body: var welcomeId = data.welcome_message.id; var welcomeRule = { "welcome_message_rule": { "welcome_message_id": welcomeId } }; T.post('direct_messages/welcome_messages/rules/new', welcomeRule, sent); Now, we are all set to show the new users with a welcome message. Buttons: Let’s go a bit…

Continue ReadingAdvanced functionality in SUSI Tweetbot

Advanced functionality in SUSI FBbot

SUSI AI is integrated to Facebook (blog). During the initial phase, SUSI FBbot had basic UI and functionalities like just “plain text” replies. Facebook provides many more features like replies enclosed in templates (blog link), sharing the replies by SUSI A.I. with friends, get started button or a persistent menu to show quick reply options to the user etc. All these features to enhance the user experience with SUSI AI chatbot. This blog post walks you through on adding these functionalities to the SUSI FBbot: Adding Get Started button A Get Started button is added to the SUSI FBbot to give the user a brief introduction about SUSI AI and what the user can try next. Clicking on the get started button , will send the message as “Get Started” to the SUSI FBbot: The reply message, provides the user with options to visit SUSI A.I. repository or to just start chatting. To have this button in our bot, we use this code snippet: // Add a get started button to the messenger request({ url: 'https://graph.facebook.com/v2.6/me/messenger_profile', qs: {access_token:token}, method: 'POST', json: { "get_started":{ "payload":"GET_STARTED_PAYLOAD" } } }, function(error, response, body) { // handle errors and response here }) When a user clicks this button, a postback is sent to the webhook of SUSI FBbot with payload as “GET_STARTED_PAYLOAD”. When we receive such postback, we reply with a message as shown above using generic template. Adding a persistent menu to the bot If not at the start, while chatting with SUSI AI for sometime, it is quite possible that the user becomes curious to visit the repository of SUSI A.I. . So we need a quick access to the “Visit repository” button all the time. Persistent menu, helps us with this feature: This way it is accessible at each point of time. Some other buttons can also be added to the menu like “Latest News” as shown in the image above. To have a persistent menu for the SUSI FBbot, the following code snippet is used: request({ url: 'https://graph.facebook.com/v2.6/me/messenger_profile', qs: {access_token:token}, method: 'POST', json: { "persistent_menu":[{ "locale":"default", "composer_input_disabled":false, "call_to_actions":[{ "type":"web_url", "title":"Visit Repository", "url":"https://github.com/fossasia/susi_server", "webview_height_ratio":"full" }] }] } }, function(error, response, body) { // handle errors and response }) We can add more buttons to the menu. JSON object having the required properties of that button can be appended to the key “call_to_actions” to do so. Adding a messenger code to join SUSI FBbot To enable Facebook users to chat with SUSI AI by scanning a code through messenger. This feature is added to the bot by making the following POST request: request({ url: 'https://graph.facebook.com/v2.6/me/messenger_codes', qs: {access_token:token}, method: 'POST', json: { type: "standard", image_size: 1000 } }, function(error, response, body) { // handle errors and response. }); Adding message sharing feature To increase the reach of SUSI A.I. to more users on Facebook, message sharing proves to be a big boon. The reply by SUSI A.I. to users can be shared with their friends. Along with the message we can also send…

Continue ReadingAdvanced functionality in SUSI FBbot

Showing RSS and Table Type Replies in SUSI Messenger Bots

All the messengers have a “plain text” reply support. To show web search (RSS) or table type replies, either: We need a “list type” (as in Facebook messenger) or “table type” reply support built in the messenger itself.                                                               or We need to convert the RSS or table type reply by SUSI API to plain text, so that we can send it, due to the “plain text” reply support available in almost every messenger. The second point is the most favorable approach, as that way, replying with RSS or table type results is dependent only on the text support feature in the messenger. This way RSS or table type replies can be shown in messengers like REST API Gitter (which do not provide any other reply type support except text). In SUSI web app, the UI of the web search and table type results: As the SUSI web app is made in React js, it provided the app with necessary features to show the results this way. The messengers may not be having these required features. So the task is we need to convert the RSS or table type replies by SUSI API to plain text to send it to the messenger. Let’s work it out. Converting RSS results to text: First get familiar with the SUSI API reply to query “why” by visiting this url - http://api.susi.ai/susi/chat.json?q=why. The JSON object returned will be constituting an array of objects as the value of the data key like: "data": [ { "title": "Why is Oracle male?", "description": "Why is Oracle male?. http dba oracle com why is male htm. Oracle Why is masculine?. ", "link": "http://dba-oracle.com/t_why_is_oracle_male.htm" } ] If we notice carefully each object has 3 main keys namely “title”, “description” and “link”. So extracting these 3 properties from each object and binding them together into 1 string is the task we need to do. So we traverse each object (i.e. rss result) in the data array and we keep on appending the values of “title”, “description” and “link” key values to the ans variable. At the end we send this resultant string to the messenger bot as a reply.   Suppose we have the returned JSON object, in the data variable. // storing the number of rss results var metaCnt = data.answers[0].metadata.count; for(var i=0;i<metaCnt;i++){ ans += ('Title : '); ans += data.answers[0].data[i].title+', '; ans += ('Link : '); ans += data.answers[0].data[i].link+', '; ans += '\n\n'; } // send the message in ans variable to the messenger Converting table type replies to text: First get familiar with the SUSI API reply to query “why” by visiting this url - http://api.susi.ai/susi/chat.json?q=universities+in+australia. The JSON object returned will be constituting an array of objects representing universities as the value of the data key in this form: { "alpha_two_code": "AU", "name": "Australian Correspondence Schools", "country":…

Continue ReadingShowing RSS and Table Type Replies in SUSI Messenger Bots

Using Templates in SUSI FBbot

The SUSI AI Fbbot previously showed rss and table type replies as plain text to the user. To enhance the user experience, Facebook provides with templates which can be used in it’s messenger. Using those, we show rss and table type replies wrapped up in a better U.I. creating a better user experience. The 4 basic template structures that can be used for this task are: Button template Generic template List template Receipt template List template is used in SUSI A.I. Fbbot because rss reply and table type reply both are lists of data. The basic syntax for list template with reference to Fb official docs is: "message": { "attachment": { "type": "template", "payload": { "template_type": "list", "top_element_style": "compact", "elements": [ { "title": "Classic White T-Shirt", "subtitle": "100% Cotton, 200% Comfortable", "default_action": { "type": "web_url", "url": "https://peterssendreceiveapp.ngrok.io/view?item=100" }, "buttons": [ { "title": "Buy", "type": "web_url", "url": "https://peterssendreceiveapp.ngrok.io/shop?item=100" } ] } ] } } } This code shows a reply to the user like this: If we want to show a “View more” button at the end of the list, we can add a “buttons” key and an array as its value which will have information regarding all the buttons we want to show. The code below will show a “View more” button at the end of the list: "elements": [ { // all the elements, like shirt in the above case } ], "buttons": [ { "title": "View More", "type": "postback", "payload": "payload" } ] Let’s learn how to incorporate these features to rss results in SUSI Fbbot: When sending a reply using list template, “elements” key must have an array type value which will be constituted of list items. Therefore, we need to push all the rss results into that array and set it as the value of the “elements” key. Let’s develop the code part: Fetch the JSON object from SUSI API url with query as “why” i.e. http://api.susi.ai/susi/chat.json?q=why. Let body be a variable which stores the returned JSON object. The below code fills up an array (namely elementsVal) with all the rss results: var elementsVal = []; var metaCnt = body.answers[0].metadata.count; for(var i=0;i<((metaCnt>4)?4:metaCnt);i++){ elementsVal.push( { "title": body.answers[0].data[i].title, "subtitle": body.answers[0].data[i].link } ); } Setting the elementsVal array as the value of the "elements" key: var message = { "type": "template", "payload": { "template_type": "list", "top_element_style": "compact", "elements": elementsVal } }; Sending this message as a reply to the user: sendTextMessage(sender, message); Same procedure can be used to render table type replies in the bot using the list template. Generic template provided by Facebook can also used to render the web and table type replies. This template helps in showing the results in square boxes, which can be changed using left or right arrows. Resources: By Mikhail Larionov from Facebook blogs - List templates and check box plugin By Slobodan Stojanović from smashing magazine - Develop a chat bot with node js.

Continue ReadingUsing Templates in SUSI FBbot

Integration of SUSI AI to Facebook

It's easy to create your own SUSI AI Facebook messenger bot. You can read the official documentation by Facebook to get started. Messenger bots use a web server to send and receive messages. You also need to have the bot be authenticated to speak with the web server and be approved by Facebook before getting public. If any problems faced, visit the susi_fbbot repository which hosts the code for SUSI Facebook Messenger bot. We will be using Node js technology to develop the FB bot. First, let’s see on how to request an answer from the SUSI API. To call Susi API and fetch an answer from it for a query (‘hi’ in this case). Let's first visit http://api.asksusi.com/susi/chat.json?q=hi from the browser. We will get a JSON object as follows: The answer can be found as the value of the key named expression. In this case, it is “Hallo!”. To fetch the answer through coding, we can use this code snippet in Node js: // including request module var request = require(‘request’); // setting options to make a successful call to Susi API. var options = { method: 'GET', url: 'http://api.asksusi.com/susi/chat.json', qs: { timezoneOffset: '-330', q: 'hi' } }; // A request to the Susi bot request(options, function (error, response, body) { if (error) throw new Error(error); // answer fetched from susi ans = (JSON.parse(body)).answers[0].actions[0].expression; } The properties required for the call are set up through a JSON object (i.e. options). Pass the options object to our request function as its 1st parameter. The response from the API will be stored in ‘body’ variable. We need to parse this body, to be able to access the properties of that body object. Hence, fetching the answer from Susi API. Now let’s dive into the code of receiving and messaging back to the user on Facebook: A generic function to send a message to the user. // the first argument is the sender id and the second is the text to send. function sendTextMessage(sender, text) { var messageData = { text:text }; // making a post request to facebook graph API to send message. request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token:token}, method: 'POST', json: { recipient: {id:sender}, message: messageData, } }, function(error, response, body) { if (error) { console.log('Error sending messages: ', error); } else if (response.body.error) { console.log('Error: ', response.body.error); } }); } According to step 9, in the below instructions we need to include this code snippet too: // for facebook verification app.get('/webhook/', function (req, res) { if (req.query['hub.verify_token'] === 'my_voice_is_my_password_verify_me') { res.send(req.query['hub.challenge']); } res.send('Error, wrong token'); }); When user messages to our bot, we need to extract the text of the message from the request body. Then we need to extract the reply from the SUSI API and send it back to the user. // when a message from a user is received. app.post('/webhook/', function (req, res) { var messaging_events = req.body.entry[0].messaging for (var i = 0; i < messaging_events.length; i++) { // fetching the current event var event = req.body.entry[0].messaging[i];…

Continue ReadingIntegration of SUSI AI to Facebook

Integration of SUSI AI in Twitter

We will be making a Susi messenger bot on Twitter. The messenger bot will tweet back to your tweets and reply instantly when you chat with it. Feel free to tweet to the already made SUSI AI account (mentioning @SusiAI1 in it). Follow it, to have a personal chat. Make a new account, which you want to use as the bot account. You can make one from sign up option from https://www.twitter.com. Prerequisites To create your account on -: 1. Twitter 2. Github 3. Heroku 4. Node js Setup your own Messenger Bot 1. Make a new app here, to know the access token and other properties for our application. These properties will help us communicate with Twitter. Click "modify the app permissions" link, as shown here: Select the Read, Write and Access direct messages option: Don't forget to click the update settings button at the bottom. Click the Generate My Access Token and Token Secret button. 3. Create a new heroku app here. This app will accept the requests from Twitter and Susi api. 4. Create a config variable by switching to settings page of your app.      The name of your first config variable should be HEROKU_URL and its value is the url address of the heroku app created by you.   The other config variables that need to be created will be these:   The corresponding names of these variables in the same order are:   i) Access token   ii) Access token secret   iii) Consumer key   iv) Consumer secret    We need to visit our app from here, the keys and access tokens tab will help us with the values of these variables. Let’s start with the code part of the integration of SUSI AI to Twitter. We will be using Node js to achieve this integration. First we need to require some packages: Now using the Twit module, we need to authenticate our requests, by using our environment variables as set up in step 4: Now let’s make a user stream: var stream = T.stream('user'); We will be using the capabilities of this stream, to catch events of getting tweeted or receiving a direct message by using: stream.on('tweet', functionToBeCalledWhenTweeted); stream.on('follow', functionToBeCalledWhenFollowed); stream.on('direct_message', functionToBeCalledWhenDirectMessaged); So, when a person tweets to our account like this: We can catch it with ‘tweet’ event and execute a set of instructions: stream.on('tweet', tweetEvent); function tweetEvent(eventMsg) { var replyto = eventMsg.in_reply_to_screen_name; // to store the message tweeted excluding '@SusiAI1' substring var text = eventMsg.text.substring(9); // to store the name of the tweeter var from = eventMsg.user.screen_name; if (replyto === 'SusiAI1') { var queryUrl = 'http://api.asksusi.com/susi/chat.json?q=' + encodeURI(text); var message = ''; request({ url: queryUrl, json: true }, function (err, response, data) { if (!err && response.statusCode === 200) { // fetching the answer from the data object returned message = data.answers[0].actions[0].expression + data; } else { message = 'Oops, Looks like Susi is taking a break'; console.log(err); } console.log(message); // If the message length is more than tweet limit if(message.length > 140){ tweetIt('@'…

Continue ReadingIntegration of SUSI AI in Twitter