Мы развернули простой Echobot с использованием шаблона Azure при создании бота веб-приложения.
В настоящее время он находится по этому адресу: http://18.194.88.194/echobot/
Мы часто сталкиваемся со следующей ошибкой тайм-аута (около 40% времени)
Соединение WebSocket с 'wss: //directline.botframework.com/v3/directline/conversations/EH9EbbBIasz8o90sZSeAwT-9/stream ? watermark = - & t = ew0KICAiYWxnIj ... (snip) не удалось: ошибка при установлении соединения: net :: ERR_CONNECTION_TIMED_OUT
Вот наш код клиента: botclient.js
(async function() {
let {token, conversationId} = sessionStorage;
const delay = 1800000;
//const delay = 20000;
const currentTime = new Date();
const currentTimeUnix = currentTime.getTime();
if (
sessionStorage['startTime'] &&
currentTimeUnix - sessionStorage['startTime'] > delay
) {
sessionStorage.removeItem('token');
token = sessionStorage['token'];
}
const payload = JSON.stringify({botname: 'echobot'});
if (!token) {
const res = await fetch(
'https://ox38xh0fx5.execute-api.eu-central-1.amazonaws.com/dev/directline/token',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: payload,
},
);
const {token: directLineToken} = await res.json();
sessionStorage['token'] = directLineToken;
token = directLineToken;
console.log('token', token);
const startTime = new Date();
const startTimeUnix = startTime.getTime();
sessionStorage['startTime'] = startTimeUnix;
}
const data = {
// from: user,
name: 'requestWelcomeDialog',
type: 'event',
value: {
url: window.location.href,
},
};
var botConnection = new window.WebChat.createDirectLine({token});
window.WebChat.renderWebChat(
{
directLine: botConnection,
userID: 'YOUR_USER_ID',
username: 'Web Chat User',
locale: 'en-US',
},
document.getElementById('webchat'),
);
})().catch(err => console.log(err));
index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
}
#webchat {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script src="botclient.js">
</script>
</body>
</html>
Токен извлекается из лямбда-функции AWS со следующим кодом:
import json
import boto3
from urllib.parse import urlencode
from urllib.request import Request, urlopen
BOT_SECRET = 'defaultSecret'
URL = 'https://directline.botframework.com/v3/directline/tokens/generate'
POST_FIELDS = {'foo': 'bar'}
def set_headers(req, secret):
req.add_header('Content-Type', 'application/json')
req.add_header('Authorization', f'Bearer {secret}')
return req
def lambda_handler(event, context):
print(event)
s3 = boto3.client('s3')
if event.get('botname', None) == 'echobot':
response = s3.get_object(Bucket='directline', Key='echobotSecret')
else:
response = s3.get_object(Bucket='directline', Key=BOT_SECRET)
secret = response['Body'].read().decode('utf-8').rstrip()
request = Request(URL, urlencode(POST_FIELDS).encode())
request = set_headers(request, secret)
jsonresponse = urlopen(request).read()
print(jsonresponse)
return jsonresponse
Мы подозреваем, что существует проблема с конфигурация локальной сети, и пакеты отбрасываются. Есть ли какие-нибудь указания, как с этим справиться?