다음을 통해 공유


Microsoft Bot Framework Basics: Building Intelligent Bots – Adding Bing News API (Part 3)

Scope

The following articles demonstrates the use of the Bing News API from Microsoft Cognitive Services in a bot using the Microsoft Bot Framework. This article will build on the previous articles about Bot Framework where the basics of building a bot and the integration of Language Understanding API was demonstrated.
The objective is to allow a user to send a message to the bot, the bot will use language understanding capability to understand the message, fetch news based on the user input using Bing API and return the results to the user.

Introduction

The News API provides a similar (but not exact) experience to Bing.com/News. The News API lets you send a search query to Bing and get back a list of relevant news articles.
Bing News API also includes authoritative images of the news article, related news and categories, provider information, article URLs, and dates when images were added.

Adding the Bing News API

At this stage, we have set up our project and we have successfully implemented Language Understanding in our bot. It’s now time to build the search functionality using the Bing News API.
What will happen is that once LUIS identify a sentence as a news, it will then return us the News Entity, that is, the item about which the user is trying to search for news. We’ll then take this entity and pass it to the Bing News API to get the results.

To connect to the Bing News API, follow the steps here to register and get the keys. The API takes a text and input and returns a JSON of all the news item as shown below.

{
  "_type": "News",
  "readLink": "https://api.cognitive.microsoft.com/api/v5/news/search?q=football",
  "totalEstimatedMatches": 1980000,
  "value": [
    {
      "name": "Tennessee <b>Football</b>: Former Coach Phillip Fulmer Takes Shot at Lane Kiffin",
      "url": "http://www.bing.com/cr?IG=6E1D71ECB12642478D9B43CABFE6D6DA&CID=368054890FCB699507CA5ECA0EFA68F3&rd=1&h=hHf7Kln-pgk2Ygz0QhP5uZ6DaajSR6YII2JGClvmfYA&v=1&r=http%3a%2f%2fallfortennessee.com%2f2017%2f03%2f10%2ftennessee-football-fulmer-kiffin%2f&p=DevEx,5023.1",
      "image": {
        "thumbnail": {
          "contentUrl": "https://www.bing.com/th?id=ON.3093BAC7465DF3974947D6AFC8A00B69&pid=News",
          "width": 700,
          "height": 461
        }
      },…

Once we have subscribed to the Bing News API, follow the steps below to add the code to the bot to retrieve the news.

Create function GetBingNews to fetch the news. 

The function getBingNews takes the news to search as a parameter, makes a connection to the Bing News API, passes the parameter to it and gets the JSON response of the news back.
Then, it is deserialized and converted to a List of news using the JsonConvert library.

private async Task<BingNews> getBingNews(string query)
        {
            BingNews bingNews;
            String bingUri = "https://api.cognitive.microsoft.com/bing/v5.0/news/search/?count=50&q=" + query;
            string rawResponse;
 
            HttpClient httpClient = new  HttpClient()
            {
                DefaultRequestHeaders = {
                    {"Ocp-Apim-Subscription-Key", "SUBSCRIPTION KEY"},
                    {"Accept", "application/json"}
            }
            };
 
            try
            {
                rawResponse = await httpClient.GetStringAsync(bingUri);
                bingNews = JsonConvert.DeserializeObject<BingNews>(rawResponse);
            }
            catch (Exception e)
            {
                return null;
            }
            return bingNews;
        }

In the SearchNews intent, add the following code to retrieve the entity. It is this retrieved entity that represents the news that we need to search

EntityRecommendation newsEntity;
if (result.TryFindEntity("NewsItem", out  newsEntity)) {…}

Call the getBingNews method using the intent

BingNews bingNews = await getBingNews(newsEntity.Entity);

Check if there are no news returned and inform the user accordingly

var message = await activity;
var reply = context.MakeMessage();
 
if (bingNews == null || bingNews.totalEstimatedMatches == 0)
{
     reply.Text = "Sorry, couldn't find any news about '"  + newsEntity.Entity;
}

Display the news to the user

reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
reply.Attachments = new  List<Microsoft.Bot.Connector.Attachment>();
for (int i = 0; i < 10 && i < (bingNews?.totalEstimatedMatches ?? 0); i
{
    var article = bingNews.value[i];
    HeroCard attachment = new  HeroCard()
    {
        Title = article.name.Length > 60 ? article.name.Substring(0, 57) + "..." : article.name,
        Text = article.provider[0].name + ", " + article.datePublished.ToString("d") + " - " + article.description,
        Images = new  List<CardImage>() { new CardImage(article.image?.thumbnail?.contentUrl +  "&w=400&h=400") },
        Buttons = new  List<CardAction>() { new CardAction(
                                                        ActionTypes.OpenUrl,
                                                        title: "View on Web",
                                                        value: article.url)}
    };
    reply.Attachments.Add(attachment.ToAttachment());
}
await context.PostAsync(reply);
context.Wait(this.MessageReceived);

Test the bot in the emulator

See Also

  1. Microsoft Bot Framework Basics: Building Intelligent Bots (Part 1)
  2. Microsoft Bot Framework Basics: Building Intelligent Bots - Adding Language Understanding Capability (Part 2)

** **

References

  1. Searching the web for news