0

【2023年7月利用可能】GASを使用してGoogleDrive上の画像をTweetする

最終更新日 投稿日 2023年06月29日

GASを使用してtwitterで画像をツイートするコードを備忘録として残します。
twitter APIは今年に入って多くの改変(主に改悪)をしていますが、こちらは2023.6.29現在、Freeプランでツイート可能です。

すでに文章のみでのツイートはできる前提での記事になりますので、そちらについては以下のわかりやすい記事がございますので、そちらを参考にしてください。

以下はやっていくことのイメージです
image.png

ポイントは2つあって

1.Base64への変換が必要

2.アップロード先とツイート先のapiが違う

以下、コードです

function tweetWithImage() {
  var value = '******'; // Replace with your tweet message
  
  // Upload the image and get its media ID
  var mediaId = uploadImageFromDrive();

  // Check if the image upload was successful
  if (mediaId) {
    // Tweet with the uploaded image
    const url = "https://api.twitter.com/1.1/statuses/update.json";
    const payload = {
      "status": value,
      "media_ids": mediaId
    };
    const options = {
      'method': 'post',
      'payload': payload,
      'muteHttpExceptions': true
    };
    makeRequest(url, options);
  }
}

// Upload an image from a Google Drive URL to Twitter and return its media ID
function uploadImageFromDrive() {
  var imageFile = DriveApp.getFileById("******"); //https://drive.google.com/file/d/******/view 
  var base64Data = Utilities.base64Encode(imageFile.getBlob().getBytes())


  const url = "https://upload.twitter.com/1.1/media/upload.json";

  const service = getService();
  const mediaUploadParams = {
    'method': 'post',
    'payload': { 'media': base64Data },
    'muteHttpExceptions': true
  };

  const res = service.fetch(url, mediaUploadParams);
  const result = JSON.parse(res.getContentText());

  if (result && result.errors && result.errors[0] && result.errors[0].code === 324) {
    console.log('Error: Unsupported media type. Please ensure the image is in a supported format (JPEG, PNG, GIF).');
    return null;
  }

  if (result && result.media_id_string) {
    return result.media_id_string;
  } else {
    console.log('Image upload failed.');
    console.log(res.getContentText()); // Log the response content text for debugging
    return null;
  }
}

function makeRequest(url, options) {
  const service = getService();
  const res = service.fetch(url, options);
  const result = JSON.parse(res.getContentText());
  console.log(JSON.stringify(result));
}

chatGPTがくれたコードを少しかえてもってきたのでやや冗長ですがこれでうまくいきました
適宜******を本文と画像のID(https://drive.google.com/file/d/******/view)にかえてください
chatGPTがBase64への変換をやってくれず苦労しました、

参考 
https://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q10253949515
https://note.com/kadoyu/n/naa35ff9f945f
https://www.noelcafe.com/blog/entry_010157/

新規登録して、もっと便利にQiitaを使ってみよう

  1. あなたにマッチした記事をお届けします
  2. 便利な情報をあとで効率的に読み返せます
ログインすると使える機能について
q13
@q13

コメント

この記事にコメントはありません。
あなたもコメントしてみませんか :)
新規登録
すでにアカウントを持っている方はログイン
記事投稿キャンペーン開催中
100万人に届けたい!私のお気に入りガジェット
~
100万人に伝えたい!失敗を乗り超えた話を共有しよう
~
0