Как подключиться к фреймворку ботов Microsoft с android cilent
Я создал простое приложение для Android, которое отправляет сообщение в формате JSON с использованием restfull jersey WS
какой URL я должен ввести в моем приложении, которое соединяет бота?
и как этот бот получает сообщение и отправляет ответ?
На данный момент я использую эмулятор бота от Microsoft
Заранее спасибо.
3 ответа
Вы можете подключить свой 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)
Если вам удастся получить этот ответ, вы получите Идентификатор разговора и токен для начала обмена сообщениями.
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; }
Здесь вы получаете набор сообщений, что означает отправленное вами сообщение и ответ от бота. Теперь вы можете отобразить его в окне чата.
Модель сообщения -
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;
}
Спасибо Cheers с вашим ботом.
Как упоминалось в предыдущем ответе, вам нужно будет использовать Direct Line API для связи с вашим ботом. Чтобы иметь возможность использовать API Direct Line, вам необходимо зарегистрировать своего бота, настроить Direct Line в качестве канала, который может получить к нему доступ, и сгенерировать секретный ключ Direct Line, который вы будете использовать во время связи. Все это описано в учебном пособии " Начало работы с соединителем".
После того, как вы зарегистрировали бота и настроили канал Direct Line, есть 3 шага для разговора с ботом через API Direct Line. Для каждого шага 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 преобразуется в класс беседы.
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, чтобы создать путь для отправки сообщения.
// 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();
}
}
Здесь я написал рабочую демонстрацию для того же самого, используя Direct Line API - https://blogs.msdn.microsoft.com/brijrajsingh/2017/01/10/android-sample-direct-line-api-microsoft-bot-framework/