我创建了一个简单的Android应用程序,它使用restfull jersey WS
通过JSON格式发送消息我应该在连接机器人的应用程序中输入哪个URL?
该机器人如何接收消息并发回响应?
截至目前,我正在使用Microsoft的bot模拟器
提前致谢。
答案 0 :(得分:11)
您可以在机器人仪表板中进行简单的网络聊天之前,将您的Android客户端与DirectLine Rest API连接起来。 请参阅有关Bot框架的直线方法的文档。
您需要做的是使用https://directline.botframework.com/api/conversations作为您的终端并调用这些API,如文档中所示。
示例: - 我刚尝试使用ASP.MVC应用程序。我创建了一个文本框和按钮,用于向bot提交消息。
1.首先在您的bot应用程序中启用直接链接。然后记住那个秘密。
2.以下代码示例向您展示如何将聊天应用程序或公司应用程序与使用bot框架工作构建的bot连接。
3.首先,您需要授权您访问直接链接API。
client = new HttpClient();
client.BaseAddress = new Uri("https://directline.botframework.com/api/conversations/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BotConnector", "[Your Secret Key Here]");
response = await client.GetAsync("/api/tokens/");
if (response.IsSuccessStatusCode)
4.如果您之前的回复成功,您可以开始新的对话模型 -
public class Conversation {
public string conversationId { get; set; }
public string token { get; set; }
public string eTag { get; set; }
}
控制器内的代码 -
var conversation = new Conversation();
response = await client.PostAsJsonAsync("/api/conversations/",conversation);
if (response.IsSuccessStatusCode)
如果您使用此响应成功,您将获得conversationId和令牌以开始发送消息。
5.然后通过以下代码将消息传递给bot,
Conversation ConversationInfo = response.Content.ReadAsAsync(typeof(Conversation)).Result as Conversation; string conversationUrl = ConversationInfo.conversationId+"/messages/"; Message msg = new Message() { text = message }; response = await client.PostAsJsonAsync(conversationUrl,msg); if (response.IsSuccessStatusCode)
如果您获得成功回复,则表示您已将消息发送至机器人。现在您需要从BOT
获取回复消息6.从bot获取消息,
response = await client.GetAsync(conversationUrl); if (response.IsSuccessStatusCode){ MessageSet BotMessage = response.Content.ReadAsAsync(typeof(MessageSet)).Result as MessageSet; ViewBag.Messages = BotMessage; IsReplyReceived = true; }
这里有一个消息集,这意味着你发送的消息和Bot的回复。您现在可以在聊天窗口中显示它。
消息模型 -
public class MessageSet
{
public Message[] messages { get; set; }
public string watermark { get; set; }
public string eTag { get; set; }
}
public class Message
{
public string id { get; set; }
public string conversationId { get; set; }
public DateTime created { get; set; }
public string from { get; set; }
public string text { get; set; }
public string channelData { get; set; }
public string[] images { get; set; }
public Attachment[] attachments { get; set; }
public string eTag { get; set; }
}
public class Attachment
{
public string url { get; set; }
public string contentType { get; set; }
}
使用这些API调用,您可以轻松地将任何自定义聊天应用程序与bot框架连接起来。以下是一种方法中的完整代码,可让您了解如何归档目标。
private async Task<bool> PostMessage(string message)
{
bool IsReplyReceived = false;
client = new HttpClient();
client.BaseAddress = new Uri("https://directline.botframework.com/api/conversations/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BotConnector", "[Your Secret Code Here]");
response = await client.GetAsync("/api/tokens/");
if (response.IsSuccessStatusCode)
{
var conversation = new Conversation();
response = await client.PostAsJsonAsync("/api/conversations/", conversation);
if (response.IsSuccessStatusCode)
{
Conversation ConversationInfo = response.Content.ReadAsAsync(typeof(Conversation)).Result as Conversation;
string conversationUrl = ConversationInfo.conversationId+"/messages/";
Message msg = new Message() { text = message };
response = await client.PostAsJsonAsync(conversationUrl,msg);
if (response.IsSuccessStatusCode)
{
response = await client.GetAsync(conversationUrl);
if (response.IsSuccessStatusCode)
{
MessageSet BotMessage = response.Content.ReadAsAsync(typeof(MessageSet)).Result as MessageSet;
ViewBag.Messages = BotMessage;
IsReplyReceived = true;
}
}
}
}
return IsReplyReceived;
}
感谢干杯与你的机器人。
答案 1 :(得分:7)
如前一个答案中所述,您需要使用Direct Line API与机器人进行通信。为了能够使用Direct Line API,您需要注册机器人,将Direct Line配置为可以访问它的通道,并生成您将在通信期间使用的Direct Line密钥。这已在Getting Started with the Connector教程中介绍。
您已经注册了机器人并配置了直线通道,通过Direct Line API与Bot进行对话有3个步骤。对于每个步骤,URL略有不同。下面是Android Java代码,演示了完成每个步骤所需的3个步骤和URL。
第一步是与机器人建立对话。
// Step 1: Establish a conversation with your bot
String secretCode = "[YOUR SECRET CODE HERE]";
Conversation conversation = null;
URL directLineUrl = new URL("https://directline.botframework.com/api/conversations/");
HttpsURLConnection directLineConnection = (HttpsURLConnection) directLineUrl.openConnection();
directLineConnection.setRequestMethod("POST"); // for some reason this has to be a post, even though we're really doing a get.
directLineConnection.addRequestProperty("Authorization", "BotConnector " + secretCode);
directLineConnection.setRequestProperty("Content-Type", "application/json");
directLineConnection.setDoOutput(true);
directLineConnection.setDoInput(true);
if (directLineConnection.getResponseCode() == 200) {
// Read the Conversation JSON
InputStream in = new BufferedInputStream(directLineConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
conversation = new Conversation(result.toString());
}
directLineConnection.disconnect();
生成的JSON将映射到Conversation类。
public class Conversation {
public Conversation() {}
public Conversation(String jsonString) throws JSONException {
this(new JSONObject(jsonString));
}
public Conversation(JSONObject json) throws JSONException {
if (json.isNull("conversationId") == false) {
conversationId = json.getString("conversationId");
}
if (json.isNull("eTag") == false) {
eTag = json.getString("eTag");
}
if (json.isNull("token") == false) {
token = json.getString("token");
}
}
public String conversationId = null;
public String eTag = null;
public String token = null;
}
现在我们已经建立了一个对话,下一步就是向bot发送一条消息。这是Message类(注意:并非所有属性都已完全实现以转换为/来自JSON)
public class Message {
public Message() {}
public Message(String jsonString) throws JSONException {
this(new JSONObject(jsonString));
}
public Message(JSONObject json) throws JSONException {
if(json.isNull("id") == false) {
this.id = json.getString("id");
}
if(json.isNull("conversationId") == false) {
this.conversationId = json.getString("conversationId");
}
if(json.isNull("created") == false) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
this.created = dateFormat.parse(json.getString("created"));
} catch (ParseException e) {
e.printStackTrace();
}
}
if(json.isNull("from") == false) {
this.from = json.getString("from");
}
if(json.isNull("text") == false) {
this.text = json.getString("text");
}
if(json.isNull("eTag") == false) {
this.eTag = json.getString("eTag");
}
// TODO: Implement channelData, images, and attachments
}
public String id = null;
public String conversationId = null;
public Date created = null;
public String from = null;
public String text = null;
public Object channelData = null;
public List<String> images = null;
public List<Attachment> attachments = null;
public String eTag = null;
public String toJSON() {
String jsonString = "";
try {
JSONObject json = new JSONObject();
json.put("id", this.id);
json.put("conversationId", this.conversationId);
if(this.created != null) {
json.put("created", this.created.toString());
}
json.put("from", this.from);
json.put("text", this.text);
json.put("eTag", this.eTag);
// channelData, images, and attachments are never encoded to JSON by this object.
jsonString = json.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return jsonString;
}
}
我们使用Conversation.conversationId创建POST消息的路径。
// Step 2: Post Message to bot
String botUrl = "https://directline.botframework.com/api/conversations/" + conversation.conversationId + "/messages/";
Message message = new Message();
message.text = "[SOME TEXT TO SEND TO YOUR BOT]";
boolean messageSent = false;
URL messageUrl = new URL(botUrl);
HttpsURLConnection messageConnection = (HttpsURLConnection) messageUrl.openConnection();
messageConnection.setRequestMethod("POST");
messageConnection.addRequestProperty("Authorization", "BotConnector " + secretCode);
messageConnection.setRequestProperty("Content-Type", "application/json");
messageConnection.setDoOutput(true);
messageConnection.setDoInput(true);
// Send message to bot through direct line connection
DataOutputStream outputStream = new DataOutputStream(messageConnection.getOutputStream());
outputStream.writeBytes(message.toJSON());
outputStream.flush();
outputStream.close();
if (messageConnection.getResponseCode() == 204) {
messageSent = true;
}
messageConnection.disconnect();
最后一步,我们将机器人的任何响应读入MessageSet类。
public class MessageSet {
public MessageSet() {}
public MessageSet(String jsonString) throws JSONException {
this(new JSONObject(jsonString));
}
public MessageSet(JSONObject json) throws JSONException {
if (json.isNull("watermark") == false) {
this.watermark = json.getString("watermark");
}
if (json.isNull("eTag") == false) {
this.eTag = json.getString("eTag");
}
if (json.isNull("messages") == false) {
JSONArray array = json.getJSONArray("messages");
if (array.length() > 0) {
this.messages = new ArrayList<Message>();
for (int i = 0; i < array.length(); ++i) {
this.messages.add(new Message(array.getJSONObject(i)));
}
}
}
}
public List<Message> messages;
public String watermark;
public String eTag;
}
我们在查询字符串上使用前一个(如果有的话)消息交换的MessageSet.watermark,因此我们只得到对我们发送的当前消息的响应。
// Step 3: Read the bot response into MessageSet
MessageSet messageSet = null;
String messageSetPath = botUrl;
if (lastWatermark.isEmpty() == false) {
messageSetPath += "?watermark=" + lastWatermark;
}
URL messageSetUrl = new URL(messageSetPath);
HttpsURLConnection messageSetConnection = (HttpsURLConnection) messageSetUrl.openConnection();
messageSetConnection.addRequestProperty("Authorization", "BotConnector " + secretCode);
messageSetConnection.setRequestProperty("Content-Type", "application/json");
messageSetConnection.setDoOutput(true);
messageSetConnection.setDoInput(true);
if (messageSetConnection.getResponseCode() == 200) {
InputStream in = new BufferedInputStream(messageSetConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
messageSet = new MessageSet(result.toString());
lastWatermark = messageSet.watermark;
}
messageSetConnection.disconnect();
以下是一种方法中的完整代码,以了解它们如何结合在一起。
private String lastWatermark = "";
public void DirectLineExample() throws IOException, JSONException {
// Step 1: Establish a conversation with your bot
String secretCode = "[YOUR SECRET CODE HERE]";
Conversation conversation = null;
URL directLineUrl = new URL("https://directline.botframework.com/api/conversations/");
HttpsURLConnection directLineConnection = (HttpsURLConnection) directLineUrl.openConnection();
directLineConnection.setRequestMethod("POST"); // for some reason this has to be a post, even though we're really doing a get.
directLineConnection.addRequestProperty("Authorization", "BotConnector " + secretCode);
directLineConnection.setRequestProperty("Content-Type", "application/json");
directLineConnection.setDoOutput(true);
directLineConnection.setDoInput(true);
if (directLineConnection.getResponseCode() == 200) {
// Read the Conversation JSON
InputStream in = new BufferedInputStream(directLineConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
conversation = new Conversation(result.toString());
}
directLineConnection.disconnect();
// Step 2: Post Message to bot
String botUrl = "https://directline.botframework.com/api/conversations/" + conversation.conversationId + "/messages/";
Message message = new Message();
message.text = "[SOME TEXT TO SEND TO YOUR BOT]";
boolean messageSent = false;
URL messageUrl = new URL(botUrl);
HttpsURLConnection messageConnection = (HttpsURLConnection) messageUrl.openConnection();
messageConnection.setRequestMethod("POST");
messageConnection.addRequestProperty("Authorization", "BotConnector " + secretCode);
messageConnection.setRequestProperty("Content-Type", "application/json");
messageConnection.setDoOutput(true);
messageConnection.setDoInput(true);
// Send message to bot through direct line connection
DataOutputStream outputStream = new DataOutputStream(messageConnection.getOutputStream());
outputStream.writeBytes(message.toJSON());
outputStream.flush();
outputStream.close();
if (messageConnection.getResponseCode() == 204) {
messageSent = true;
}
messageConnection.disconnect();
if (messageSent) {
// Step 3: Read the bot response into MessageSet
MessageSet messageSet = null;
String messageSetPath = botUrl;
if (lastWatermark.isEmpty() == false) {
messageSetPath += "?watermark=" + lastWatermark;
}
URL messageSetUrl = new URL(messageSetPath);
HttpsURLConnection messageSetConnection = (HttpsURLConnection) messageSetUrl.openConnection();
messageSetConnection.addRequestProperty("Authorization", "BotConnector " + secretCode);
messageSetConnection.setRequestProperty("Content-Type", "application/json");
messageSetConnection.setDoOutput(true);
messageSetConnection.setDoInput(true);
if (messageSetConnection.getResponseCode() == 200) {
InputStream in = new BufferedInputStream(messageSetConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
messageSet = new MessageSet(result.toString());
lastWatermark = messageSet.watermark;
}
messageSetConnection.disconnect();
}
}
答案 2 :(得分:2)
在这里,我使用Direct Line API编写了相同的工作演示 - https://blogs.msdn.microsoft.com/brijrajsingh/2017/01/10/android-sample-direct-line-api-microsoft-bot-framework/