0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

5分でできる!Python製Twitter Botの作り方【最新API対応】

Posted at

PythonでTwitter Botを作る入門【X API対応】

こんにちは!この記事では、Pythonを使ってシンプルなTwitter(現X)Botを作成する方法を解説します。


✅ 準備するもの

  • Python 3.7以降
  • X APIの開発者アカウントとアクセスキー(Twitter Developer Portalで取得)
  • tweepy ライブラリ

🧰 必要なライブラリのインストール

pip install tweepy python-dotenv

🔑 .env ファイルに認証情報を記述

ルートフォルダに .env ファイルを作成し、以下を記述します。

API_KEY=xxxxxxxxxxxxxxxxxxxx
API_SECRET=xxxxxxxxxxxxxxxxxxxx
ACCESS_TOKEN=xxxxxxxxxxxxxxxxxxxx
ACCESS_TOKEN_SECRET=xxxxxxxxxxxxxxxxxxxx

🧠 Twitter BotのPythonコード(twitter_bot.py)

import tweepy
import os
from dotenv import load_dotenv

# .envの読み込み
load_dotenv()

# 認証情報の取得
API_KEY = os.getenv("API_KEY")
API_SECRET = os.getenv("API_SECRET")
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
ACCESS_TOKEN_SECRET = os.getenv("ACCESS_TOKEN_SECRET")

# 認証
auth = tweepy.OAuth1UserHandler(API_KEY, API_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)

# ツイートを投稿する関数
def tweet(text):
    try:
        api.update_status(text)
        print("✅ ツイート完了!")
    except Exception as e:
        print(f"❌ エラー: {e}")

# 実行例
if __name__ == "__main__":
    tweet("こんにちは、これはPythonからの自動ツイートです! #Python #TwitterBot")

📅 応用:定期ツイートにするには?

cronschedule ライブラリで定期ツイートにもできます。例えば:

pip install schedule
import schedule
import time

def job():
    tweet("定期ツイートだよ! #PythonBot")

schedule.every(1).hours.do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

✨ まとめ

Python + Tweepyを使えば、X(Twitter)のBotが簡単に作れます!キーワード返信、自動フォローなどの機能追加もできるので、ぜひ挑戦してみてください。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?