You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何设置:特定Twitter账号首次使用Hashtag时发送邮件通知

How to Build a Twitter (X) Hashtag Tracker That Sends Email Alerts

Hey there! I get that you're not a full-time developer, so I'll keep this guide straightforward and actionable. Let's walk through building a tool that tracks specific Twitter accounts and emails you when any of them uses your target hashtag for the first time.

Step 1: Gather Your Tools & Credentials

First, you'll need a few things set up:

  • X (Twitter) Developer Account: Sign up via the X Developer Portal, create a new project, and grab your API Key, API Secret Key, Access Token, and Access Token Secret. These let your script fetch tweets from the accounts you want to track.
  • Email Service: We'll use Gmail for simplicity (other services work too). If you're using Gmail, either enable "Less secure app access" (quick but less safe) or create an App Password (safer, recommended if you have 2FA enabled—you can make one in your Google Account's Security settings).
  • Python: Install Python on your computer—it's free and has all the pre-built tools we need for this task.

Step 2: Plan the Core Logic

The biggest thing to avoid is spamming yourself with duplicate alerts. Here's the plan:

  1. Check the latest tweets from your target accounts at regular intervals.
  2. Keep a record of which accounts have already triggered an alert (so we don't email you twice for the same account).
  3. Send an email only when an account uses the hashtag for the very first time.

Step 3: Write the Script (Python Example)

Here's a simplified, commented script you can copy-paste. Save it as twitter_tracker.py:

import requests
import smtplib
import json
import time
from datetime import datetime

# --- CONFIGURE THESE VALUES FIRST ---
# X API Credentials
API_KEY = "your_api_key_here"
API_SECRET_KEY = "your_api_secret_key_here"
ACCESS_TOKEN = "your_access_token_here"
ACCESS_TOKEN_SECRET = "your_access_token_secret_here"

# Email Settings
SENDER_EMAIL = "your_email@gmail.com"
SENDER_PASSWORD = "your_app_password_or_email_password"
RECIPIENT_EMAIL = "your_alert_email@gmail.com"

# Tracking Settings
TARGET_ACCOUNTS = ["account1", "account2", "account3"]  # Replace with Twitter handles (no @)
TARGET_HASHTAG = "#YourHashtagHere"
CHECK_INTERVAL = 900  # Check every 15 minutes (in seconds)
TRACKED_ACCOUNTS_FILE = "tracked_accounts.json"
# --- END CONFIG ---

def load_tracked_accounts():
    """Load the list of accounts that already triggered an alert"""
    try:
        with open(TRACKED_ACCOUNTS_FILE, "r") as f:
            return json.load(f)
    except FileNotFoundError:
        return []

def save_tracked_accounts(tracked):
    """Save the updated list of tracked accounts"""
    with open(TRACKED_ACCOUNTS_FILE, "w") as f:
        json.dump(tracked, f)

def send_alert_email(account):
    """Send an email alert when an account uses the hashtag"""
    subject = f"Alert: @{account} used {TARGET_HASHTAG}!"
    body = f"Hey,\n\nThe account @{account} just posted with {TARGET_HASHTAG} for the first time.\n\nCheck their profile here: https://twitter.com/{account}\n\nTimestamp: {datetime.now()}"
    message = f"Subject: {subject}\n\n{body}"

    try:
        with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
            server.login(SENDER_EMAIL, SENDER_PASSWORD)
            server.sendmail(SENDER_EMAIL, RECIPIENT_EMAIL, message)
        print(f"Alert sent for @{account}")
    except Exception as e:
        print(f"Failed to send email: {str(e)}")

def check_tweets():
    """Check each target account's latest tweets for the hashtag"""
    tracked_accounts = load_tracked_accounts()
    auth = requests.auth.OAuth1(API_KEY, API_SECRET_KEY, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
    base_url = "https://api.twitter.com/1.1/statuses/user_timeline.json"

    for account in TARGET_ACCOUNTS:
        if account in tracked_accounts:
            continue  # Skip if we already alerted for this account

        # Fetch up to 20 latest tweets (excludes replies/retweets)
        params = {"screen_name": account, "count": 20, "exclude_replies": True, "include_rts": False}
        response = requests.get(base_url, auth=auth, params=params)
        
        if response.status_code != 200:
            print(f"Failed to fetch tweets for @{account}: {response.text}")
            continue

        tweets = response.json()
        for tweet in tweets:
            if TARGET_HASHTAG.lower() in tweet["text"].lower():
                # Found the hashtag—send alert and mark account as tracked
                send_alert_email(account)
                tracked_accounts.append(account)
                save_tracked_accounts(tracked_accounts)
                break  # No need to check older tweets for this account

if __name__ == "__main__":
    print(f"Starting tracker for {TARGET_HASHTAG} on accounts: {', '.join(TARGET_ACCOUNTS)}")
    while True:
        check_tweets()
        print(f"Next check in {CHECK_INTERVAL//60} minutes...")
        time.sleep(CHECK_INTERVAL)

Step 4: Run & Maintain the Script

  • Local Run: Open your terminal/command prompt, navigate to the folder where you saved the script, and run python twitter_tracker.py. Keep your computer on if you want it running non-stop.
  • Cloud Deployment (Optional): If you don't want to leave your computer on, deploy the script to a free cloud service like Heroku or AWS Lambda. For Heroku, create a Procfile to run the script as a background worker.

Key Tips to Avoid Headaches

  • API Rate Limits: The X API has request limits—this script checks 20 tweets per account every 15 minutes, which stays well within free tier limits.
  • Tracked Accounts File: The tracked_accounts.json file stores accounts that already triggered alerts. Don't delete it if you want to avoid duplicate emails.
  • Testing: Test with a friend's Twitter account first to make sure the email alert works before relying on it for your target accounts.

内容的提问来源于stack exchange,提问作者Robert Hansen

火山引擎 最新活动