7

我创建了一个简单的 android 应用程序,它使用 restfull jersey WS 通过 JSON 格式发送消息

我应该在连接机器人的应用程序中输入哪个 URL?

该机器人如何接收消息并发送回响应?

截至目前,我正在使用 Microsoft 的机器人模拟器

提前致谢。

4

3 回答 3

11

您可以将您的 android 客户端与 DirectLine Rest API 连接,然后在您的机器人仪表板中启用网络聊天。请参阅有关 Bot 框架的直线方法的文档。

您需要做的是使用https://directline.botframework.com/api/conversations作为您的端点并调用这些 API,如文档中所示。

示例:- 我刚刚尝试使用 ASP.MVC 应用程序。我创建了一个文本框和按钮,用于向机器人提交消息。

1.首先在您的机器人应用程序中启用直接链接。然后记住那个秘密。

2.以下代码示例向您展示了如何将您的聊天应用程序或您的公司应用程序与您使用机器人框架工作构建的机器人连接起来。

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.然后通过以下代码将您的消息传递给机器人,

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.从机器人获取消息,

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 调用,您可以轻松地将任何自定义聊天应用程序与机器人框架连接起来。以下是一种方法中的完整代码,可让您了解如何归档目标。

 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;
    }

谢谢你的机器人干杯。

于 2016-06-13T09:03:59.127 回答
7

如上一个答案所述,您将需要使用Direct Line API与您的机器人进行通信。为了能够使用 Direct Line API,您需要注册您的机器人,将 Direct Line 配置为可以访问它的通道,并生成您将在通信期间使用的 Direct Line 密钥。这一切都在连接器入门教程中介绍。

您已经注册了机器人并配置了 Direct Line 通道,通过 Direct Line API 与 Bot 进行对话有 3 个步骤。每个步骤的 URL 都会略有不同。下面是演示 3 个步骤和完成每个步骤所需的 URL 的 Android Java 代码。

第一步是与您的机器人建立对话。

    // 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 将映射到一个对话类。

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;
}

现在我们已经建立了对话,下一步是向机器人发送消息。这是 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();
    }
}
于 2016-10-13T15:45:09.957 回答
2

在这里,我使用 Direct Line API 编写了一个工作演示 - https://blogs.msdn.microsoft.com/brijrajsingh/2017/01/10/android-sample-direct-line-api-microsoft-bot-framework/

于 2017-01-20T09:18:31.600 回答