问题
I am not a coder but I've managed to successfully use the Google script below to integrate with Twitter API to send tweets, add users to lists and more, from a Google Sheet.
I found the script on Google's developer documentation here and with the help of @Diego here I managed to work it out to do all sorts of Twitter POST operations by changing the payload
parameters and the url
for the call.
For some reason I can't understand why, sending DMs keeps on returning ERROR message: Exception: Request failed for https://api.twitter.com returned code 401. Truncated server response: {"errors":[{"code":32,"message":"Could not authenticate you."}]}
.
But for example if I change the payload to this:
var params = '';
var options = {
method: 'POST',
payload: {
list_id: listId,
screen_name: newMembers
}
};
and authUrlFetch.fetch('https://api.twitter.com/1.1/direct_messages/events/new.json ', params, options);
to this: https://api.twitter.com/1.1/lists/members/create_all.json
. The same code will successfully ad users to lists.
I followed the instructions on Twitter's DM help page but I can't figure out what am I doing wrong to get the authentication error?
// User-level Twitter API request
// Requires the OAuth1 library to be pasted into the script.
// https://developers.google.com/google-ads/scripts/docs/examples/oauth10-library
// https://developer.twitter.com/en/docs/twitter-api/v1/direct-messages/sending-and-receiving/api-reference/new-event
// Twitter app
var CONSUMER_KEY = '************************';
var CONSUMER_SECRET = '************************';
var ACCESS_TOKEN = '************************';
var ACCESS_SECRET = '************************';
/**
* Sends a tweet.
* @param {user_id} [recipient_id] - The user ID of the recipient
* @param {dm_message} [text] - The te text of the DM to send the recipient
*/
function sendDm(user_id, dm_message) {
if (typeof OAuth1 === 'undefined') {
var libUrl = 'https://developers.google.com/google-ads/scripts/docs/examples/oauth10-library';
throw Error('OAuth1 library not found. Please take a copy of the OAuth1 ' +
'library from ' + libUrl + ' and append to the bottom of this script.');
}
var params = '';
var options = {
method: 'POST',
contentType: 'application/json',
payload: {
event: {
type: 'message_create',
message_create: {
target: {
recipient_id: user_id
},
message_data: {
text: dm_message
}
}
}
},
};
var authUrlFetch = OAuth1.withAccessToken(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET);
var response = authUrlFetch.fetch('https://api.twitter.com/1.1/direct_messages/events/new.json', params, options);
var responseText = response.getContentText();
return JSON.parse(responseText);
}
/**
* Google Ads Twitter OAuth1 library goes here
https://developers.google.com/google-ads/scripts/docs/examples/oauth10-library
*/
来源:https://stackoverflow.com/questions/65256374/google-script-sheets-twitter-api-integration-post-direct-messages-events-n