I'm trying to set u a telegram bot whereby when someone makes a post on facebook, the post will be sent to telegram as well. Is there anything wrong with this code in general? I keep getting invalid or unexpected or token even after I have the correct API token and chat ID.
*API token and chat ID must be kept secret
const fetch = require('node-fetch');
let token = "<token*>";
let data = {
chat_id: "<chat ID*>",
text: "text"
};
(async () => {
await fetch(`https://api.telegram.org/bot${token}/sendMessage`,
{
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
}
}
)
})();
Related
I am using Twilio to integrate Salesforce with Whatsapp. When I get a message I create a case in Salesforce, how can I update the same case with 'closed' status?
I am trying to use this code, but I receive a error message
exports.handler = function(context, event, callback) {
const requestPayload = `{"Status":"Closed"}`;
const stts = JSON.parse(requestPayload);
getTokenInformation()
.then(token => {
const options = {
Authorization: 'Bearer ' + token.access_token,
'Content-Type': 'application/json'
};
return got(`${token.instance_url}/services/data/v56.0/sobjects/Case/${event.caseId}`, {
headers: options,
json: true,
method: 'PATCH',
body: stts,
});
Error message:
SyntaxError: Unexpected end of JSON input
at JSON.parse ()
at /var/task/handlers/ZF17ec8620a9320c740bb2f847bb1240b1.js:79:31
at processTicksAndRejections (internal/process/task_queues.js:95:5)
I finished developing my application with Next.js.
I used Next Auth to handle user authentication.
I use the Credential Provider for authentication with email and password.
In development everything works fine when I log in the session is well created and a JWT token is well generated.
On the other hand when putting in production it does not work, I have the following error:
[next-auth][error][CLIENT_FETCH_ERROR]
https://next-auth.js.org/errors#client_fetch_error invalid json response body at https://my-site.fr/api/auth/csrf reason: Unexpected token < in JSON at position 0 {
I really don't understand why the error only appears in production.
Here is the code of my Credential Provider
CredentialProvider({
async authorize(credentials, req) {
// console.log(credentials);
const url = `${process.env.NEXT_PUBLIC_API}/auth/login`;
const res = await fetch(url, {
method: "POST",
body: JSON.stringify(credentials),
headers: {
"Content-Type": "application/json",
Accept: "application/json, text/plain, */*'",
"User-Agent": "*",
},
});
// console.log(res);
const user = await res.json(res);
if (res.ok && user) {
return user;
}
return null;
},
}),
Thanks for your help.
I have built a discord bot and now want to build a website for it. I have managed to setup an implicit grant with discord oauth2, however I don't know how to get any of my scope values (identity, email, guilds, bot). All I have is the access token, the token type, the time it will take to expire, the guild id and the scopes, which are listed in the url. Please help!!!!
You need to call the GetCurrentUser Api
It is a GET to https://discord.com/api/users/#me
And you have to pass the Authorization header with your token.
EDIT
In javascript this code should do the work:
fetch('https : //discord.com/api/users/#me', {
method: 'GET',
headers: {
'Authorization': jwtToken,
}
})
.then(res => res.json())
.then(data => {
console.log(data);
});
Or async version:
async getUserInfo() {
const response = await fetch('https://discord.com/api/users/#me', {
method: 'GET',
headers: {
'Authorization': jwtToken,
}
});
var data = await response.json();
console.log(data);
}
getUserInfo();
The values you're looking for should be set as claims in your token.
Try to paste the token into https://jwt.io/
*My goal here is to get the location of bikes from a bike-sharing company's API.
I did Steps 1 and 2 using Postman. but ill try to integrate it into my code once I get the hang of it.
The first step is to verify your email and generate an Auth token. This requires only a verifiable email address. Make a POST request to https://web.spin.pm/api/v1/magic_links with the body:
{"email": "sampleemail#gmail.com"}
From there, you will need to find the token within your email. This token needs to be sent with a POST request to
https://web.spin.pm/api/v1/auth_tokens with the body:
{
"grant_type": "magic_link",
"magic_link": {
"email": "<email>",
"token": "<token>"
}
}
This request returns a JSON that looks like this: {"jwt":"eyJ0eXAiOiJ.....cXVLw","refreshToken":"2cb07....bab5030","existingAccount":false}
To get the position of vehicles so a GET-Request to https://web.spin.pm/api/v3/vehicles?lng=-77.0146489&lat=38.8969363&distance=&mode= User Header Authorization: Bearer to Authenticate and use the jwt-Token we got from the Auth request.
You will get something like this as return JSON {"vehicles":[{"lat":37.69247,"lng":-122.46595,"last4":"3595","vehicle_type":"bicycle","batt_percentage":null,"rebalance":null}, … ]}
Step 3 is done using (async/awit function) using fetch where I am having the problem with. I copy-pasted the jwt in my .env file and set up the proper headers.
I get a 401 response when making the call. when I tested step 3 using postman everything seems to work fine.
I have attached a screenshot of the error in this post. Hopefully its more clear, Thanks in advance.
const fetch = require("node-fetch");
require('dotenv').config();
async function getBikes()
{
const lat = '38.897574612438575';
const lng = '-77.01855164084469';
const api_url = `https://web.spin.pm/api/v3/vehicles?lng=${lng}&lat=${lat}&distance=&mode=`;
const jwt_key = process.env.BERER_KEY;
try{
const config = { method: 'GET',
headers: {json: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer'+ jwt_key
} },
rejectUnauthorized: false
};
const response = await fetch(api_url,config );
const data = await response.json(); //response.json() //headers //.jwt; //response.json()
if (response.ok)
{
console.log("STATUS CODE IS: "+response.status);
console.log('My JWT:', response);
return data;
}
else{
console.log("something went wrong ");
console.log("STATUS CODE IS: "+ response.status);
console.log( response);
}
} catch (error) {
console.log(error);
}
}
const y = getBikes();
console.log(y)
BEARER_KEY=eyJhbGciOiJIUzI1NiJ9.eyJ1c2V
Using feedlys api with a node wrapper suggested from feedly to access its api. I am not getting successful logins. I have scoured the docs and any resources available and cannot find any answers so I'm reaching out to the stack overflow community to see if anyone has had experience with this platform.
I tried clearing the cache. I've tried using the fetch api instead of using the node wrapper I am trying to implement.
I installed the node package 'feedly'.
added this code to my server:
const Feedly = require('feedly')
const f = new Feedly({
client_id: 'client_id here',
client_secret: 'client_secret here',
base: 'https://cloud.feedly.com/v3/collections/',
port: 8080
})
async function feedlyStream() {
const results = await f.reads()
return console.log('results', results)
}
feedlyStream();
It does take me to a page to log in, presumably this is the auth so then i can retrieve data.
I'm not a backend user and primarily front end so performing the task this way is new to me.
When i run nodemon ./server.js from the console, it takes me to a login page, like that of feedlys website but then I get the error 'session expired'. There is no other errors, not in the console etc.
I can get retrieve information when working with insomnia to test the api endpoints, with the same exact info as above plus a bearer token.
Here is the fetch version i have tried with is very similar to that of the insomnia input.
const URL = 'https://cloud.feedly.com/v3/collections/'
const proxyurl = "https://cors-anywhere.herokuapp.com/";
window.onload = () => {
fetch(proxyurl + URL, {
credentials: 'same-origin',
Accept: 'application/json',
headers:
{
'Authorization': 'Bearer TOKEN GOES HERE',
'Access-Control-Allow-Origin': 'include',
'Content-Type': 'application/json',
"client_id": "client_id here",
"method": "GET",
"client_secret": "client_secret here",
}
})
.then(function (data) {
console.log('data from api', data.body);
const here = document.getElementById("here")
const bodyText = () => {
if (data.body == null) {
return "Nope, it's null"
}
return data.body;
}
here.innerHTML = bodyText();
})
}
This is what i receive from the console log above
data from api ReadableStreamlocked: false__proto__: ReadableStream
Any help will be greatly appreciated. Thank you.
quite simply i was missing part of the fetch. I needed to transform the response into JSON. Not use to fetch or apis still and this was an obvious but annoying one.
"method": "GET",
"client_secret": "client_secret here",
}
})
.then(res => res.json();) // this is what i needed to add in :)
.then(function (data) {
console.log('data from api', data.body);