I’m trying to post tweets via the twitter API, using Needle to make the POST request and I'm getting error 32, Could not authenticate you.
I’m using oauth-1.0a to form the authorization data. I’ve been working off of the example code they give, which uses Request (now depreciated / no longer updated) instead of Needle. I know my keys / tokens are all in order because I can make posts fine using the Request library, I just want to do it using Needle, so something is being malformed obviously. Instead of just doing what works, I’m using this as a Learning Opportunity.
Here’s my needle request:
const oauth = OAuth({
consumer: {
key: the_key,
secret: the_secret,
},
signature_method: "HMAC-SHA1",
hash_function(base_string, key) {
return crypto.createHmac("sha1", key).update(base_string).digest("base64");
},
});
const request_data = {
url: "https://api.twitter.com/1.1/statuses/update.json",
method: "POST",
data: { status: "this is th best test tweet i've ever written" },
};
let options = {
headers: {
Authorization: oauth.toHeader(oauth.authorize(request_data, token))
.Authorization,
},
};
// Weird indent here, sumarrizing, sorry
needle(request_data.method, request_data.url, request_data.data, options)
.then((resp) => {
// console.log(Object.keys(resp.req));
console.log(resp.req._header);
if (resp.statusCode == 200) {
console.log(`Tweet posted at ${resp.body.created_at}`);
} else {
let err = resp.body.errors[0];
console.log(`Got code "${err.code}, ${err.message}" from twitter`);
}
})
.catch(async (err) => {
console.log(
`Got ${err} from twitter request, waiting ${
reconnectDelay / 1000
} seconds and trying again...`
);
await sleep(reconnectDelay);
reconnectDelay *= 2;
postTweet();
});
where request_data.data is {status: "this is a status that gets updated"}
Taking a peak at the headers that I sent from Needle, I get:
POST /1.1/statuses/update.json HTTP/1.1
accept: */*
user-agent: Needle/2.5.2 (Node.js v12.18.3; win32 x64)
authorization: OAuth oauth_consumer_key="XXX", oauth_nonce="XXX", oauth_signature="XXX", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1609292426", oauth_token="XXX", oauth_version="1.0"
content-length: 67
content-type: application/x-www-form-urlencoded
host: api.twitter.com
Connection: close
The headers look totally correct? Here's what the twitter docs say the header should look like.
Again, I know my tokens are correct because this works totally fine with:
request(
{
url: request_data.url,
method: request_data.method,
form: oauth.authorize(request_data, token),
},
function(error, response, body) {
if (error) console.log(error)
console.log(Object.keys(response.request))
console.log(response.request.body)
// console.log(response.req)
}
)
I’ve tried reforming the Needle request a few different ways and it’s really driving me crazy so any help would be appreciated! Thanks.