2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

クラウドAI開発講座 Microsoftと高専キャリアがコラボ #6

Last updated at Posted at 2020-08-12

クラウドAI開発講座

マイクロソフトと高専キャリア教育研究所が共催するAI開発プログラム
無料で参加でき、困ったときにはメンターに相談ができるオンラインプログラム

進歩

Twitter developersアカウントに登録申請がやっと通り、おーちょさんの記事を参考にして、優しい言葉を返してくれるbotが遂に完成しました。その結果を報告します。

やさしいbot

今回作成したのは、ポジティブな言葉をかけると塩対応し、ネガティブな言葉をかけると偉人のありがたい言葉をかけてくれるbotです。うまいこと動作してくれました。
6-1.PNG

プログラム全体は次のようになっています。

EchoBot.cs
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Schema;

//for TextAnalytics
using System;
using System.Net.Http;
using Microsoft.Azure.CognitiveServices.Language.TextAnalytics;
using Microsoft.Azure.CognitiveServices.Language.TextAnalytics.Models;
using Microsoft.Rest;
using System.Diagnostics;
using CoreTweet;

namespace YasashiiBot.Bots
{
    public class EchoBot : ActivityHandler
    {
        private static readonly string key = "27bf963e7f5542d78d2093f33f93663d";
        private static readonly string endpoint = "https://yasashiibottextanalytics.cognitiveservices.azure.com/";

        protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            
            //for TextAnalytics
            var client = authenticateClient();
            var score = sentimentAnalysisExample(client, turnContext.Activity.RemoveRecipientMention()); 
            var res = "";
          

            if (0.5 <= score)
            {
                res = getShioComment();

            }
            else
            {
                res = getTweet();

            }

            res = $"Score:{score:0.00}" + Environment.NewLine + res;
            await turnContext.SendActivityAsync(MessageFactory.Text(res), cancellationToken);
        }

        protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
        {
            var welcomeText = "Hello and welcome!";
            foreach (var member in membersAdded)
            {
                if (member.Id != turnContext.Activity.Recipient.Id)
                {
                    await turnContext.SendActivityAsync(MessageFactory.Text(welcomeText, welcomeText), cancellationToken);
                }
            }
        }

        //for TextAnalytics
        static TextAnalyticsClient authenticateClient()
        {
            ApiKeyServiceClientCredentials credentials = new ApiKeyServiceClientCredentials(key);
            TextAnalyticsClient client = new TextAnalyticsClient(credentials)
            {
                Endpoint = endpoint
            };
            return client;
        }

        //for TextAnalytics
        static double sentimentAnalysisExample(ITextAnalyticsClient client, string message)
        {
            var result = client.Sentiment(message, "ja"); 
            return (double)result.Score; 
        }

        static string getTweet()
        {
            Random cRandom = new System.Random(); 
            var tokens = Tokens.Create("N1eh9z5iLUs7Xnna6RTHcq80E", "JqrJ7GQeAC23SllxH8XVp3vRAL0VB18vNZMwncXTptuJequk8H", "1281859988290301953-nX8cxCXu4wCuTqPxr9x0hyeuVJZZN7", "UZICOJlHfmYC7ebv78QRLOpGpk5Pv5lhp8XyQJh0PiiMW");  
            var tweet = "";

            var parm = new Dictionary<string, object>(); 
            parm["count"] = 60; 
            parm["screen_name"] = "hagemasi1_bot";  

            Task task = Task.Factory.StartNew(async () =>
            {
                var tweets = await tokens.Statuses.UserTimelineAsync(parm); 
                var random = cRandom.Next(61);
                tweet = tweets[random].Text; 

            }).Unwrap();

            task.Wait();

            return tweet;
        }

        static string getShioComment()
        {
            Random cRandom = new System.Random();
            string res = "";
            var shio = new string[] { "へー・・・。", "・・・だから?", "知らんわー。", "興味ないね。", "いや、聞いてないし。", "ふーん・・・。で?", "そういうのいいから。", "あーちょっと今忙しいからまた今度。", "・・・けっ!", "リア充乙。" };

            var random = cRandom.Next(11);
            res = shio[random];
            return res;
        }
    }
}

//for TextAnalytics
class ApiKeyServiceClientCredentials : ServiceClientCredentials
{
    private readonly string apiKey;

    public ApiKeyServiceClientCredentials(string apiKey)
    {
        this.apiKey = apiKey;
    }

    public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request == null)
        {
            throw new ArgumentNullException("request");
        }
        request.Headers.Add("Ocp-Apim-Subscription-Key", this.apiKey);
        return base.ProcessHttpRequestAsync(request, cancellationToken);
    }
}

高専キャリアONLINEの提供コンテンツ(高専キャリア教育研究所)

高専キャリアONLINEの提供コンテンツ(高専キャリア教育研究所

2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?