Gif not sending in facebook messenger Bot - facebook-messenger

Hi I am trying to send a gif in FB messenger. My code is as below
function sendGif(sender) {
let messageData = {
"attachment": {
"type": "image",
"payload": {
"url": "http://giphy.com/gifs/tom-cruise-risky-business-movie-3jzoNumaV4o80",
}
}
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
However, Im getting this error which is telling me that the file I am trying to attach is now allowed and to have a different format
2017-01-25T13:27:53.586498+00:00 app[web.1]: Error: { message: '(#546) The type of file you\'re trying to attach isn\'t allowed. Please try again with a different format.',
2017-01-25T13:27:53.586508+00:00 app[web.1]: type: 'OAuthException',
2017-01-25T13:27:53.586509+00:00 app[web.1]: code: 546,
2017-01-25T13:27:53.586510+00:00 app[web.1]: error_subcode: 1545026,
2017-01-25T13:27:53.586511+00:00 app[web.1]: fbtrace_id: 'BN+U/mDnnMi' }
What am i doing wrong?

You are trying to send a .html file, not a gif.
The URL for gif is:
https://media.giphy.com/media/3jzoNumaV4o80/giphy.gif

Related

Can't send image to server, getting "Error: Request failed with status code 500" while sending image file by axios in react native project

I am using react native RNCamera. I am getting the file uri from the data retuned by react native RNCamera
Here is the code how I did that
const mimeType = mime.getType(damageImage.uri);
console.log('received image', damageImage.uri, mimeType);
//Here I am getting damageImage.uri as file:///data/user/0/com.tvsmobile/cache/Camera/2c32593e-5015-4ef1-b8b0-db141628444e.jpg
// and mime type: image/jpeg
try {
const formData = new FormData();
formData.append('Content-Type', 'image/jpeg');
formData.append('damage_image', {
uri: Platform.OS === 'android' ? damageImage.uri : damageImage.uri.replace('file://', ''),
name: 'image.jpg',
type: mimeType, //I tried by passing 'image/jpeg' here
});
let response = await axios.request({
baseURL: base_url,
method: 'post',
url: headRoute + transactionRoute + damageRoute + 'add/',
headers: {
'accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
data: JSON.stringify(formData),
});
return response.data;
} catch (e) {
console.log('error at sending damage asset:' + e);
const response = e.response;
switch (response.status) {
case 601:
case 605:
case 606:
Snackbar.show({text: response.data.errMessage});
break;
default:
Snackbar.show({text: defMsg});
break;
}
}
Any help will appreciate
Thanks in advance
Error 500 means an error has happened on the server side (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500), so by inspecting front-end code is rather difficult, if not impossible, to say what is the cause. If you are able, you should check the server logs to find the cause, which might or might not be caused by your data.

React Native S3 image upload returns "Stream Closed" using XHR

After updating React Native version to latest 0.63.2 and trying to upload the image to S3 bucket XHR returns error Stream Closed image upload was working fine with version 0.61.5
The Code
uploadProfile({ variables: { filetype: mime } }).then(
({ data: { uploadUserProfile } }) => {
const { presignedUrl, url } = uploadUserProfile;
console.log('presignedUrl', { presignedUrl, url });
// uploading to s3 bucket
const xhr = new XMLHttpRequest();
xhr.open('PUT', presignedUrl);
xhr.onreadystatechange = async function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
updateAccount({
variables: {
data: {
profile: url,
},
},
});
} else {
if (/Request has expired/g.test(xhr.response))
Toast({ message: 'slow network connection' });
else {
console.log({
response: xhr.response,
responseText: xhr.responseText,
status: xhr.status,
});
Toast({ message: 'internal server error' });
await report({
error: {
response: xhr.response,
responseText: xhr.responseText,
status: xhr.status,
},
}); // reporting error
}
}
}
};
xhr.setRequestHeader('Content-Type', mime);
xhr.send({ uri: path, type: mime });
setLoading(false);
},
);
When the user wants to upload a profile image first App send a request to the server and get return the pre-signed URL and upload from client-side this how App was working.
I upgraded Flipper to version 0.51.2 and it worked for me.
Go to android/gradle.properties and add this line
FLIPPER_VERSION=0.52.1
You should have the following lines in your android/app/build.gradle
dependencies {
// ....
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
// ...
}
upgrading flipper version solves the issue for me, If upgrading flipper version doesn't solve for you then try this solution.
Whoever is still struggling with this issue. it's happening because of Flipper network plugin.
I disabled it and things work just fine.
My workaround to make this work is commenting outline number 43
38 NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39 NetworkingModule.setCustomClientBuilder(
40 new NetworkingModule.CustomClientBuilder() {
41 #Override
42 public void apply(OkHttpClient.Builder builder) {
43 // builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44 }
45 });
46 client.addPlugin(networkFlipperPlugin);
in this file android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java
found this answer link

Sending JSON via Postman causes an error in my Node.js service

I created schema in node.js. It worked before I included arrays.
This is my schema code:
const Item = new item_Schema({
info:{
title:{type:String, required:true},
bad_point:{type:Number, 'default':0},
Tag:{type:String, required:true}
},
review:{
Review_text:{type:Array, required:true},
Phone_list:{type:Array, required:true},
LatLng_list:{type:Array, required:true}
}
});
Item.statics.create = function(info, review){
const list = new this({
info:{
title,
bad_point,
Tag
},
review:{
Review_text,
Phone_list,
LatLng_list
}
});
return list.save();
};
This is my register code:
exports.register = (req, res) => {
const { info, review } = req.body
const create = (list) => {
return Item.create(info, review)
}
const respond = () => {
res.json({
message: 'place route registered successfully'
})
}
const onError = (error) => {
res.status(409).json({
message: error.message
})
}
RouteReviewItem.findOneBytitle(title)
.then(create)
.then(respond)
.catch(onError)
}
And this is the Postman JSON raw code:
{
"info":"{
"title":"test title",
"badPoint":"0"
"Tag":"tag1"
}",
"review":"{
"Review_text":["1번리뷰", "2번리뷰", "3번리뷰"],
"Phone_list":"["010-0000-0000", "010-1111-1111", "010-2222-2222"],
"LatLng_list":["111.1111,111.1111", "222.222,222.222","333.3333,333.3333"]
}"
}
This is the error I get in Postman:
SyntaxError: Unexpected token in JSON at position 17
at JSON.parse (<anonymous>)
at parse (C:\MainServer\node_modules\body-parser\lib\types\json.js:89:19)
at C:\MainServer\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\MainServer\node_modules\raw-body\index.js:224:16)
at done (C:\MainServer\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\MainServer\node_modules\raw-body\index.js:273:7)
at emitNone (events.js:105:13)
at IncomingMessage.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1045:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
Is this a problem with postman? Or the node.js side?
I looked at the node.js book I was studying, but could not find any relevant information.
The code is fine, you have an issue with JSON you used for testing. For further testing and debugging, I suggest that you verify that the requests you send you the endpoint are correct by using a service like JSONLint (or any offlne tool that does the same). For the request you posted in the question, this service complains:
Error: Parse error on line 2:
{ "info": "{ "title": "test t
----------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
Next time, before sending a request, make sure it is correct syntactically. That way you'll know that there is a problem with your code, and won't spend time debugging a non-existent issue.

Uploading files to meteor server using Method call

I am trying to implement file uploads for meteor using Method call.
I am using this meteor package: https://atmospherejs.com/ostrio/files.
I have no problem on client side (I can send file in a base64 encoded format). on server side I am trying to implement this function : https://github.com/VeliovGroup/Meteor-Files/blob/master/docs/write.md
but I am getting this error.
Error during upload: TypeError: Images.write is not a function
Here is the code of my Method on server:
export const insertImage = new ValidatedMethod({
name: 'images.insert',
validate: new SimpleSchema({
file: { type: String },
}).validator(),
run({ file }) {
Images.write(file, {
fileName: 'sample.png',
type: 'image/png',
}, function (error, fileRef) {
if (error) {
throw error;
} else {
console.log(`${fileRef.name} is successfully saved to FS. _id: ${fileRef._id}`);
}
});
},
});
According to the lib documentation you will need to first instantiate Images with an instance of FilesCollection, similar to as following:
https://github.com/VeliovGroup/Meteor-Files#api-overview-full-api
import { FilesCollection } from 'meteor/ostrio:files';
const Images = new FilesCollection({
collectionName: 'Images',
allowClientCode: false, // Disallow remove files from Client
onBeforeUpload(file) {
// Allow upload files under 10MB, and only in png/jpg/jpeg formats
if (file.size <= 10485760 && /png|jpg|jpeg/i.test(file.extension)) {
return true;
} else {
return 'Please upload image, with size equal or less than 10MB';
}
}
});
For more details on the constructor parameters please refer to https://github.com/VeliovGroup/Meteor-Files/wiki/Constructor
I have used this syntax:
Meteor.call('images.insert', {
file: image
}, (err, res) => {
if (err) {
console.log(`Error during upload: ${err}`);
} else {
console.log(`Upload successfully!`);
}
});

Sending images or buttons on facebook messenger via ibm watson configuered via botkit

I have made a wotson chat bot, deployed on facebbok messenger the broker is a node app just like in this github example. I'm recieving text responses perfectly but how do I configure the bot to send images or buttons to the fb messenger. I have tried Respond with JSON option in watson dialog.
JSON:
{
"output": {
},
"context":{
"facebook":{
"message":{
"attachment":{
"type":"image",
"payload":{
"url":"https://petersapparel.com/img/shirt.png"
}
}
}
}
}
}
I Think there is some problem with my JSON.
To send buttons define message with template_type generic and buttons with type postback
controller.hears('test', 'message_received', function(bot, message) {
var attachment = {
'type':'template',
'payload':{
'template_type':'generic',
'elements':[
{
'title':'Chocolate Cookie',
'image_url':'http://cookies.com/cookie.png',
'subtitle':'A delicious chocolate cookie',
'buttons':[
{
'type':'postback',
'title':'Eat Cookie',
'payload':'chocolate'
}
]
},
]
}
};
bot.reply(message, {
attachment: attachment,
});
});
To send attachment define attachment message with resource url and call upload method.
controller.hears('test', 'message_received', function(bot, message) {
var attachment = {
"type":"image",
"payload":{
"url":"https://pbs.twimg.com/profile_images/803642201653858305/IAW1DBPw_400x400.png",
"is_reusable": true
}
};
controller.api.attachment_upload.upload(attachment, function (err, attachmentId) {
if(err) {
// Error
} else {
var image = {
"attachment":{
"type":"image",
"payload": {
"attachment_id": attachmentId
}
}
};
bot.reply(message, image);
}
});
}
Check Botkit Messenger documentation.

Resources