Aida-chiyo-Talk-app

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

A3RTService.cs (2457B)


      1 using Newtonsoft.Json.Linq;
      2 using System;
      3 using System.Collections.Generic;
      4 using System.Linq;
      5 using System.Text;
      6 using System.Threading.Tasks;
      7 
      8 namespace Aida_chiyo_Talk_app
      9 {
     10     internal class A3RTService
     11     {
     12         private string APIKEY;
     13 
     14         /// <summary>
     15         /// コンストラクタ
     16         /// </summary>
     17         internal A3RTService()
     18         {
     19             // App.configから設定を取得
     20             APIKEY = "DZZqpz3HVnJL4LGk57u8ZfmgfAIjrB3B";
     21 
     22             // 必要な情報が取得できない場合はエラー
     23             if (string.IsNullOrEmpty(APIKEY))
     24             {
     25                 throw new ArgumentException("A3RT_APIKEY is empty");
     26             }
     27         }
     28 
     29         /// <summary>
     30         /// 対話APIを実行し、応答文を返す
     31         /// </summary>
     32         /// <param name="message">発言</param>
     33         /// <returns>応答</returns>
     34         internal async Task<string> MakeRequestAsync(string message)
     35         {
     36             HttpClient client = new HttpClient();
     37 
     38             // リクエストURL
     39             string uri = $"https://api.a3rt.recruit.co.jp/talk/v1/smalltalk";
     40 
     41             // リクエスト本文
     42             var content = new FormUrlEncodedContent(
     43                 new Dictionary<string, string>
     44                 {
     45                     { "apikey", APIKEY },
     46                     { "query", message }
     47                 });
     48 
     49             // APIを実行し、レスポンス本文を取得
     50             HttpResponseMessage response = await client.PostAsync(uri, content);
     51             JObject rss = await response.Content.ReadAsAsync<JObject>();
     52 
     53             // HTTPステータスが異常であればエラー
     54             if (!response.IsSuccessStatusCode)
     55             {
     56                 throw new ApplicationException(
     57                     $"API failed. code={response.StatusCode}");
     58             }
     59 
     60             // 何も返さなかった場合は、何か埋めて返しておく
     61             if ((int)rss["status"] == 2000)
     62             {
     63                 return "...";
     64             }
     65             // APIがエラーを出していればエラー
     66             else if ((int)rss["status"] != 0)
     67             {
     68                 Console.WriteLine(rss);
     69                 throw new ApplicationException(
     70                     $"API failed. ");
     71             }
     72 
     73             // レスポンス本文から応答文のみを抽出して返す
     74             return (string)rss["results"][0]["reply"];
     75         }
     76     }
     77 }