我使用VS Code開發已經有蠻長一段時間了,時間長了,越來越喜歡VS Code,雖然有些時候會沒有傳統的VS方便,比如開發Azure Function時你需要編寫一下launch.json,而且你需要手動啟動StorageEmulator,但是也正是由于缺少VS的自動配置,需要你自己手動把環境一步步搭建出來,也讓自己更加理解一些框架和技術。
最近練習做一個簡單的docker image,并且想做一個windows上的image,但是下載一個server core的image讓我崩潰了,雖然能夠下載,但是那個速度簡直瘋掉了,等待一個晚上下載完成后,我做了一個image需要upload到ACR,那個叫龜速,而且我稍微一改代碼就要重新build,重新docker build,重新docker push。雖然我的layer很小,而且ACR也選擇了離我最近的region創建的,但是一次push我都可以完成一杯咖啡了。
后來,我突然想到了VSCode的Remote功能,立刻在云端創建了一臺linux虛機,在上面做開發,瞬間感覺到了云時代的優勢了,雖然我的虛機配置很低,但整個docker build,push過程比在本地快了起碼10倍,而且VScode的remote體驗很好,基本感覺不到在remote的感覺。
所以我想在這篇博客里介紹了一下,如何在VSCode Remote環境下開發Teams Bot。如果你還沒有remote環境的話,可以參考?這個?來搭建一個remote的開發環境,然后安裝最新的?dotnet SDK
先ssh到遠程,我們先創建一個簡單的webapi
$ mkdir test-bot
$ cd test-bot
$ dotnet new webapi
在VSCode里打開這個遠程folder。打開test-bot.csproj
,增加這兩個package
<ItemGroup><PackageReference Include="Microsoft.Bot.Builder.Integration.AspNet.Core" Version="4.9.2" /></ItemGroup>
打開Startup.cs文件,簡化Configure方法
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){app.UseRouting();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}
到controller目錄下,創建一個新的BotController.cs
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Integration.AspNet.Core;
using Microsoft.Bot.Schema;namespace test_bot.Controllers
{[Route("api/messages")][ApiController]public class BotController : ControllerBase{private static readonly IBotFrameworkHttpAdapter Adapter = new BotFrameworkHttpAdapter();[HttpPost, HttpGet]public async Task PostAsync(){await Adapter.ProcessAsync(Request, Response, new EchoBot());}}public class EchoBot : ActivityHandler{protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken){var replyText = $"Echo: {turnContext.Activity.Text}";await turnContext.SendActivityAsync(MessageFactory.Text(replyText, replyText), cancellationToken);}}
}
我還需要一個工具ngrok,先在remote運行下面這個命令安裝ngrok,然后啟動ngrok
$ sudo snap install ngrok
$ ngrok http 5000
?
在本地啟動bot emulator,增加一個bot endpoint,輸入上面ngrok產生的一個url
?
因為我們是用本機的bot emulator連到另一臺機器的bot service,所以我們本地的bot emulator需要配置本地ngrok的路徑,如下圖:
?
完成后,我們就可以在emulator里打開這個bot,發送文字,然后就可以收到你的remote bot的回復了。 :D
?