Upload and Post Images to Twitter with Google Script

Last Updated : 23 Jul, 2025

Twitter is a social media site that allows its users to publish short messages, called "tweets," to their followers. Twitter does allow for an interface that will accept an image to be uploaded. We can also automate the process of uploading the images to Twitter.

Google Apps Script is a cloud-based scripting platform developed by Google. It provides the possibilities for automation by utilizing other Google services including Gmail, Sheets, and Drive. It is also possible to use it for working with various external APIs. This article will explain how to use Google Apps Script to upload and post images on your Twitter account.

Steps to Post Images to Twitter with Google Apps Script:

Step 1: Create an account for Twitter developer and register an application with Twitter.

First of all, you need to have a Twitter Developer account and set up an application that will issue access keys for the Twitter API before setting out to connect Google Apps Script with Twitter.

  • Go to the Twitter Developer Portal and log in at: https://developer.x.com/en
Sign-in
Login to Twitter Developer Portal
  • Create a New App: After logging in on the dashboard, you will get the application by default created by Twitter API.
    • Fill in Application Name and Description, and other required information.
    Create-New-App
    Create new app and fill required information
  • Generate Access Tokens: Once the app is created, go to the "Keys and Tokens" tab.
    • Create API Key, API Secret Key, Bearer Token, Access Token and Access Token and Secret, by clicking on the "Generate" button.
    Keys-and-Tokens
    Important API Keys and Tokens
    • Please keep these credentials securely as they are going to be used in Google Apps Script.

Step 2: Google Apps Script Configuration

  • Open Google Apps Script: Go to script.google.com, create a new project.
new-project
Click on new project
  • Include Twitter OAuth Library:
    • In the left-hand sidebar of the Apps Script editor, click on Libraries.
    Add-library-option
    Add library Option
    • You can add the OAuth1 library by giving the script ID: 1CXDCY5sqT9ph64fFwSzVtXnbjpSfWdRymafDrtIZ7Z_hwysTY7IIhi7s.
    OAuth-Script
    Add OAuth1 library with Script

Step 3: Now, lets write the script to post an image

The following sample script below shows how to upload and post an image to Twitter:

JavaScript
function postImageToTwitter() {
  // Twitter API credentials
  var API_KEY = 'your-api-key';  // Replace with your API Key
  var API_SECRET = 'your-api-secret';  // Replace with your API Secret
  var ACCESS_TOKEN = 'your-access-token';  // Replace with your Access Token
  var ACCESS_TOKEN_SECRET = 'your-access-token-secret';  // Replace with your Access Token Secret

  // Initialize the OAuth1 service for Twitter
  var oauthService = OAuth1.createService('twitter')
    .setAccessTokenUrl('https://api.twitter.com/oauth/access_token')
    .setRequestTokenUrl('https://api.twitter.com/oauth/request_token')
    .setAuthorizationUrl('https://api.twitter.com/oauth/authorize')
    .setConsumerKey(API_KEY)
    .setConsumerSecret(API_SECRET)
    .setAccessToken(ACCESS_TOKEN, ACCESS_TOKEN_SECRET);

  // Check if the OAuth service is authorized
  if (!oauthService.hasAccess()) {
    var authorizationUrl = oauthService.authorize();
    Logger.log('Open the following URL to authorize: ' + authorizationUrl);
    return;
  }

  try {
    // Image URL
    var imageUrl = "https://media.geeksforgeeks.org/wp-content/uploads/20230825143824/Install-Windows-10-From-USB-Flash-Drive.webp";  
    // Replace with your image URL

    // Convert the image to binary format
    var response = UrlFetchApp.fetch(imageUrl);
    var imageBlob = response.getBlob();

    // Upload media to Twitter
    var mediaUploadUrl = "https://upload.twitter.com/1.1/media/upload.json";
    var uploadResponse = oauthService.fetch(mediaUploadUrl, {
      method: "POST",
      muteHttpExceptions: true,  // Handle HTTP errors properly
      contentType: 'multipart/form-data',
      payload: {
        media_data: Utilities.base64Encode(imageBlob.getBytes())  // Encode image in Base64
      }
    });

    // Log the full response (headers, status, content)
    Logger.log("Response Code: " + uploadResponse.getResponseCode());
    Logger.log("Response Headers: " + JSON.stringify(uploadResponse.getAllHeaders()));
    Logger.log("Upload Response: " + uploadResponse.getContentText());

    var uploadResponseText = uploadResponse.getContentText();

    if (uploadResponse.getResponseCode() !== 200) {
      throw new Error("Media upload failed. Response code: " + uploadResponse.getResponseCode());
    }

    var mediaId = JSON.parse(uploadResponseText).media_id_string;

    // Post tweet with the uploaded media
    var tweetText = "This is a test tweet with an image!";
    var postTweetUrl = "https://api.twitter.com/1.1/statuses/update.json";
    var tweetResponse = oauthService.fetch(postTweetUrl, {
      method: "POST",
      muteHttpExceptions: true,  // Handle HTTP errors properly
      payload: {
        status: tweetText,
        media_ids: mediaId
      }
    });

    Logger.log("Tweet posted successfully: " + tweetResponse.getContentText());

  } catch (error) {
    Logger.log("Error: " + error.toString());
  }
}

Step 4: Running the Script

  • Replace API_KEY, API_SECRET, ACCESS_TOKEN, and ACCESS_TOKEN_SECRET with your credentials from Twitter Developer.
Keys-and-Tokens
Replace with your Keys and Tokens
  • Now instantiate the imageUrl with the path of the image to be uploaded. Images can also be uploaded from Google Drive using the getBlob() method.
example-image
Replace with your image URL
  • In the Apps Script editor, clicked the "Run" button. Since this is the very first time this script was run, a request popped to authorize the OAuth1 connection. Click on "Review permissions" and grant access.
Provide-access
Provide Access

Step 5: Testing and Output

After the script runs successfully, you should see a new tweet on your Twitter timeline containing the uploaded image and the message defined in the script.

Tweet Example:

  • Text: "This is a test tweet with an image!"
  • Image: The image from the specified URL or Google Drive will be attached to the tweet.

We can modify the script to dynamically fetch images from Google Drive, Google Sheets, or external URLs as needed.

Output

Twitter-output
Twitter Output

Key Points to Check

  1. API Credentials: Ensure you have the correct API Key, API Secret, Access Token, and Access Token Secret from the Twitter Developer Portal.
  2. OAuth1 Library: Make sure you've added the OAuth1 library in your Apps Script project with the script ID: 1CXDCY5sqT9ph64fFwSzVtXnbjpSfWdRymafDrtIZ7Z_hwysTY7IIhi7s.
  3. HTTP Status Codes: Use muteHttpExceptions: true to handle HTTP responses properly. This allows you to debug any issues with the API calls.
  4. Access Permission: Make sure that your app has "Read and write" permission enabled. Otherwise this script won't work, and you will get an error and nothing will happen. It will be found in User authentication settings.
App-permission
Mandatory to change permission

Conclusion

In conclusion, one can post images to Twitter using Google Apps Script easily, but it requires a lot knowledge and patience. Main part is setting account and app in Twitter developer. It is rather an effective automation for different social media tasks. This use case allows for a simple OAuth1 connection in order to interact with the Twitter API by posting updates, media, and many others, by just a few lines of code into their respective Google environment. Such a solution would work for both personal and business applications since it remains scalable and open for customizations.

Comment