【簡単自動化】Pythonを使ったTwitter予約投稿プログラムの作成手順

1. Twitter APIの取得とライブラリのインストール

Twitter Developer登録:
 Twitter Developerに登録し、各アカウントごとにAPIキーとアクセストークンを取得します。

■Tweepyライブラリのインストール:
 Tweepyを利用してPythonからTwitter APIを操作するために、pip install tweepyでTweepyをインストールします。

2. Pythonスクリプトの作成

■予約投稿のロジック:
 各アカウントの情報(APIキー、アクセストークン)を使って、指定された日時にツイートするロジックを実装します。

import tweepy
from datetime import datetime, timedelta
import time

# Twitter API認証情報の設定
api_key = 'YOUR_API_KEY'
api_secret_key = 'YOUR_API_SECRET_KEY'
access_token = 'YOUR_ACCESS_TOKEN'
access_token_secret = 'YOUR_ACCESS_TOKEN_SECRET'

# Tweepyを使用した認証
auth = tweepy.OAuthHandler(api_key, api_secret_key)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

# 投稿内容の設定
accounts = [{'username': 'account1', 'text': 'Hello World!',
  'media': ['image1.jpg', 'video.mp4'], 'hashtags': ['example', 'python'],
  'schedule_time': '2023-12-31 12:00:00'},
{'username': 'account2', 'text': 'Another tweet!',
  'media': ['image2.jpg'], 'hashtags': ['tweepy', 'automation'],
  'schedule_time': '2023-12-31 15:30:00'}]

# ツイート関数
def tweet(account):
try:
# ツイート内容の作成
tweet_text = f"{account['text']} {' '.join(account['hashtags'])}"

# 画像や動画の添付
media_ids = []
for media in account['media']:
media_id = api.media_upload(media).media_id
media_ids.append(media_id)

# ツイート実行
api.update_status(status=tweet_text, media_ids=media_ids)
print(f"Tweeted from {account['username']} successfully!")
except tweepy.TweepError as e:
print(f"Error while tweeting from {account['username']}: {e}")

# 予約投稿の実行
for account in accounts:
scheduled_time = datetime.strptime(account['schedule_time'], '%Y-%m-%d %H:%M:%S')
current_time = datetime.now()
if scheduled_time > current_time:
time_difference = (scheduled_time - current_time).total_seconds()
time.sleep(time_difference)
tweet(account)
else:
print(f"Skipping tweet for {account['username']}, schedule time has passed.")

3. スクリプトの実行と運用

■スケジュール設定:
 Cronジョブやタスクスケジューラを使用して、定期的にスクリプトを実行します。

■エラーハンドリング:
 スクリプトにエラーハンドリングを組み込み、問題が発生した際の対処法を考慮します。

以上の手順で、複数のTwitterアカウントに対して予約投稿ができるPythonスクリプトを構築できます。ただし、API制限やセキュリティの観点から適切な対応が必要です。

 

moun45.hatenablog.com