1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

VSCodeでTwitter API (X API)とPythonを使用したい...ということで?!

Last updated at Posted at 2025-03-27

はじめに

お久しぶりです!今回はTwitter (X) API & PythonをVSCode上で開発するための構築について記録します👍
前々から気になっていた自動ツイート...なぜかって??IoT機器で取得した情報を自動ツイートやLamda&スケジューラを使用したツイート...などなどおもしろそうな開発をできそうだからです!テキスト&画像付きツイートの投稿方法、今回発生したエラーと解決策についても記録しますね!

開発環境

  • OS: Windows11
  • 開発環境: VSCode
  • 言語: Python
  • ライブラリ: tweepy, python-dotenv

1. X API の準備(API キーの取得)

※ 本投稿では事前に登録やプロジェクトの作成をしているので、実施事項は他サイトを参照してください 要望が多かったり時間があったら別の記事を...(´・ω・`)

  1. X Developer Portal にアクセスし、アイコン横のDeveloper Portalを選択
    image.png
  2. Projects & Apps から任意のプロジェクトを選択
  3. Consumer Keys (API Key & API Secret) を取得
  4. Access Token & Secret を取得
  5. Bearer Token も取得
    image.png

2. VSCodeでの環境構築

2.1 仮想環境の立ち上げ

プロジェクトごとでライブラリを分けたいので、仮想環境を作成します。任意のディレクトリに移動して、以下のコマンドをそれぞれ実施。(※VSCodeのPS上で実施)

# 1.virtualenvのインストール
> pip install virtualenv
# 2.仮想環境の作成
> python -m venv venv
# 3.Twitter(X)の投稿に必要なライブラリとenv管理のためのライブラリをインストール
> pip install tweepy python-dotenv

2.2 .env ファイルの作成

API キーやトークンを安全に管理するため、.env ファイルをmainソースと同じディレクトリに作成し、以下のように生成したTokenを記述&保存。

.env
CONSUMER_KEY=xxxxxxxxxxxxxxxxxxxxxx
CONSUMER_SECRET=xxxxxxxxxxxxxxxxxxxxxx
ACCESS_TOKEN=xxxxxxxxxxxxxxxxxxxxxx
ACCESS_TOKEN_SECRET=xxxxxxxxxxxxxxxxxxxxxx
BEARER_TOKEN=xxxxxxxxxxxxxxxxxxxxxx

3. Python でツイートを投稿する

3.1 テキストツイートの投稿

以下のコードで、環境変数を .env から読み込み、ツイートを投稿します。

main.py
import os
from dotenv import load_dotenv
import tweepy

# .env ファイルを読み込む
load_dotenv()

# APIキーを取得
consumer_key = os.getenv("CONSUMER_KEY")
consumer_secret = os.getenv("CONSUMER_SECRET")
bearer_token = os.getenv("BEARER_TOKEN")
access_token = os.getenv("ACCESS_TOKEN")
access_token_secret = os.getenv("ACCESS_TOKEN_SECRET")

# Tweepy クライアントを作成
client = tweepy.Client(
    bearer_token=bearer_token,
    consumer_key=consumer_key,
    consumer_secret=consumer_secret,
    access_token=access_token,
    access_token_secret=access_token_secret
)

# ツイートを投稿
client.create_tweet(text="Hello World\nThis is a multi-line tweet.")

3.2 画像付きツイートの投稿

Tweepy の API を使用して、画像をアップロードしてツイートします。main.pyと同じ場所に画像をおいて実行してみてください。(任意の場所でも可能)

main.py
# library
import os
from dotenv import load_dotenv
import tweepy

# .env ファイルを読み込む
load_dotenv()
# Twitter Deverloper Portalで取得
consumer_key = os.getenv("CONSUMER_KEY")
consumer_secret =  os.getenv("CONSUMER_KEY_SECRET")
bearer_token = os.getenv("BEARER_TOKEN")
access_token = os.getenv("ACCESS_TOKEN")
access_token_secret = os.getenv("ACCESS_TOKEN_SECRET")

# Client (テキスト投稿用)
client = tweepy.Client(bearer_token=bearer_token,
                        consumer_key=consumer_key,
                        consumer_secret=consumer_secret,
                        access_token=access_token,
                        access_token_secret=access_token_secret)

# OAuth認証
auth = tweepy.OAuth1UserHandler(consumer_key, consumer_secret, access_token, access_token_secret)
api = tweepy.API(auth)

# 画像をアップロード
media = api.media_upload("クロネコアイコン2.jpeg")  # アップロードしたい画像のパスを指定

# 画像付きツイートを投稿(改行を含める)
tweet_text = "2025/03/25 - Hello World\nThis is a multi-line tweet with an image.\n #Python #API #開発はじめ"
client.create_tweet(text=tweet_text, media_ids=[media.media_id])

最終的な実施結果例

4. 発生したエラーと解決策

4.1 401 Unauthorized (89 - Invalid or expired token)

対策: API キーやアクセストークンが正しいか確認。

  • .envCONSUMER_SECRET のスペルミスがないかチェック
  • Twitter Developer PortalAccess Token & Secret を再発行
  • envが読み込まれているか確認
main.py(任意の場所に追加)
# None がある場合、エラーを出して処理を中断
if None in (consumer_key, consumer_secret, access_token, access_token_secret):
    raise ValueError("環境変数が正しく設定されていません。'.env' ファイルを確認してください。")
  • api.verify_credentials() を使って認証をテスト
main.py(任意の場所に追加)
try:
    api.verify_credentials()
    print("✅ 認証成功!")
except tweepy.TweepError as e:
    print(f"❌ 認証エラー: {e}")

5. まとめ

  • Python + Tweepy で Twitter (X) API を使い、ツイート投稿を実装
  • .env を活用して API キーを安全に管理
  • 画像付きツイートの投稿方法も紹介
  • 主要なエラー (401 Unauthorized) の解決策を整理

今回はAPIとPythonを用いて、自動ツイートという環境セットアップをしましたが、本質はここではなく、スケジューラなどのツールを用いた投稿システムを作成することなので、記録として残しますね (´・ω・`)

参考文献

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?