Microsoft MVP

MunChan Park

[email protected]

Windows Platform Development MVP

www.facebook.com/groups/w10app

유튜브 채널 Using OneDrive in a Bot Framework • 가능하면 모두 영문 버전 사용을 추천 • version 1709 (16299.x) • 가능 하면 최신 버전으로.. • Visual Studio 2017 version 15.6.x 환경 및 준비 • 가능 하면 최신 버전으로.. • Bot Framework V3.0 • Account • Windows Software Development Kit (Windows SDK) 10.0.16299 • Bot Service Documentation • ngrok (for local test) • Microsoft Graph • Microsoft Application Registration Portal • Add audio streaming to your skill 참고 자료 • csharp-bot-onedrive • Botauth • OneDrive and SharePoint in Microsoft Graph Rest APIs • Use query parameters to customize response Microsoft Graph

• Microsoft Graph API를 사용하여 Microsoft 클라우드에 있는 여러 서비스를 사용할 수 있습니다. • Microsoft Graph를 이용해서 접근할 수 있는 서비스 • Files(OneDrive), Calendar, Messages, People, Devices … • Microsoft Graph를 이용해서 무엇을 할 수 있나요? • 다음 모임을보고 참석자에게 직책과 함께 일하는 사람, 작업중인 최신 문서 및 프 로젝트에 대한 정보를 제공하여 준비를 도와줍니다. • 캘린더를 스캔하고 다음 팀 회의에 가장 적합한 시간을 제안합니다. • OneDrive의 Excel 파일에서 최신 판매 계획 차트를 가져 와서 휴대 전화에서 실 시간으로 예측을 업데이트 할 수 있습니다. • 캘린더의 변경 사항을 구독하고 회의에 너무 많은 시간을 할애하면 알림을 보내 며, 참석자의 관련성에 따라 놓치거나 위임 할 수있는 알림을 제공합니다. • 휴대 전화에서 개인 정보 및 직장 정보를 정리할 수 있습니다. 예를 들어 개인 OneDrive로 이동해야하는 사진과 비즈니스 용 OneDrive로 이동해야하는 사업 영수증을 분류하면됩니다. Graph Explorer 시스템 구성

사용자 Azure Microsoft Bot Service https://login.microsoftonline.com/common

OneDriveBot

Magic Number Page Microsoft Graph https://graph.microsoft.com/v1.0/me/drive

BotAuth

• Bot에서 인증을 할 수 있게 지 원하는 누겟 패키지 • Authentication middleware for the botframework • Csharp, Node • Include prerelease 체크! • Browse 탭에서 botauth 입력 • BotAuth, BotAuth.AADv2 설치 Bot 개발

실습 Web.config

• appSettings • • • • 콜백 주소 입력은 https://apps.dev.microsoft.com에서 입력한 값을 사용 MicrosoftAppId, ClientId

MicrosoftAppPassword, ClientSecret

Callback

Add 클릭 • 봇 생성 • BotAuth • 설치 및 https://github.com/MicrosoftDX/bot auth 셈플 다운로드 • Web.config 수정 OneDriveBot • RootDialog.cs 수정 작업 순서1 • 셈플에서 magic.htm 파일 복사 후 프로젝트에 추가 • 디버그 실행 • Bot Framework Emulator로 테스트 • … -> Settings -> Service -> ngrok 경로 입력 • Publish • Azure Bot Service • Bot Channel 생성(https://youtu.be/QuqPJmgc01Q 참고) • 생성된 Channel로 이동 • Settings • Microsoft App ID -> Manage 클릭 • Microsoft Application Registration Portal • Bot과 연결된 application 페이지로 이동 • Application Secrets OneDriveBot • Generate New Password 클릭 -> 복사 • Platforms 작업 순서2 • Add Platform -> Web • Redirect URLs • https://localhost:3979/Callback (로컬 테스트 시) • https://bot주소.azurewebsites.net/Callback (운영시) • Microsoft Graph Permissions • Application Permissions -> Add -> Files.Read 선택 • Web.config • Application Id, Application Secrets 붙여넣기 • Callback 주소 입력 • https://localhost:3979/Callback (로컬 테스 트시, 포트번호 주의) • https://bot.azurewebsites.net/Callback OneDriveBot (운영시) • Publish 작업 순서3 • Bot Framework Emulator로 테스트시 • AppId, AppPassword 입력하고 테스트 • 주의! • 인증 과정 중 오류가 발생하는 대부분의 이유는 콜백 주소 문제가 많습니다. 주소는 철저히 확인 부탁드립니다. 봇 인증 핵심 코드 RootDialog.cs

private readonly AuthenticationOptions _authenticationOptions = new AuthenticationOptions() { Authority = ConfigurationManager.AppSettings["aad:Authority"], ClientId = ConfigurationManager.AppSettings["aad:ClientId"], ClientSecret = ConfigurationManager.AppSettings["aad:ClientSecret"], Scopes = new[] { "Files.Read" }, RedirectUrl = ConfigurationManager.AppSettings["aad:Callback"], MagicNumberView = "/magic.html#{0}" }; var query = "https://graph.microsoft.com/v1.0/me/drive/special/music/children?$top=5"; // Save the query so we can run it after authenticating context.ConversationData.SetValue("GraphQuery", query); // Forward the dialog to the AuthDialog to sign the user in and get an access token for calling the Microsoft Graph and then execute the specific action await context.Forward(new AuthDialog(new MSALAuthProvider(), _authenticationOptions), GetOneDriveMusicFiles, activity, CancellationToken.None); RootDialog.cs

private async Task GetOneDriveMusicFiles(IDialogContext context, IAwaitable result) { // Getting the token from the Microsoft Graph var tokenInfo = await result;

// Get the Documents from the OneDrive of the Signed-In User var json = await new HttpClient().GetWithAuthAsync(tokenInfo.AccessToken, context.ConversationData.GetValue("GraphQuery"));

var root = JsonConvert.DeserializeObject(json.ToString()); var reply = ((Activity) context.Activity).CreateReply();

foreach (var music in root.value) { var audioCard = new AudioCard { Title = music.name, Subtitle = $"Artist: {music.audio.artist}, Genre: {music.audio.genre}", Media = new List { new MediaUrl(music.microsoftgraphdownloadUrl) }, Buttons = new List { new CardAction(ActionTypes.OpenUrl, "Open File", value: music.webUrl) } }; if (reply.Attachments.Any() == false) audioCard.Autostart = true; reply.Attachments.Add(audioCard.ToAttachment()); } reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

var client = new ConnectorClient(new Uri(context.Activity.ServiceUrl)); await client.Conversations.ReplyToActivityAsync(reply); } 최종 소스 https://github.com/kaki104/bot Mobile-First, Cloud-First