且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从网络服务向机器人发送消息

更新时间:2023-11-19 12:34:22

这里是从另一个应用程序向机器人发送消息的示例.在这种情况下,我是通过Web API进行此操作的,Web API是一个代理,可拦截来自用户的消息并将其发送给机器人.这段代码中没有包含如何构造活动的信息,但是看起来您已经将该部分归类了.请注意,在此辅助应用程序中,我使用的是Bot.Builder,因此我可以使用活动对象和其他功能.

Here is an example of sending a message to a bot from another application. In this case I was doing this from a web API which was a proxy intercepting messages from the user and sending them to the bot. Not included in this code is how to construct an activity, but it looks like you have that part sorted our already. Note that in this secondary application I was using Bot.Builder so I could use activity objects and other features.

//get a token (See below)
var token = GetToken();

//set the service url where you want this activity to be replied to
activity.ServiceUrl = "http://localhost:4643/api/return";

//convert an activity to json to send to bot
var jsonActivityAltered = JsonConvert.SerializeObject(activity);

//send a Web Request to the bot
using (var client = new WebClient())
{
    //add your headers
    client.Headers.Add("Content-Type", "application/json");
    client.Headers.Add("Authorization", $"Bearer {token}");

    try
    {
        //set where to to send the request {Your Bots Endpoint}
        var btmResponse = client.UploadString("http://localhost:3971/api/messages", jsonActivityAltered);
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
}

获取令牌:

private static string GetToken()
{
    string token;
    using (var client = new WebClient())
    {
        var values = new NameValueCollection();
        values["grant_type"] = "client_credentials";
        values["client_id"] = "{MS APP ID}";
        values["client_secret"] = "{MS APP SECRET}";
        values["scope"] = "{MS APP ID}/.default";

        var response =
            client.UploadValues("https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token", values);

        var responseString = Encoding.Default.GetString(response);
        var result = JsonConvert.DeserializeObject<ResponseObject>(responseString);
        token = result.access_token;
    }

    return token;
}

响应对象类:

public class ResponseObject
{
    public string token_type { get; set; }
    public int expires_in { get; set; }
    public int ext_expires_in { get; set; }
    public string access_token { get; set; }
}