見出し画像

【対選手権決戦兵器】X選手権の投稿を自動監視・リプライするPythonスクリプト

残り2

2024/12/19
価格は購入人数に比例して順次上げていくつもりですがまずは数名限定で販売したいと思います。

Twitter(X)での選手権関連の投稿を自動で監視し、条件に合うツイートに対してリプライを投稿するスクリプトを作成しました。このスクリプトを利用すれば、効率的にエンゲージメントを増やし、ターゲット層へのリーチを拡大できます。

本記事の内容

  • 何ができるのか

    • 選手権の投稿(特定のハッシュタグやキーワードを含むツイート)を監視

    • 条件に合うツイートに自動リプライを投稿

    • API制限や投稿上限を管理しながら効率的に動作

  • コードの説明

    • 必要なPythonライブラリと準備

    • 設定ファイルの読み込みと管理

    • ユーザーの投稿を監視してリプライを投稿するロジック

  • 実行方法

    • スクリプトの設定方法と使い方


コードの概要

以下は、このスクリプトの主要な部分を説明したものです。

必要なライブラリ

import tweepy
import time
import json
import random
from datetime import datetime, timezone

このスクリプトでは、Twitter APIを操作するために tweepy を使用します。他にも、設定ファイルの管理や時間計算のための標準ライブラリを活用します。

設定ファイルの管理

APIキーやトークン、ユーザーリストやキーワードリストなどを外部ファイルで管理します。

# 設定ファイルの読み込み
def load_config():
    with open("config.json", "r") as file:
        return json.load(file)

# 外部ファイル読み込み
def load_file(file_path):
    with open(file_path, "r", encoding="utf-8") as file:
        return [line.strip() for line in file if line.strip()]

これにより、スクリプト本体を変更することなく、設定を柔軟に管理できます。

ツイート監視とリプライの実装

以下は、主要なロジック部分です。

# ツイートを監視してリプライ
def monitor_and_reply(client, user_ids, comments, keywords, max_posts=10):
    post_count = 0
    last_seen_ids = load_last_seen_ids()  # {user_id: last_tweet_id}

    while post_count < max_posts:
        try:
            for username, user_id in user_ids.items():
                print(f"\n--- ユーザー: {username} のツイートを監視中 ---")
                since_id = last_seen_ids.get(user_id)

                tweets = client.get_users_tweets(
                    id=user_id,
                    since_id=since_id,
                    tweet_fields=["id", "text", "created_at"]
                )

                if not tweets.data:
                    print(f"新しいツイートがありません (ユーザー: {username})。")
                    continue

                for tweet in reversed(tweets.data):
                    tweet_time = tweet.created_at.replace(tzinfo=timezone.utc)
                    if (datetime.now(timezone.utc) - tweet_time).total_seconds() > 300:
                        continue

                    if any(keyword in tweet.text for keyword in keywords):
                        random_comment = random.choice(comments)
                        try:
                            client.create_tweet(text=random_comment, in_reply_to_tweet_id=tweet.id)
                            print(f"リプライを投稿しました: {random_comment} (ツイートID: {tweet.id})")
                            post_count += 1
                            last_seen_ids[user_id] = str(tweet.id)
                            save_last_seen_ids(last_seen_ids)

                            if post_count >= max_posts:
                                print("投稿数の上限に達しました。スクリプトを終了します。")
                                return

                            time.sleep(random.randint(5, 10))
                        except tweepy.Forbidden:
                            print(f"リプライ制限でスキップ (ツイートID: {tweet.id})")

                print(f"--- ユーザー: {username} の処理が完了しました ---")
                time.sleep(5)

            print("\n全ユーザーの監視が完了しました。5分待機して再実行します...")
            time.sleep(300)

        except tweepy.TooManyRequests as e:
            handle_rate_limit(e)
        except Exception as e:
            print(f"エラー発生: {e}")
            time.sleep(600)

主な機能

  • ツイートの取得と監視

  • キーワードによるフィルタリング

  • ランダムなコメント投稿

  • レートリミットやエラーの処理


スクリプトの使い方

  1. 必要なPythonライブラリのインストール

以下のコマンドで必要なライブラリをインストールします。

pip install tweepy
  1. 設定ファイルの準備

以下のように config.json ファイルを作成します。

{
    "BEARER_TOKEN": "your_bearer_token",
    "API_KEY": "your_api_key",
    "API_SECRET": "your_api_secret",
    "ACCESS_TOKEN": "your_access_token",
    "ACCESS_SECRET": "your_access_secret"
}
  1. 監視対象とキーワードの設定

以下のような形式でテキストファイルを用意します。

  • users.txt: 監視するユーザー名をリスト化

user1
user2
user3
  • keywords.txt: 対象とするキーワード

#選手権
#トレンド
  • comments.txt: 投稿するコメント例

素晴らしいツイートですね! ありがとうございます!
これ最高!
  1. スクリプトの実行

以下のコマンドでスクリプトを実行します。

python your_script.py

注意事項

  • Twitter APIのレートリミットに注意してください。

  • 投稿の頻度や内容によりアカウントが制限される可能性があります。


このスクリプトを活用すれば、選手権や特定イベントに関連する投稿を効率的にモニタリングし、エンゲージメントを向上させることができます。詳細なサポートやカスタマイズについては、お気軽にお問い合わせください!

具体的なコードは有料部分になります。

ここから先は

4,828字

¥ 3,000 (数量限定:残り 2 / 3)

期間限定!Amazon Payで支払うと抽選で
Amazonギフトカード5,000円分が当たる

よろしければサポートお願いします! いただいたサポートはクリエイターとしての活動費やSaaSや各種プラットフォームの費用に使わせていただきます!