Microsoft MVP MunChan Park kaki104@daum.net Windows Platform Development MVP www.facebook.com/groups/w10app 유튜브채널 Using OneDrive in a Bot Framework
환경및준비 가능하면모두영문버전사용을추천 Windows 10 version 1709 (16299.x) 가능하면최신버전으로.. Visual Studio 2017 version 15.6.x 가능하면최신버전으로.. Microsoft Bot Framework V3.0 Microsoft Azure 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 Bot Service Microsoft 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 <add key="botid" value="kakionedrivebot" /> <add key="microsoftappid" value= " /> <add key="microsoftapppassword" value= " /> <!-- AAD settings...register your own at https://apps.dev.microsoft.com --> <add key="aad:clientid" value= AppId 와동일 " /> <add key="aad:clientsecret" value= AppPassword 와동일 " /> <add key="aad:authority" value="https://login.microsoftonline.com/common" /> <add key="aad:callback" value="http://localhost:3979/callback" /> 콜백주소입력은 https://apps.dev.microsoft.com 에서입력한값을사용
MicrosoftAppId, ClientId MicrosoftAppPassword, ClientSecret Callback Add 클릭
OneDriveBot 작업순서 1 봇생성 BotAuth 설치및 https://github.com/microsoftdx/bot auth 셈플다운로드 Web.config 수정 RootDialog.cs 수정 셈플에서 magic.htm 파일복사후프로젝트에추가 디버그실행 Bot Framework Emulator 로테스트 -> Settings -> Service -> ngrok 경로입력 Publish
OneDriveBot 작업순서 2 Azure Bot Service Bot Channel 생성 (https://youtu.be/quqpjmgc01q 참고 ) 생성된 Channel 로이동 Settings Microsoft App ID -> Manage 클릭 Microsoft Application Registration Portal Bot 과연결된 application 페이지로이동 Application Secrets Generate New Password 클릭 -> 복사 Platforms Add Platform -> Web Redirect URLs https://localhost:3979/callback ( 로컬테스트시 ) https://bot 주소.azurewebsites.net/Callback ( 운영시 ) Microsoft Graph Permissions Application Permissions -> Add -> Files.Read 선택
OneDriveBot 작업순서 3 Web.config Application Id, Application Secrets 붙여넣기 Callback 주소입력 https://localhost:3979/callback ( 로컬테스트시, 포트번호주의 ) https://bot.azurewebsites.net/callback ( 운영시 ) Publish 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<AuthResult> 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<string>("graphquery")); var root = JsonConvert.DeserializeObject<Rootobject>(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<MediaUrl> { new MediaUrl(music.microsoftgraphdownloadUrl) }, Buttons = new List<CardAction> { 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