LoginSignup
3
0

More than 3 years have passed since last update.

GASでTwitterのDMを送るには

Posted at

はじめに

GASでTwitterのDM送信したいんだけどCode:32が帰ってくる という事例があり正しい送り方を調べてみました。ググっても正解が出てこない!w

なぜ送れなかったのか

端的に言うと、2018年夏のDM API新仕様にちゃんと対応できていなかったから、でした。新仕様における必須要件の一つである、Content-Typeが設定できていなかったのです。

作ったもの

function newDirectMessage(recipient_id, data){
  try{
    var service = twitter.getService();
    var payload = JSON.stringify({
      event: {
        type: 'message_create',
        message_create: {
          target: {
            recipient_id: String(recipient_id)
          },
          message_data: data
        }
      }
    });
    var response = service.fetch('https://api.twitter.com/1.1/direct_messages/events/new.json',{
      method: 'POST',
      contentType: 'application/json',
      payload: payload
    });
    return response;
  }catch(e){
    Logger.log('Exception:'+e);
  }
}
function demoDirectMessage(){
  newDirectMessage(recipient_id,{text:"送りたい文言"});
}

肝は以下の2点です。

  • payloadは明示的にjsonを作る
  • Content-Typeに'application/json'を指定する
    • これのやり方がわからなかった! Service.gs のコードを追いかけてやっと判明したという。

おまけ

前提となる環境整備の部分とかは@zensai3805さんのGoogle Apps Script(GAS)でスパムと思われるTwitterアカウントを自動的にブロックするをご覧ください。(他力本願)

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0