LoginSignup
0
0

More than 5 years have passed since last update.

Dialogflow のエージェントに C# でメッセージを送る

Posted at

簡単に対話型エージェントを作れて何やらすごそうな Dialogflow ですが C# から触るにあたって情報が少なくて嵌ったため共有します。

事前準備

  • エージェントを作る
    • 私はこちらの記事を参考にさせていただきました。ありがとうございます。
  • 認証の設定(JSONファイルを取得)

C# でメッセージを送る

NuGet パッケージのインストール

Google.Apis.Dialogflow.v2 を入れます。

サンプルソース

Program.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Dialogflow.v2;
using Google.Apis.Dialogflow.v2.Data;
using Google.Apis.Services;
using System;
using System.IO;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        private static readonly string PROJECT_ID = "yourProjectId";
        private static readonly string CREDENTIAL_PATH = @"Your\Credential\Path.json";

        static void Main(string[] args)
        {
            var sessionId = Guid.NewGuid().ToString();
            var message = "hoge";
            var response = RequestAsync(sessionId, message).Result;
        }

        private static async Task<GoogleCloudDialogflowV2DetectIntentResponse> RequestAsync(string sessionId, string message)
        {
            ServiceAccountCredential credential;
            using (var stream = new FileStream(CREDENTIAL_PATH, FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream)
                                             .CreateScoped(DialogflowService.Scope.CloudPlatform)
                                             .UnderlyingCredential as ServiceAccountCredential;
            }

            var service = new DialogflowService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
            });

            var request = service.Projects.Agent.Sessions.DetectIntent(new GoogleCloudDialogflowV2DetectIntentRequest
            {
                QueryInput = new GoogleCloudDialogflowV2QueryInput
                {
                    Text = new GoogleCloudDialogflowV2TextInput
                    {
                        Text = message,
                        LanguageCode = "ja",
                    },
                },
            }, $"projects/{PROJECT_ID}/agent/sessions/{sessionId}");

            return await request.ExecuteAsync();
        }
    }
}

コンソールアプリでやるならこんな感じ。

所感とか

  • GCP の API はライブラリ使う前提?
    • 生の REST API を触らせる想定じゃなさそう → C# は GCP 的にマイナー言語なので情報が少なくて悲しい
  • Programatically 触る動機
    • Slack や Line などと連携する機能を Dialogflow 自体が持っているので自前で連携する必要は無い場合が多そう
    • とはいっても連携が実装されてないサービス(Microsoft Teams とか)もあるし、Bot を開発するとなると何かに依存せずに色んなチャットツールに乗せられる形で作りたい
    • → じゃあ自前で連携できるかどうか一応確認しとかなきゃ的な
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0