Bots are just like your buddies with whom you can interact. They carry out your tasks, keep you notified about your to-dos and come in handy when you need constant updates from a third party application.
So, how can you make your bot respond to a message?
The bot message handler is a piece of code triggered when a message is sent to the bot. Message handlers help you customise your bot responses to make it look conversational. The message input from the user can be either a string or an option selected from the bot suggestions.
Let us try building a utility bot, that will bring us the top news from a particular category chosen from the list of suggestions.
The sample workflow on triggering this handler is given below.
- The user pings the bot to get a list of current top trending news.
- Message handler of the bot identifies a keyword from the user's input and is triggered to respond with a list of categories for the user to choose from.
- Once the user selects an option, the message input is again captured to call the corresponding API.
- This API response is shared by the bot to the user in a card format!
A sample code snippet for the above-mentioned scenario is given below. Take a look!
- response = Map();
- categories = {"Business","Entertainment","Gaming","General","Health-and-Medical","Music","Politics","Science-and-Nature","Sport","Technology"};
- if(message.containsIgnoreCase("NEWS") || message.containsIgnoreCase(" BREAKING NEWS") || message.containsIgnoreCase("HEADLINES"))
- {
- list = List();
- for each category in categories
- {
- entry = Map();
- entry.put("text",category);
- list.add(entry);
- }
- suggestion = Map();
- suggestion.put("list", list);
-
- response.put("text","Hey " + user.get("first_name") + " ,choose one option from the list! I can help you with these. :smile:");
- response.put("suggestions",suggestion);
- }
- else if(categories.containsIgnoreCase(message))
- {
- url = getUrl("https://newsapi.org/v2/top-headlines?category=" + message.toLowerCase() + "&language=en&apiKey=<Insert_API_Key>");
- newslist = url.get("articles");
- rows = List();
- count = 0;
- for each news in newslist
- {
- count = count + 1;
- row = Map();
- row.put("Headline",news.get("title"));
- row.put("View Link","[Read More](" + news.get("url") + ")");
- if(count <= 10)
- {
- rows.add(row);
- }
- }
- return {"text":"Hello! Here's the top news in the " + message + " category!","card":{"theme":"modern-inline","title":"Hi " + user.get("first_name") + " :smile:"},"slides":{{"type":"table","data":{"headers":{"Headline","View Link"},"rows":rows}}}};
- }
- else
- {
- return {"text": "Hello There, this looks like an invalid category! Just try typing *News* or *Breaking News* or *Headlines*"};
- }
- return response;
The bot message handler is the easiest way to get started with building an interactive bot. So get started with it right away!
Few useful links:
Comments and suggestions are welcome!
Best,
Manasa
Cliq