🦔

Twitter APIのFreeプランを利用してツイートする

2023/04/20に公開

はじめに

2023年2月にTwitter社がTwitter APIの有料化を発表し、3月末に新しい料金プランを公開しました。
今回は無料で利用できるFreeプランを利用してツイートする方法を確認しました。

新プランの概要

Free Basic Enterprise
料金 無料 100ドル/月 非公開
APPのID数 1件まで 2件まで 非公開
ツイート投稿 1,500件/月 3,000件/月 非公開
ツイート取得 × 10,000件/月 非公開

月1,500件以下のBot投稿であればFreeプラン、それ以上の投稿やツイートの分析等を行う場合は、Basicプラン以上を利用する必要がありそうです。
https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api

Developer Accountの登録

Twitter APIを利用する為には、developerサイトでDeveloper Accountを登録する必要があります。
Freeプランの場合は「Sign up for Free Account」を選択します。

TwitterのデータとAPIの使用例を250文字以上で説明します。

アプリの設定

ダッシュボードにデフォルトのアプリが1つ登録されています。今回はそのまま使用します。
アプリを開いて、User authentication settingsを編集します。

アプリの権限が「Read」のみになっているので、「Read and Write」に変更します。
Callback URIとWebsite URLは必須です。今回はとりあえず https://twitter.com/ を入れておきます。

Keys and tokensの生成

Consumer Keys

ダッシュボードでアプリのConsumer Keysを作成します。
作成されたAPI KeyとAPI Key Secretはコピーして保存しておきます。

Access Token and Secret

続けて、Access Token and Secretを作成します。
作成されたAccess TokenとAccess Token Secretはコピーして保存しておきます。

ツイートを投稿する

JavaのTwitter API v1.1のライブラリで一般的なのはTwitter4Jですが、Twitter4JはTwitter API v2が未対応だった為、今回はTwitteredというライブラリを使用してみました。

import io.github.redouane59.twitter.TwitterClient;
import io.github.redouane59.twitter.signature.TwitterCredentials;

public class TestTwittered {
    public static void main(String[] args) {
        try {

            TwitterCredentials credentials = TwitterCredentials.builder()
                                  .apiKey(CONSUMER_KEY)
                                  .apiSecretKey(CONSUMER_SECRET)
                                  .accessToken(ACCESS_TOKEN)
                                  .accessTokenSecret(ACCESS_SECRET).build();

            TwitterClient client = new TwitterClient(credentials);

            String tweetText = "Hello, world!";
            client.postTweet(tweetText);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

まとめ

Twitter APIを利用する為に必要な手順は多くないのですが、デフォルトで「Read」専用の権限になっていたり、既存のライブラリが使用できなかったりで、所々でポイントになる所がありました。
こちらの記事が少しでも今後利用する方の参考になれば幸いです。

レスキューナウテックブログ

Discussion