v4 Bot sendActivity no output in Bot [object Promise] - botframework

I do not get an output inside my web chat Bot with the line
await turnContext.sendActivity('No output in Bot? '+this.translateText(turnContext.activity.text));
There is no error message and in the log I get the correct JSON from the Microsoft Cognitive Text Translator API service. But in the Bot Framework emulator I get only [object Promise]?
const request = require('request');
const uuidv4 = require('uuid/v4');
const rp = require('request-promise');
class EchoBot {
constructor(conversationState) {
this.conversationState = conversationState;
}
async onTurn(turnContext) {
if (turnContext.activity.type === ActivityTypes.Message) {
// OK
await turnContext.sendActivity(`${ count }: Alex you said "${ turnContext.activity.text }"`);
// not output in Bot?
await turnContext.sendActivity('No output in Bot? '+this.translateText(turnContext.activity.text));
} else {
await turnContext.sendActivity(`[${ turnContext.activity.type } event detected]`);
}
await this.conversationState.saveChanges(turnContext);
}
async translateText(inputText){
let options = {
method: 'POST',
baseUrl: 'https://api.cognitive.microsofttranslator.com/',
url: 'translate',
qs: {
'api-version': '3.0',
'to': 'de'
},
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
body: [{
'text': inputText
}],
json: true,
};
rp(options)
.then(function (repos) {
console.log(JSON.stringify(repos, null, 4));
return JSON.stringify(repos, null, 4);
})
.catch(function (err) {
console.log("error alex");
});
};
}

Since you are using the response-promise package, I would recommend using async/await instead of the then/catch method. The async/await approach falls more inline with the flow of the BotFramework and will allow you to return the resulting promise from your request to your onTurn method. This is how your translateText function should look:
async translateText(inputText){
let options = {
method: 'POST',
baseUrl: 'https://api.cognitive.microsofttranslator.com/',
url: 'translate',
qs: {
'api-version': '3.0',
'to': 'de'
},
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
body: [{
'text': inputText
}],
json: true,
};
const repos = await rp(options);
return repos[0].translations[0].text;
};
Note, since translateText is an asynchronous method and returns a promise you will have to add await before the function call.
await turnContext.sendActivity('No output in Bot? ' + await this.translateText(turnContext.activity.text));
Hope this helps!

Related

Flutter app gave an error after performing the necessary integration with laravel api, it returned null

I have a signup page having done all the necessary integration my flutter app still not posting
Here I have my signup method
_signup() async {
var data = {
'first': firstNameController.text,
'last': lastNameController.text,
'email': emailController.text,
'phone': phoneController.text,
'age': ageController.dropDownValue!.name,
'gender': genderController.dropDownValue!.name,
'password': passwordController.text,
'confirm': confirmPasswordController.text
};
print(data);
var res = await CallApi().postData(data, 'register');
print(res);
var body = json.decode(res.body);
print(body);
}
Why I have the api authentication here which is well configured
import 'package:http/http.dart' as http;
class CallApi {
final String baseURL = 'https://beereapp.edusmart.ng/api/auth/';
postData(data, apiUrl) async {
var fullUrl = baseURL + apiUrl;
return await http.post(
Uri.parse(fullUrl),
body: jsonEncode(data),
headers: _setHeaders());
}
getData(apiUrl) async {
var fullUrl = Uri.parse(baseURL + apiUrl);
return await http.get(fullUrl, headers: _setHeaders());
}
_setHeaders() => {
'Content-type': 'application/json',
'Accept': 'application/json',
};
}
As you can see my terminal below I printed my data out which is showing but next is error.
Help please!
[![My terminal][1]][1]
[1]: https://i.stack.imgur.com/10uMa.jpg

I am having trouble integrating my twilio video api through react hooks, specifically for the videochat.js

webpage; videochat.js; room.js
const handleSubmit = useCallback(async event => {
event.preventDefault();
alert('Work');
const data = await fetch('./video/token', {
method: 'POST',
body: JSON.stringify({
identity: username,
// room: roomName
}),
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json());
setToken(data.token);
}, [username, roomName]);
This is the part where I am likely having an issue (lines 18-32 of videochat.js)

gapi.client.drive.files.create does not work

I'm writing a vue app. I read this sample code and wrote code like this:
const apiKey = 'mykey';
const discoveryDocs = ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"]
const clientId = 'myclientid'
const scopes = 'https://www.googleapis.com/auth/drive.appdata'
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
function initClient() {
gapi.client.init({
apiKey,
discoveryDocs,
clientId,
scope: scopes
}).then(function () {
createFile()
});
}
function createFile() {
console.log('createFile')
var fileMetadata = {
'name': 'config.json',
'parents': ['appDataFolder']
};
var media = {
mimeType: 'application/json',
body: "body"
};
gapi.client.drive.files.create({
resource: fileMetadata,
media,
fields: 'id'
}, function (err, file) {
console.log('function in createFile')
if (err) {
console.error(err);
} else {
console.log('Folder Id:', file.id);
}
});
}
window.onload=handleClientLoad()
In the console, 'createFile' is logged but 'function in createFile' is not logged, so I think function(err, file)... does not work.
What is wrong?
I want the sample code to work.
I had the same issue. The function create() returns a promise, to execute the request, it seems to need a then(). See also this post.
The example code though does not work since you will get a 403 The user does not have sufficient permissions for this file error. This seems to happen since example code will create the file not in appDataFolder but in the root directory.
I managed to get it to work using the following code. Putting all request parameters flat into the object passed to create() seems to do the trick.
const s = new Readable();
s.push("beep"); // the string you want
s.push(null);
gapi.client.drive.files
.create({
name: "config.json",
parents: ["appDataFolder"],
mimeType: "application/json",
upload_type: "media",
fields: "id",
body: s,
})
.then(function (response) {
if (response.status === 200) {
var file = response.result;
console.log(file);
}
})
.catch(function (error) {
console.error(error);
});

DynamoDB update data works but return Internal Server Error

I am using API server with AWS Lambda and DynamoDB
I've created an API for Update data.
export const updateD = async(event, context, callback)=>{
const {email, uid} = JSON.parse(event.body);
let unique = await getUnique();
const updateParams = {
TableName: "MY_TABLE",
Key: {
email: email,
uid: uid
},
UpdateExpression: "set code = :code, expiredAt = :now", //expiredAt is TTL
ExpressionAttributeValues: {
":isVerified": unique,
":now": moment().add(10, "minutes").unix()
},
ReturnValues: "ALL_NEW"
}
DYNAMO_DB.update(updateParams, (err, data) => {
if(err) {
const r = {
statusCode: 500,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify(err)
}
callback(null, r);
}
const r = {
statusCode: 200,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify({msg: "success"})
}
callback(null, r);
});
}
When I called this API, the data is updated successfully by it, but I can receive only
{
"message": "Internal server error"
}
What I missed in my code??
Your handler is defined as an async function due to which lambda is expected to return a response.
However the function body follows non-async pattern passing the response to the callback instead of returning it.
If you want to use async/await you should update your function by using the promisified version of update operation instead of callback, it may like look like as follows:
export const updateD = async (event) => {
const {email, uid} = JSON.parse(event.body);
let unique = await getUnique();
const updateParams = {
TableName: "MY_TABLE",
Key: {
email: email,
uid: uid
},
UpdateExpression: "set code = :code, expiredAt = :now", //expiredAt is TTL
ExpressionAttributeValues: {
":isVerified": unique,
":now": moment().add(10, "minutes").unix()
},
ReturnValues: "ALL_NEW"
};
try {
const data = await DYNAMO_DB.updateItem(updateParams).promise();
return {
statusCode: 200,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify({msg: "success"})
}
} catch (err) {
return {
statusCode: 500,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify(err)
}
}
};

Error during upload image to imgur - inavlid URL

i have some troubles with imgur api. I converted image to base64 code and tried upload it to imgur api. Unfortuatelly I'm receiving an error:
"error": "Invalid URL (data:image/png;base64,iVBORw0KGgoAA..."
Here's my function:
uploadImageToImgur: function (file) {
const url = 'https://api.imgur.com/3/image',
reader = new FileReader();
reader.onloadend = async function () {
let { result } = reader;
try {
const request = await fetch(url, {
method: 'POST',
headers: {
"Authorization": 'my client key',
},
body: result
});
const response = await request.json();
console.log(response);
} catch (e) {
throw new Error(e);
}
}
if (file) {
reader.readAsDataURL(file);
}
}
You need to cut this part out.
You are missing some parameters. Also, make sure your headers have the Client-ID key.
const request = await fetch(url, {
method: 'POST',
headers: {
"Authorization": 'Client-ID {yourKey}',
},
form: {
"image": result,
"type": "base64"
}
});

Resources