Skip to content

Instantly share code, notes, and snippets.

@togosh
Last active September 3, 2021 22:46
Show Gist options
  • Save togosh/a74235512c94428272d7ab611b1ba1ad to your computer and use it in GitHub Desktop.
Save togosh/a74235512c94428272d7ab611b1ba1ad to your computer and use it in GitHub Desktop.
Twitter Bot (Post Tweet with Image)
// https://developer.twitter.com/en/apply-for-access
const twitterAPI = require('twitter-api-client');
const imageToBase64 = require('image-to-base64');
var twitterClient = new twitterAPI.TwitterClient({
apiKey: "XXXXXXXXXXXXXXXX",
apiSecret: "XXXXXXXXXXXXXXXX",
accessToken: "XXXXXXXXXXXXXXXX",
accessTokenSecret: "XXXXXXXXXXXXXXXX",
});}
async function tweet(imageURL=undefined){
var mediaId = "";
var tweetStatus = "";
if (imageURL) {
mediaId = await uploadImage(imageURL);
}
tweetStatus += "TESTING" + "\r\n";
tweetStatus += "\r\n";
// https://developer.twitter.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-statuses-update
const data = await twitterClient.tweets.statusesUpdate({
status: tweetStatus,
media_ids: mediaId
});
return;
}
async function uploadImage(imageURL){
var imageData = await imageToBase64(imageURL);
//https://developer.twitter.com/en/docs/twitter-api/v1/media/upload-media/api-reference/post-media-upload
const data = await twitterClient.media.mediaUpload({ media_data: imageData });
return data.media_id_string || '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment