Discord.js v13 Sending a File Attachment via URL - file

Discord.js released v13 and I'm trying to update my little homebrew discordbot.
I've come across an issue where I can no longer send an attached file (png) via a web URL.
Discord.js v12
var testchart = `http://jegin.net/testchart2.php?sysid=268.png`;
message.channel.send("Last updated " + updatedAt.fromNow(), {
files: [{
attachment: testchart,
name: 'file.png'
}]
No errors to the console are made (other than a depreciation warning):
And the bot does not return an image:
I've tried:
message.channel.send("Last updated " + updatedAt.fromNow(), {
files: [testchart]
and
message.channel.send("Last updated " + updatedAt.fromNow(), {
files: Array.from(testchart)
});
And finally
message.channel.send({
files: [testchart],
content: `Last updated ${updatedAt.fromNow()}`
});
Which gives me this AWFUL output:
Thanks for the help!
Discord.js's guide for updates: https://discordjs.guide/additional-info/changes-in-v13.html#sending-messages-embeds-files-etc
Only other issue I was able to find on the matter: Discord.js V13 sending message attachments

Found the issue, it has to do with the testchart2.php part of the URL (http://jegin.net/testchart2.php?sysid=268.png)
Was able to get it sent by using:
message.channel.send({
files: [{
attachment: testchart,
name: 'chart.png'
}],
content:`Last updated ${updatedAt.fromNow()}`,
});
Basically, just take the content part of the v12 and move it to it's own area. Worked like a charm.

Your first attempt was close, but not exactly correct. You just have to merge those together (sending messages only takes 1 argument now) and you will get a png file (because you specified the file name), along with the content:
var testchart = `http://jegin.net/testchart2.php?sysid=268.png`;
message.channel.send({
content: "Last updated " + updatedAt.fromNow(),
files: [{
attachment: testchart,
name: 'file.png'
}]
})

Related

BOX API by Google Apps Script - new file version upload

I've already asked the GAS community but I was advised to continue asking here...
So far I'm able to connect to BOX and get a list of files and I can download a file from BOX as well.
The whole idea is to download a file using BOX API, edit it and upload it back as a new file version using the BOX API.
I'm unable to make the last part working as it gives me error code 400.
Here is the function.
function uploadNewFileVersion() {
//767694355309 testing
var boxFileId="767694355309";
var newVerFile = DriveApp.getFileById("1sK-jcaJoD0WaAcixKtlHA85pf6t8M61v").getBlob();
var confirmAuthorization = getBoxService_().getAccessToken();
//var parent = { "id": "0" };
//"name": "apiNewVersion.xlsx",
//"parent": parent,
var payload = {
"file": newVerFile
}
var headers = {
'Authorization': 'Bearer ' + confirmAuthorization
}
var options = {
"method": "post",
"muteHttpExceptions": true,
"contentType": "multipart/form-data",
"headers": headers,
"payload": payload
}
var apiHtml = "https://upload.box.com/api/2.0/files/"+boxFileId+"/content/";
var response = UrlFetchApp.fetch(apiHtml, options);
Logger.log(response.getResponseCode());
var a = 1;
}
The boxFileId is the file on the box.
The newVerFile is the one downloaded from Box and updated. I need to make it as a new version of the Box file.
Could you please advise?
Thank you!
PEtr
I think parent and name is optional so I commented it out.
If I don't getBlob, then it returns 415 istead.
I believe your goal and situation as follows.
You want to upload a file of Google Drive using Box API with Google Apps Script.
From your question, I cannot find the official document of the method of API that you want to use. But, from the endpoint https://upload.box.com/api/2.0/files/"+boxFileId+"/content/ in your script, I guessed that you wanted to use "Upload file version".
Values of your access token and file ID are valid for using the API.
If my understanding of your question is correct, how about the following modification?
Modification points:
When I saw the official document of "Upload file version", I confirmed the following sample curl. In this case, it is considered that when the following curl command is converted to Google Apps Script, the request might work.
$ curl -i -X POST "https://upload.box.com/api/2.0/files/12345/content" \
-H "Authorization: Bearer <ACCESS_TOKEN>" \
-H "Content-Type: multipart/form-data" \
-F attributes="{"name":"Contract.pdf", "parent":{"id":"11446498"}}" \
-F file=#<FILE_NAME>
From the curl command, it is found that attributes and file are sent as form and files.
And, I thought that attributes="{"name":"Contract.pdf", "parent":{"id":"11446498"}}" might should be attributes="{\"name\":\"Contract.pdf\", \"parent\":{\"id\":\"11446498\"}}".
When I saw your current script, it seems that multipart/form-data is used for contentType. In this case, boundary in the request body is required to be included. Fortunately, at UrlFetchApp, in the case of multipart/form-data, when contentType is not used, the content type is automatically included in the request header. I think that in your case, this can be used.
In your script, attributes="{"name":"Contract.pdf", "parent":{"id":"11446498"}}" is not included. But I thought that you might use it in the future script. So in this answer, this is also included.
When above points are reflected and the sample curl command on the official document is converted to Google Apps Script, the script becomes as follows.
Sample script:
Please copy and paste the following script to the script editor and set the variables, and run the function of myFunction. By this, the request same with the sample curl is requested with Google Apps Script.
function myFunction() {
const accessToken = "###"; // Please set your access token.
const fileId = "###"; // Please set your fileId.
const fileBlob = DriveApp.getFileById("1sK-jcaJoD0WaAcixKtlHA85pf6t8M61v").getBlob();
const metadata = {name: "Contract.pdf", parent: {id: "11446498"}}; // Please set your file metadata.
const params = {
method: "post",
headers: {Authorization: `Bearer ${accessToken}`},
payload: {
attributes: JSON.stringify(metadata),
file: fileBlob,
},
muteHttpExceptions: true,
};
const url = `https://upload.box.com/api/2.0/files/${fileId}/content`;
const res = UrlFetchApp.fetch(url, params);
console.log(res.getContentText());
}
I could confirm that above sample script is the same request with above sample curl.
If you don't want to use the file metadata, please remove the line of attributes: JSON.stringify(metadata), from payload.
Note:
In this case, the maximum data size ("URL Fetch POST size") of UrlFetchApp is 50 MB. Please be careful this. Ref
About the limitation of file upload of Box API, please check https://developer.box.com/guides/uploads/.
If your access token and file ID are invalid, I think that an error occurs. So please be careful this.
References:
Upload file version
Class UrlFetchApp

Is there anyway to mark images as spoiler?

The new discord update added the feature to mark images and text as spoilers for text: you just have to type || text ||. For images, there is a check mark at the bottom of the attachment prompt:
Is there a way to mark images as spoiler or is the feature too new?
This does not work:
let image = new Attachment('./img/image.jpg');
message.channel.send("|| " + image + " ||");`
a quick way of doing it would be starting the filename with SPOILER_
for example img.png would become SPOILER_img.png
message.channel.send({
files: [{
attachment: 'IMG LINK',
name: 'SPOILER_NAME.jpg'
}]
})
This is what the API has listed for the image for embeds and it doesn't seem to mention marking as a spoiler so perhaps it is yet to be added for bots. I can't find anything about spoilers in the API, maybe you'll have more luck.

Is there a way to set a request header using the JW Player

I am currently using the JW Player in a react app.
The videos I am trying to access are m3u8 playlist files that require a cookie to be sent in the header on each subsequent request.
Issue : So I can't just append the headers in the url as query params (e.g. https://somevideorul?cookie=somecookie).
Question : Is there a way to set headers with the request that the video player makes? I can't seem to find anything in their docs that support this.
Yes!
playlist: [{
sources: [{
file: 'video.m3u8',
onXhrOpen: function(xhr, url) {
xhr.setRequestHeader('customHeader', 'customHeaderValue');
}
}]
}]

How to get nightwatchjs screenshots working?

I am trying to generate a screenshot with nightwatch js , it saves a file to my location but the size is 1kb and when I try to open this there is no image. The config file is the one I got from https://www.npmjs.com/package/learn-nightwatch.
What could be the culprit?
Before you launch the screenshot, you need to be sure that the page is "ready". If you already checked that, please make sure that you added an image extension to the file name.
I'm sharing a working example:
module.exports = {
"Do a screenshot task" : function (browser) {
browser
.url("http://example.com")
.waitForElementPresent('body', 1000, 'Page loaded')
.resizeWindow(900, 3000)
.saveScreenshot('/home/yourName/path/imageName.png')
.end();
}
};
Hope it helps you.
As it stands this is how you can set up automatic screenshots in nightwatch.conf.js
"screenshots": {
"enabled": true,
"path": "./tests_output/screenshots", // location to save
"on_failure": true,
"on_error": true
}

how to transfer the taken image using ngcordova file transfer plugin to my ftp

I am trying to upload image to my FTP.
what i have achived so far is in this plnkr
my cordova file transfer looks like
$scope.upload =function(){
var options = {
fileKey: "file",
fileName: "gopi",
chunkedMode: false,
mimeType: "image/jpeg",
params : {'user_token':'Chandru#123', 'user_email':'wepopusers'} // directory represents remote directory, fileName represents final remote file name
};
console.log(options);
$cordovaFileTransfer.upload('ftp://308.3d8.myftpupload.com/', MyService.getImgPath(), options)
.then(function(result) {
// Success!
console.log(result);
console.log("SUCCESS: " + JSON.stringify(result.response));
alert('ftp success');
}, function(err) {
// Error
console.log(err);
alert('ftp fail');
console.log("ERROR: " + JSON.stringify(err));
}, function (progress) {
// constant progress updates
console.log(progress);
});
};
My response of my error function for cordova file looks like
FileTransferError {code: 2, source: "file:///storage/sdcard0/Android/data/com.ionicframework.camera108827/cache/1462186990291.jpg", target: "ftp://308.3d8.myftpupload.com/", http_status: null, body: null…}body: nullcode: 2exception: nullhttp_status: nullsource: "file:///storage/sdcard0/Android/data/com.ionicframework.camera108827/cache/1462186990291.jpg"target: "ftp://308.3d8.myftpupload.com/"proto: Object
I have button TakePicture which will take the pic and show to the user and also I have a function to upload using cordovafiletransfer $scope.upload .
my ftp host is ftp://308.3d8.myftpupload.com/ username and password is given in my coding in this i have a folder name called gopi where my image should store.
my path of the image taken is in imageURI parameter so i used services to set the path.
steps I’m in confusion
1) I am not able to understand the var options object in cordova file transfer plugin.
2) I am not getting any erro while remote debugging but i am only invoking my error funtion in my cordova file transfer.
How can i update my taken image to FTP using IONIC
UPDATE
Thanks to gandhi's answer https://github.com/xfally/cordova-plugin-ftp some how i managed to connect to ftp without multipart.
but sill facing error in this
$window.cordova.plugin.ftp.upload("/ping", "/gopi/ping", function(percent) {
i don't know what to in the first argument and second.
$window.cordova.plugin.ftp.upload("/default.prop", "/gopi/default.prop", function(percent) {
the above line success fully posted to my ftp but i am not able to post my image which is stored in my ping variable.
https://plnkr.co/edit/ETGmdl4B0d5dlHWdJQ9m?p=info
The answer to your first question is available in the official documentation of file transfer plugin. The excerpt is as follow,
options: Optional parameters (Object). Valid keys:
fileKey: The name of the form element. Defaults to file. (DOMString)
fileName: The file name to use when saving the file on the server. Defaults to image.jpg. (DOMString)
httpMethod: The HTTP method to use - either PUT or POST. Defaults to POST. (DOMString)
mimeType: The mime type of the data to upload. Defaults to image/jpeg. (DOMString)
params: A set of optional key/value pairs to pass in the HTTP request. (Object, key/value - DOMString)
chunkedMode: Whether to upload the data in chunked streaming mode. Defaults to true. (Boolean)
headers: A map of header name/header values. Use an array to specify more than one value. On iOS, FireOS, and Android, if a header named Content-Type is present, multipart form data will NOT be used. (Object)
Check out this link for more info.
For your second question, try getting the error code in the error callback function and try to narrow down the problem.
Update: I guess ftp upload is not possible using file transfer plugin. The plugin definition itself states "The FileTransfer object provides a way to upload files using an HTTP multi-part POST or PUT request, and to download files"
You may have to look at this for ftp client for ftp uploads.

Resources