I'm using API https://api.telegram.org/bot${botToken}/sendMessage via Javascript to send messages to my channel, and it works fine, but when I use latin characters like: é they are not printed correctly in Telegram, how can I solve this?
this is my code:
const url = `https://api.telegram.org/bot${botToken}/sendMessage`;
const data = new FormData();
data.append("chat_id", '-100'+chatId);
data.append("text", text);
fetch(url, {
method: 'POST',
cache: 'no-cache', cached
body: data
});
Related
I want to download certain videos with a click. For that, I created a Button and attached a Function that should trigger the associated video download.
But I am only able to download the link of the video, not the video. I am able to download videos with an external downloader or simply drag the URL to the download section of the browser. But unable to trigger that activity via JavaScript. Please help Me.
I tried multiple ways to tackle this problem:
Using a Simple Blob Technique without Axios:
const blob = new Blob([this.src_url], { type: 'video/mp4' })
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = this.src_url.replace(
>! // 'https://redis-test.com/videos/',
link.click()
URL.revokeObjectURL(link.href)
endpoint: video URL get downloaded as a file of 122 bytes
Then using File Saver Package:
var FileSaver = require('file-saver')
console.log(this.src_url)
var blob = new Blob([this.src_url], { type: 'video/mp4' })
FileSaver.saveAs(blob, 'hello world.mp4')
Then using the form method:
<form method="get" action="file.doc">
<button type="submit">Download!</button>
</form>
endpoint: video starts to play in the same window
Using href download attribute:
function download(url) {
const a = document.createElement('a')
a.href = url
a.download = url.split('/').pop()
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
endpoint: video starts to play in the same window
Using your method:
const link = document.createElement('a')
link.href = url
link.click()
endpoint: video starts to play in the same windows
With Axios defaults now:
axios.defaults.withCredentials = true
window.open(
'https://cdn.pixaandom_urlrbay.com/vieo/487508532/Woman%20-%2058142.mp4?rendition=source&expiry=1666842719&hash=7dd6d178d9dbbd8adaf68dafd80c9167e91eca21&download'
)
endpoint: video starts to play in the new window
With attaching disposable content type in headers with AXIOS:
axios
.get(
String(nuxtConfig.axios.mediaURL) +
this.src_url.replace(
'https://redisrandom_url.com/videos/',
''
),
{
headers: {
mode: 'no-cors',
referrerPolicy: 'no-referrer',
'Content-Disposition': 'attachment; filename=Woman - 58142.mp4',
Host: 'redis-nfs',
'User-Agent': 'PostmanRuntime/7.29.2',
Accept: '*/*',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br',
Connection: 'keep-alive',
Cookie:
'tk_or=%22https%3A%2F%2Fwww.google.com%2F%22; tk_lr=%22https%3A%2F%2Fwww.google.com%2F%22; _gcl_au=1.1.954672920.1660108804; _ga=GA1.2.1392122600.1660108808; _fbp=fb.1.1660108809200.1970395787',
'Upgrade-Insecure-Requests': '1',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-User': '?1',
Pragma: 'no-cache',
'Cache-Control': 'no-cache',
},
}
)
.then((response) => {
console.log(response)
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'title')
document.body.appendChild(link)
link.click()
})
.catch((error) => {
console.log('rex')
})
endpoint: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at redis-random_url/videos/be319-72e1-2e79-8dc3-bcef1/…. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200
"...But I am only able to download the link of the video, not the video."
I don't use VueJS but I suspect this.src_url is just text of the path to video URL.
In HTML5 you can only download those files that exist on your server. If the file is external then you need a PHP script (on same server as your HTML file) to read those external bytes back into your JS buffer array.
const blob = new Blob([this.src_url], { type: 'video/mp4' })
Should be:
let myBytes = //# update variable with data result of reading files bytes
let myBlob = new Blob( [ Uint8Array.from( myBytes ) ] , {type: "application/octet-stream"} );
Where the bytes reading can be done with FileReader API or Fetch API.
When you can read a file's bytes into an Array using VueJS then your problem is solved.
I'm trying to upload a file to an IPFS node using Google Apps Script (GAS) without success.
However, I was able to upload a file successfully using Postman. Unfortunately Postman only gives back the source code snippet closest to GAS as a JavaScript - Fetch code, which is not working as is in GAS.
In GAS, the authentication part is working and I know that because if I'm changing the bearer token, then I'm getting invalid credentials error instead of "Invalid request format".
Test code attached where I'm getting the "Invalid request format" error from the server.
For testing purpose, the file which needs to be uploaded, could be created on the fly with the script, but has to be one from Google Drive eventually.
function test() {
let myHeaders = {'Authorization': 'Bearer ...'};
let fileBlob = Utilities.newBlob('Hello!', 'text/plain', 'TestFile.txt');
let formdata = {'file': fileBlob,
'pinataMetadata': {'name': 'TestFileNewName.txt','keyvalues': {'MetaData1': 'Test1', 'MetaData2': 'Test2'}},
'pinataOptions': {'cidVersion': 0}};
let requestOptions = {
method: 'post',
headers: myHeaders,
papyload: formdata,
muteHttpExceptions: true
};
let url = "https://api.pinata.cloud/pinning/pinFileToIPFS";
let response = UrlFetchApp.fetch(url, requestOptions);
let responeText = JSON.parse(response.getContentText());
Logger.log(responeText);
}
If your access token of Bearer ... is the valid value for using the API, how about the following modification? From the official document, I thought that in the case of your formdata, the values of pinataMetadata and pinataOptions might be required to be the string type.
From:
let formdata = {'file': fileBlob,
'pinataMetadata': {'name': 'TestFileNewName.txt','keyvalues': {'MetaData1': 'Test1', 'MetaData2': 'Test2'}},
'pinataOptions': {'cidVersion': 0}};
To:
let formdata = {
'file': fileBlob,
'pinataMetadata': JSON.stringify({ 'name': 'TestFileNewName.txt', 'keyvalues': { 'MetaData1': 'Test1', 'MetaData2': 'Test2' } }),
'pinataOptions': JSON.stringify({ 'cidVersion': 0 })
};
And also, please modify papyload: formdata, to payload: formdata,. This has already been mentioned by
TheMaster's comment.
References:
Pin File
fetch(url, params)
In short: Here is some Python code posting to Betfair API. I would like to use Axios to do the same thing.
resp = requests.post('https://identitysso-cert.betfair.com/api/certlogin',
data=payload, cert=('TestApp.crt', 'client-2048.key'), headers=headers)
I'm reading through AXIOS docs, and am curious how to apply the cert=('TestApp.crt', 'cient-2048.key') field.
In detail: Currently, I have this:
axios({
method: "POST",
headers: headers,
url: "https://identitysso-cert.betfair.com/api/certlogin",
data: payload,
});
Would I use the form-data library replacing cert=('TestApp.crt', 'cient-2048.key') with form<FormData>
const FormData = require("form-data");
const form = new FormData();
form.append("my_field", "my value");
form.append("my_buffer", new Buffer(10));
form.append("my_file", fs.createReadStream("/foo/bar.jpg"));
axios.post("https://example.com", form, { headers: form.getHeaders() });
EDIT:
Scrapped the FormData route, and am using HTTPS for node js.
I add this along with the options I provide to Axios.
const httpsAgent = new https.Agent({
cert: fs.readFileSync("certificat.crt"),
ca: fs.readFileSync("key.pem"),
});
I in turn get this error:
Error: "Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN"
Digging a little deeper,
The error SELF_SIGNED_CERT_IN_CHAIN means that you cannot use self-signed certificates.
I ended up using Python to accomplish what I needed.
I'm trying to pull an access token from Office365's /token identity platform endpoint via OAuth 2.0 client credentials grant flow. I have my app registered, the client ID & secret, etc...
I can make the POST request in Postman and receive the access token without issue:
However, when I try the POST request via JavaScript (by way of Google Apps Script), I receive an error message: AADSTS900144: The request body must contain the following parameter: 'grant_type'
I've already Google'd this error and found a bunch of different solutions, and have tried implementing them to no avail. I imagine this has to do with the URL encoding, but cannot figure it out.
Code:
function getO365() {
// POST Request (To get Access Token)
var tenantID = 'longstringhere'
var appID = 'longstringhere'
var appSecret = 'longstringhere'
var graphScore = 'https://graph.microsoft.com/.default'
var url = 'https://login.microsoftonline.com/' + tenantID + '/oauth2/v2.0/token'
var data = {
'client_id': appID,
'scope': graphScore,
'client_secret': appSecret,
'grant_type': 'client_credentials'
};
var postOptions = {
'method': 'POST',
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
'body': data,
'redirect': 'follow'
};
var authToken = UrlFetchApp.fetch(url, postOptions);
}
The only real difference between my code and the JavaScript Fetch code I pulled off of Postman is:
var urlencoded = new URLSearchParams();
urlencoded.append("client_id", "longstringhere");
urlencoded.append("scope", "https://graph.microsoft.com/.default");
urlencoded.append("client_secret", "longstringhere");
urlencoded.append("grant_type", "client_credentials");
When I try to use URLSearchParams in Google Apps Script, I keep getting this error: ReferenceError: URLSearchParams is not defined
Any ideas? Thanks in advance!
This was resolved by changing 'body' to 'payload' for UrlFetchApp per the documentation. Edited code to reflect the change. Credit to #TheMaster for pointing out my mistake.
'payload': data,//from 'body': data,
I have built one asp.net web api for my angular application which is working fine. I'm going to use same api in Flutter but surprisingly I'm not getting full object in response.body. I observed that, response.body is containing only 1023 chars.
final response = await http.post(
apiUrl,
body: body,
headers: {
'Content-Type': 'application/json;',
'Accept': 'application/json ',
'Authorization': 'Bearer $_token',
});
print(response.body) // response.body string length is 1023.
Thank in advance looking at my issue.
i had a similar issue it seems that print has a char limit to unlock use this change number to match ur response chars or just set a higher number and use printWrapped (response.body); instead
void printWrapped(String text) {
final pattern = new RegExp('.{1,800}'); // 800 is the size of each chunk
pattern.allMatches(text).forEach((match) => print(match.group(0)));
}