読者です 読者をやめる 読者になる 読者になる

かずきのBlog@hatena

日本マイクロソフトに勤めています。XAML + C#の組み合わせをメインに、たまにASP.NETやJavaなどの.NET系以外のことも書いています。掲載内容は個人の見解であり、所属する企業を代表するものではありません。

Xamarin.FormsでBotFrameworkのDirectLineを試す

自分用メモです。(雑です)

PCLを辞めます。 .NET Standardにプロジェクトを変換します。

以下をプロジェクトに追加する。

  • Micrsoft.Bot.Connector.DirectrLine
  • Microsoft.Rest.ClientRuntime

こんな感じに書けば動いた!とりあえず

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="PrismUnityApp4.Views.MainPage"
             Title="MainPage">
  <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
    <Button Text="Send"
            Command="{Binding SendCommand}" />
    <Button Text="NewConversation"
            Command="{Binding NewConversationCommand}" />
    <Label Text="{Binding Message}" />
  </StackLayout>
</ContentPage>

C#

using Microsoft.Bot.Connector.DirectLine;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using System.Linq;

namespace PrismUnityApp4.ViewModels
{
    public class MainPageViewModel : BindableBase, INavigationAware
    {
        private static readonly string Secret = "DirectLine の シークレット";
        private static readonly string Id = "okazuki";

        private Conversation Conversation { get; set; }

        public DelegateCommand SendCommand { get; }

        public DelegateCommand NewConversationCommand { get; }

        private string message;

        public string Message
        {
            get { return this.message; }
            set { this.SetProperty(ref this.message, value); }
        }

        public MainPageViewModel()
        {
            this.SendCommand = new DelegateCommand(Send);
            this.NewConversationCommand = new DelegateCommand(() => this.Conversation = null);
        }

        private async void Send()
        {
            var client = new DirectLineClient(Secret);
            if (this.Conversation == null)
            {
                this.Conversation = await client.Conversations.StartConversationAsync();
            }

            var activity = Activity.CreateMessageActivity() as Activity;
            activity.From = new ChannelAccount { Id = Id };
            activity.Text = "Hello world";
            var response = await client.Conversations.PostActivityAsync(this.Conversation.ConversationId, activity);
            var activities = await client.Conversations.GetActivitiesAsync(this.Conversation.ConversationId);
            var result = activities.Activities.FirstOrDefault(x => x.ReplyToId == response.Id);

            this.Message = result?.Text;
        }

        public void OnNavigatedFrom(NavigationParameters parameters)
        {

        }

        public void OnNavigatedTo(NavigationParameters parameters)
        {
        }
    }
}