我正在从.NET机器人启动一个网页。该页面与我们的后端系统之一的用户进行交互。互动结束后,我需要向机器人发送状态更新消息-它位于上下文中。请等待该消息。
该机器人当前正在使用Facebook频道,并通过Facebook Url按钮启动页面,但最终它将需要跨多个渠道工作。
从网站上,我可以轻松地向用户发送消息,但是尽管花了很多时间进行搜索和尝试各种机制,但我仍未找到向机器人发送消息的方法。
基于https://docs.botframework.com/en-us/csharp/builder/sdkreference/d1/df2/_conversation_reference_ex_8cs_source.html的最新尝试,(cr已缓存对话详细信息):
string MicrosoftAppId = ConfigurationManager.AppSettings["MicrosoftAppId"];
string MicrosoftAppPassword = ConfigurationManager.AppSettings["MicrosoftAppPassword"];
var account = new MicrosoftAppCredentials(MicrosoftAppId, MicrosoftAppPassword);
MicrosoftAppCredentials.TrustServiceUrl(cr.serviceUrl);
var connector = new ConnectorClient(new Uri(cr.serviceUrl), account);
Activity activity = new Activity
{
Type = ActivityTypes.Message,
Id = Guid.NewGuid().ToString(),
Recipient = new ChannelAccount
{
Id = cr.bot.id,
Name = cr.bot.name
},
ChannelId = cr.channelId,
ServiceUrl = cr.serviceUrl,
Conversation = new ConversationAccount
{
Id = cr.conversation.id,
IsGroup = false,
Name = null
},
From = new ChannelAccount
{
Id = cr.bot.id,
Name = cr.bot.name
},
Text = "Test send message to bot from web service"
};
try
{
await connector.Conversations.SendToConversationAsync(activity);
}
catch (Exception ex)
{
var s = ex.Message;
}
但是似乎没有“发自/收件人”的组合发送到bot。
我确定我缺少简单的东西,你们可以告诉我它是什么!
答案 0 :(得分:3)
这里是从另一个应用程序向机器人发送消息的示例。在这种情况下,我是通过Web API进行此操作的,Web API是一个代理,可拦截来自用户的消息并将其发送给机器人。这段代码中没有包括如何构造活动,但是看起来您已经将该部分排序了。请注意,在此辅助应用程序中,我使用的是Bot.Builder
,因此我可以使用活动对象和其他功能。
//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; }
}