Guides

Twitter Sentiment Analysis in Python: From Data to Decisions

Build a Twitter sentiment analysis pipeline in Python: choose an X data source, clean social text, run VADER and review results with a reproducible example.

Gideon ReedGideon Reed19 min read

Twitter sentiment analysis classifies opinions in posts on X, formerly Twitter, so you can organize brand feedback, compare themes and investigate changes in conversation. A useful pipeline needs more than a positive/negative chart: it must explain which posts were included, which could not be scored and how the labels were checked.

Start with an approved data source, preserve the original text and run a small reproducible analysis before collecting more. This guide builds an English-language Python workflow that saves scored records, separates review cases and produces a count summary. An authored social-text example supplies concrete outputs—including a sarcasm error—so the interpretation is visible rather than hidden behind a code snippet.

You will build a bounded API collection option, model-specific text preparation, a VADER baseline and an optional Twitter-RoBERTa path. Network routing stays separate from data permissions and model accuracy.

Key takeaways

  • Define the brand, topic, language and time window before selecting a data source.
  • Preserve raw text; do not strip negation, emoji or punctuation indiscriminately.
  • Keep blank and unsupported-language records out of the sentiment denominator.
  • Use VADER as a lightweight baseline and evaluate contextual models on the same labeled records.
  • A proxy changes a network route; it does not remove X quotas, create access rights or improve sentiment labels.

What is Twitter sentiment analysis?

Twitter sentiment analysis applies natural-language processing to the opinions expressed in posts. A polarity model usually assigns positive, neutral or negative labels. That is different from detecting topics, emotions, sarcasm, stance or purchase intent. A negative sentence about delayed delivery can still contain praise for the product, making the target of the opinion important.

Useful sentiment analysis for Twitter answers a bounded question: “Among the English posts matching our delivery query this week, which complaint themes deserve review?” It does not establish what all customers believe. The search query, language coverage, repost policy and access path determine who enters the sample.

For brand monitoring, review changes in complaint volume and theme. For product teams, separate battery, usability, price and delivery feedback instead of averaging everything into one number. Market-related conversation can be analyzed as text, but a sentiment label is not a trading signal or evidence that sentiment caused a price move.

Sarcasm, quotations, slang, mixed languages and missing conversation context make this task difficult. “Great, another crash” contains a positive word while criticizing a failure. A larger model may interpret some context better, but no general model eliminates that ambiguity.

How to get Twitter data for sentiment analysis

Choose the source for the question, not simply for the easiest download. The three practical routes below have different coverage and permissions.

Route Freshness and coverage Cost and limits Best fit
Official X API Endpoint-specific recent or historical search Current access, credits and request limits Repeatable queries with recorded collection metadata
Licensed dataset or export Depends on collection dates, fields and license Dataset terms, redistribution and storage conditions Learning, evaluation or an approved retrospective study
Service explicitly authorized under current X terms Depends on the provider’s actual access and export Service charges, coverage gaps and platform conditions A defined, authorized project with traceable records; visible pages or browser cookies alone are not authorization
data-path

Start with the current API rather than an old subscription tutorial

As reviewed on November 24, 2026, X documents pay-per-usage credits rather than the older Free/Basic/Pro subscription comparison. Its published rate table lists post reads at $0.005 per resource; the console and applicable billing rules govern your project. For illustration, 1,000 billable post reads at that listed unit rate equal $5—not a complete project budget. Add any other charged resources, storage, processing and human review. X API pricing

Recent search covers the previous seven days; full-archive search is a separate endpoint with its own access requirements. Specify the publication window rather than collecting whatever happens to appear in a feed. Query operators such as lang:en and -is:retweet help define an English original-post sample. They do not make it representative of every user. X search documentation

Access and pricing checked: 2026-11-24. X also lists a 3-million-Post-read cap per monthly pay-per-usage billing cycle and resource deduplication within each UTC day, resetting at midnight. Deduplication is a soft guarantee with possible exceptions, not an unlimited free-retry allowance. Budget from actual console usage and recheck access, prices and policy quarterly.

Download a dataset with its context intact

When deciding how to download Twitter data for sentiment analysis, preserve more than the text. Keep the source, license, collection dates, query, language and any label definitions. An older benchmark can be useful for a learning exercise or comparison; it cannot answer a question about today’s product launch.

Some datasets distribute post IDs rather than complete text. Rehydration requires a permitted current access path, and unavailable or deleted records can change the sample. Do not silently replace missing posts or assume a downloaded archive grants permission to republish its contents.

The local workflow accepts a JSON list with id, text, created_at and lang. Timestamps must include a timezone and IDs must remain strings. An optional gold column contains your human reference label. Avoid exporting unnecessary account identifiers or personal details.

Set up a Twitter sentiment analysis Python project

Use an isolated Python environment. The baseline below was executed with Python 3.12.14 and vaderSentiment==3.3.2. The collector uses requests==2.34.2 and optional PySocks==1.7.1; the scorer itself does not need an X account or proxy. Keeping collection and scoring separate lets you rerun NLP without paying for the same acquisition again.

bashbash
python -m venv .venv
# Activate the environment using your operating system's normal command.
python -m pip install vaderSentiment==3.3.2 "requests[socks]==2.34.2"

Save the complete scripts below as twitter_sentiment.py and twitter_collect.py. Keep inputs, outputs and a restricted collection log in separate folders. Raw text can contain personal information even when a post is public; choose a retention period, access controls and deletion/update process before expanding collection.

How to do Twitter sentiment analysis in Python

1. Run the reproducible example first

bashbash
python twitter_sentiment.py --demo --out demo_results

The demo creates authored social-style text, not live X posts. It writes input.json, twitter_sentiment_results.csv and summary.json. These files give you a known input and a visible result before you adapt the schema to an authorized source.

For your own approved data, use:

bashbash
python twitter_sentiment.py --input tweets_raw.json --out project_results

The program validates required fields and timezone-aware timestamps. Repeated IDs count once, with the first record retained; it reports how many duplicates were removed. If your export contains edited posts or several captures of the same ID, reconcile those versions upstream rather than relying on input order as a historical policy.

2. Run a single-page collection smoke test

The collector requests at most ten records from recent search, saves raw rows and writes a collection manifest. Set X_BEARER_TOKEN through your environment or secret manager. Supply a start and end within the recent-search window; replace the example dates when rerunning later.

bashbash
python twitter_collect.py --query '"your brand" lang:en -is:retweet' --start 2026-11-23T00:00:00Z --end 2026-11-24T00:00:00Z --out collected
python twitter_sentiment.py --input collected/tweets_raw.json --out scored

The manifest records endpoint, query, times, returned rows and any next_token. One page is not full coverage. This supplied collector is a single-page smoke test, not a paginated downloader. To implement pagination, pass the returned token in the next permitted request, retain the same query/window, deduplicate IDs and stop at explicit page, row and spending ceilings. Save each completed page before advancing; preserve the last checkpoint on any failure. Use the current official recent-search parameter reference rather than assuming a token name. Empty results, denied access and rate limiting are different outcomes.

The collector stops on non-200 responses or API errors, disables redirects and uses bounded timeouts. It does not retry behind your back. A 429 requires checking reset guidance and reducing or pausing work; billing and rate limits are separate constraints. X rate-limit guidance

3. Clean for the model without erasing sentiment

Keep raw text alongside cleaned_text. For VADER, the script removes URLs, mentions and an initial repost prefix, then removes the hashtag marker while keeping its word. It preserves capitalization, punctuation, emoji and negation. Stemming and blanket stop-word removal are poor defaults when “not happy” must remain different from “happy.”

pythonpython
text = prepare("@shop Thank you! #love https://example.org/item")
# Thank you! love

An English label in the input controls eligibility. Non-English and missing-language rows go to review; the script does not invent a translation. URL-only text becomes a review case after cleaning, not a neutral opinion. Keep a separate rule or human review for images, quoted speech and posts whose meaning depends on a thread.

cleaning

4. Score VADER and retain the score meaning

VADER is a lexicon-and-rule baseline for social text. The implementation maps compound scores of at least 0.05 to positive, at most -0.05 to negative, and the interval between them to neutral. Its compound score is a normalized polarity score, not the probability that a customer is satisfied. VADER implementation and scoring

pythonpython
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
engine = SentimentIntensityAnalyzer()
compound = engine.polarity_scores("I am not happy with the delivery.")["compound"]
label = polarity(compound)

The full implementation saves the label, score, status and review reason per record. It computes shares over scored unique records only, with excluded records reported separately. Do not silently change that denominator when comparing days or brands.

5. Plan a separate English Twitter-RoBERTa environment

The optional branch uses cardiffnlp/twitter-roberta-base-sentiment-latest. Its model card identifies an English model and negative/neutral/positive classes, and demonstrates replacing usernames with @user and links with http. Use those conventions rather than passing VADER’s stripped text into every model. Cardiff NLP model card

The VADER installation above does not install this optional runtime. Treat the transformer branch as an integration reference requiring its own environment acceptance, rather than a baseline copy-and-run step. Install a compatible, currently patched PyTorch/Transformers environment, then record the model’s immutable commit from its files/history before running. The published repository currently supplies PyTorch .bin weights rather than safetensors; the branch disables custom remote code, requests weights-only loading and requires PyTorch 2.6 or newer. Use the latest security-patched compatible release, not the minimum version by default. The first model download requires disk space and network access.

bashbash
python twitter_sentiment.py --input tweets_raw.json --model roberta --revision 3216a57f2a0d9c45a2e6c20157c20c49fb4bf9c7 --out roberta_results

The command illustrates a separate model invocation and pins the repository commit resolved on November 24, 2026; retain the revision when comparing runs. Posts exceeding the branch’s 512-token limit go to review instead of silently losing their ending. Top-class model scores are not directly comparable with VADER compound scores, and neither is automatically calibrated confidence.

Selection question VADER baseline Twitter-RoBERTa candidate
Deployment Small lexicon and Python rules Model files and tensor runtime
Preprocessing Preserve polarity cues; remove hashtag marker Follow model-card mention/link placeholders
Context and sarcasm Inspect known failure examples Evaluate on the same contextual examples
Acceptance measure Per-class errors and local task quality Same labels, split and quality measures, plus measured runtime

The model card calls this an updated 2022 English model with pretraining text from 2018–2021. “latest” in the repository name does not mean 2026 training data. Include current slang, brand terms and domain drift in evaluation. The collector analyzes the API-returned text; it does not request note-post or conversation expansions, and a token-length check cannot detect upstream truncation.

Choose the model after evaluating your domain, not from a generic accuracy claim. Record package versions, model revision, batch settings, hardware and elapsed time if speed is part of the decision.

run-coverage

Results from the reproducible example

The executed VADER run processed 12 input rows, removed one repeated ID and retained 11 unique records. Nine English nonempty texts were scored; one URL/mention-only record and one Spanish record entered review.

Label Scored records Share of nine scored records
Positive 4 44.44%
Negative 3 33.33%
Neutral 2 22.22%
Review 2 Excluded from sentiment shares

The authored reference labels and predictions agree on eight of the nine scored examples. “Great, another crash. Just what I needed.” is labeled negative in the reference but predicted positive. This exposes a meaningful failure that a distribution chart alone would hide. The sample’s macro-F1 is 0.9048, computed across all three classes; nine deliberately constructed examples are a regression exercise, not an estimate of production accuracy.

The actual confusion matrix below uses rows as authored reference labels and columns as predictions:

Reference / prediction Negative Neutral Positive
Negative 3 0 1
Neutral 0 2 0
Positive 0 0 3

Run the supplied dependency-free SVG plotter on the saved summary:

bashbash
python twitter_plot.py demo_results/summary.json demo_results/distribution.svg
distribution

Keep the scored CSV for auditing and use the summary counts for a chart. A category bar chart needs the scored denominator and review count in its caption. For a time series, choose publication-time buckets in a fixed timezone, maintain the same query and show sample sizes. Do not interpret a bucket with a failed collection as zero complaints.

confusion

Check quality before making a business decision

Build a separate, representative labeled evaluation set from the permitted data for your domain. Define whether labels concern overall tone or the target brand/product; keep mixed opinions and uncertain context in a review policy. Have two reviewers label a subset independently and resolve disagreements before treating the labels as a reference.

Compare models on the same records. Report per-class precision, recall, macro-F1 and a confusion matrix, especially negative posts predicted positive. Separate training/tuning data from evaluation; near-duplicate posts and repeated authors or events can leak across a random split. A time-based or grouped split may better match deployment.

Turn labels into a bounded action. If a reviewed negative cluster concerns checkout failures, send product support a deduplicated theme summary with restricted evidence references. If the issue is shipping clarity, test revised delivery copy and evaluate your own support contacts or conversion outcomes. Do not equate a rise in negative share with a representative decline in customer satisfaction until coverage and labeling quality are stable.

sarcasm

Match the analysis target to an action

This script performs whole-text polarity, not aspect- or entity-level extraction. Use a separate reviewed coding layer when one post discusses several targets.

Task Query and target Output and reviewer action
Brand incident triage Fixed brand terms, event window, English originals Negative count/share plus coverage; review contextual evidence before escalation
Product feedback Product terms; quality, price and delivery coded separately Aspect-specific complaint examples; reviewer resolves mixed opinions and assigns an owner
Competitor theme comparison Comparable brand queries, language and window Theme/polarity with sample sizes; review query imbalance, never infer sales

No-code services can handle connectors, model calls and exports, but those conveniences do not settle collection permissions or label quality. This tutorial stays focused on auditable Python inputs and outputs.

Where Socks5.IO fits in the data pipeline

An ordinary approved API request does not inherently need a proxy. Use the direct route when it meets your requirements. When an authorized environment requires a specific outbound route, Socks5.IO’s rotating residential proxies can supply a configurable network layer; they do not supply an X token or expand endpoint permissions.

Generate the actual product’s host, port, authentication and supported protocol in Proxy Setup. Store the generated URL in RESEARCH_PROXY_URL through a secure environment mechanism. The collector explicitly applies that value to its Requests session and disables automatic environment-proxy inheritance. For Requests with PySocks, socks5h:// requests proxy-side hostname resolution; it is not a blanket anonymity or DNS-leak guarantee for other clients. Check proxies by country for product selection.

Before collection, verify the exit from the actual Python process with an approved diagnostic endpoint. Record requested versus observed country, client versions and a redacted exit identifier. A browser check cannot establish where a separate script connects, and a proxy’s country does not identify the location of the people posting. Keep geography based on permitted data fields, not your network exit.

For a paginated task, preserve continuity when the workflow requires it; do not rotate merely because a request was denied. Use the residential proxy setup guide for endpoint generation, and budget metered traffic, retries, data acquisition, inference and review separately. An explicit refusal, challenge or rate limit is a stop/check condition, not a cue to disguise the next request.

route-boundary

Choose and diagnose the route

Direct API access is the default. An approved corporate egress policy or a specific route investigation can justify a proxy; it is not an API entitlement. Compare required exit stability, continuity, permitted region, measured latency and billable traffic before choosing residential, fixed ISP or datacenter resources. Sticky sessions are temporary, not permanent assigned addresses.

The collector sets client.trust_env=False, so a VPN/browser setting or environment HTTP_PROXY value does not automatically configure that Requests client. Its explicit variable is RESEARCH_PROXY_URL. Percent-encode special characters in username/password as URL components; never log the full credential URL. Verify an approved diagnostic endpoint using the same Session and configuration before the API request; record time, observed country, redacted exit and failure stage. A browser exit does not establish the script route, and an exit country is not an author’s country.

Failure First check Action
ProxyError, SOCKS handshake, timeout Host, port, protocol, PySocks, auth and reachability Correct configuration; one bounded diagnostic before work
HTTP 407 where applicable Proxy credentials or allowlist Fix proxy authentication, not the X token
X API 401 Bearer token validity/loading Correct API authorization
403 or explicit refusal Response permissions, policy and access Stop and resolve access, not switch exits
429 Actual reset/Retry-After and quota Preserve checkpoint; wait under an approved retry policy
TLS/SSLError Certificate chain, time, approved corporate CA Fix trust/configuration; never disable verification
200 without data Query, window, errors and result metadata Distinguish empty results from partial failure; not zero negative sentiment

Record request identifiers, UTC time, failure stage and sanitized response details in restricted diagnostics. Total project cost equals data reads + metered proxy resources + inference + storage + human review; no provider price or success rate is assumed here.

error-layers

Complete Python scripts

Complete scorer and authored demo — save as twitter_sentiment.py
pythonpython
"""English sentiment scoring; --demo creates authored fixtures, never live posts."""
import argparse
import csv
import hashlib
import importlib.metadata
import json
import re
from collections import Counter
from datetime import datetime
from pathlib import Path
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer


def prepare(text, model='vader'):
    text = re.sub(r'^RT\s+@\w+:\s*', '', text)
    if model == 'roberta':
        # Follow the model card's whitespace-token username/link convention.
        return ' '.join('@user' if t.startswith('@') and len(t) > 1
                        else 'http' if t.startswith('http') else t
                        for t in text.split())
    text = re.sub(r'https?://\S+', '', text)
    text = re.sub(r'(?<!\w)@\w+', '', text)
    # VADER ignores hashtag-prefixed lexicon terms unless the marker is removed.
    text = re.sub(r'#(?=\w)', '', text)
    return ' '.join(text.split())


def polarity(compound):
    return 'positive' if compound >= .05 else 'negative' if compound <= -.05 else 'neutral'


def has_content(text):
    probe = re.sub(r'https?://\S+', '', text)
    probe = re.sub(r'(?<!\w)@\w+', '', probe)
    return bool(probe.strip())


def validate_record(row):
    if not isinstance(row, dict) or not isinstance(row.get('id'), str) or not row['id'].strip():
        raise ValueError('Each record requires a nonempty string id')
    if not isinstance(row.get('text'), str):
        raise ValueError('text must be a string')
    when = datetime.fromisoformat(row['created_at'].replace('Z', '+00:00'))
    if when.tzinfo is None or when.utcoffset() is None:
        raise ValueError('created_at must include timezone')
    return when


def analyze(records, model='vader', revision=None):
    if not isinstance(records, list):
        raise ValueError('Input must be a JSON list')
    engine = SentimentIntensityAnalyzer()
    transformer = None
    if model == 'roberta':
        if not revision or not re.fullmatch('[0-9a-f]{40}', revision):
            raise ValueError('Supply an immutable 40-character model commit via --revision')
        from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
        import torch
        if tuple(int(x) for x in torch.__version__.split('+')[0].split('.')[:2]) < (2, 6):
            raise ValueError('Use a current patched PyTorch release, at minimum 2.6 for weights-only loading')
        name = 'cardiffnlp/twitter-roberta-base-sentiment-latest'
        tokenizer = AutoTokenizer.from_pretrained(name, revision=revision, trust_remote_code=False)
        classifier = AutoModelForSequenceClassification.from_pretrained(
            name, revision=revision, use_safetensors=False, weights_only=True, trust_remote_code=False)
        transformer = pipeline('text-classification', model=classifier, tokenizer=tokenizer, device=-1)
    seen = set()
    output = []
    duplicates = 0
    for row in records:
        when = validate_record(row)
        if row['id'] in seen:
            duplicates += 1
            continue
        seen.add(row['id'])
        text = prepare(row['text'], model)
        item = dict(id=row['id'], created_at=when.isoformat(), text=row['text'],
                    cleaned_text=text, label='', score='', status='review', reason='',
                    gold=row.get('gold', ''))
        if row.get('lang') != 'en':
            item['reason'] = 'language_not_en'
        elif not has_content(row['text']) or not text:
            item['reason'] = 'empty_after_cleaning'
        else:
            if transformer:
                length = len(transformer.tokenizer(text, truncation=False)['input_ids'])
                if length > 512:
                    item['reason'] = 'over_512_tokens'
                    output.append(item)
                    continue
                result = transformer(text, truncation=False)[0]
                label, score = result['label'].lower(), float(result['score'])
                if label not in {'positive', 'negative', 'neutral'}:
                    raise ValueError('Unexpected model label')
            else:
                score = engine.polarity_scores(text)['compound']
                label = polarity(score)
            item.update(label=label, score=round(score, 6), status='scored')
        output.append(item)
    counts = Counter(r['label'] for r in output if r['status'] == 'scored')
    scored = sum(counts.values())
    paired = [r for r in output if r['status'] == 'scored' and r['gold'] in {'positive','negative','neutral'}]
    matrix = Counter((r['gold'], r['label']) for r in paired)
    f1 = {}
    metrics = {}
    for label in ['negative', 'neutral', 'positive']:
        tp = matrix[label, label]
        fp = sum(v for (g, p), v in matrix.items() if p == label and g != label)
        fn = sum(v for (g, p), v in matrix.items() if g == label and p != label)
        f1[label] = 2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0.0
        metrics[label] = dict(precision=tp/(tp+fp) if tp+fp else 0,
                              recall=tp/(tp+fn) if tp+fn else 0, f1=f1[label])
    summary = dict(input_rows=len(records), distinct_rows=len(output), duplicate_rows=duplicates,
                   scored_rows=scored, review_rows=len(output)-scored, model=model,
                   model_revision=revision, counts=dict(counts),
                   shares={k:round(v/scored, 4) for k,v in counts.items()} if scored else {},
                   labeled_scored_rows=len(paired), per_class_f1=f1 if paired else {},
                   per_class_metrics=metrics if paired else {},
                   confusion_matrix=[[matrix[g,p] for p in ['negative','neutral','positive']]
                                     for g in ['negative','neutral','positive']],
                   macro_f1=round(sum(f1.values())/3, 4) if paired else None,
                   confusion=[{'gold':g,'predicted':p,'count':v} for (g,p),v in sorted(matrix.items())],
                   scope='Results describe only the supplied records; scores are not calibrated confidence.')
    return output, summary


def demo():
    # Author-written social-style text, not X data or a representative benchmark.
    texts = [
        ('I love this update! Great work :)', 'positive', 'en'),
        ('This is awful. I hate the broken checkout.', 'negative', 'en'),
        ('The release is scheduled for Monday.', 'neutral', 'en'),
        ('I am not happy with the delivery.', 'negative', 'en'),
        ('Absolutely fantastic service!!!', 'positive', 'en'),
        ('The package arrived at 10 AM.', 'neutral', 'en'),
        ('Great, another crash. Just what I needed.', 'negative', 'en'),
        ('The camera is great but the battery is terrible.', 'negative', 'en'),
        ('@shop Thank you! #love https://example.org/item', 'positive', 'en'),
        ('https://example.org/ @shop', '', 'en'),
        ('Me encanta este producto.', '', 'es'),
    ]
    rows = [dict(id=f'example-{i+1}', text=t, gold=g, lang=lang,
                 created_at='2026-11-24T09:00:00Z') for i,(t,g,lang) in enumerate(texts)]
    return rows + [dict(rows[0])]


def main():
    p = argparse.ArgumentParser()
    p.add_argument('--input', type=Path)
    p.add_argument('--out', type=Path, required=True)
    p.add_argument('--demo', action='store_true')
    p.add_argument('--model', choices=['vader','roberta'], default='vader')
    p.add_argument('--revision')
    args = p.parse_args()
    if args.demo == bool(args.input):
        p.error('Choose exactly one of --demo and --input')
    rows = demo() if args.demo else json.loads(args.input.read_text(encoding='utf-8'))
    results, summary = analyze(rows, args.model, args.revision)
    args.out.mkdir(parents=True, exist_ok=True)
    raw = json.dumps(rows, ensure_ascii=False, indent=2)
    (args.out/'input.json').write_text(raw, encoding='utf-8')
    summary.update(input_sha256=hashlib.sha256(raw.encode()).hexdigest(),
                   dataset='authored_fixture' if args.demo else 'user_supplied',
                   vader_version=importlib.metadata.version('vaderSentiment'))
    with (args.out/'twitter_sentiment_results.csv').open('w',encoding='utf-8',newline='') as f:
        writer = csv.DictWriter(f, fieldnames=['id','created_at','text','cleaned_text','label','score','status','reason','gold'])
        writer.writeheader()
        writer.writerows(results)
    (args.out/'summary.json').write_text(json.dumps(summary,indent=2),encoding='utf-8')
    print(json.dumps(summary,indent=2))


if __name__ == '__main__':
    main()
One-page official API collector — save as twitter_collect.py
pythonpython
"""One bounded official recent-search request; no implicit retries or pagination."""
import argparse
import json
import os
from datetime import datetime, timezone
from pathlib import Path
import requests


def collect(query, start, end, session=None):
    dates = [datetime.fromisoformat(t.replace('Z','+00:00')) for t in (start,end)]
    now = datetime.now(timezone.utc)
    if any(t.tzinfo is None for t in dates) or not dates[0] < dates[1] <= now:
        raise ValueError('Use timezone-aware start < end <= now')
    if (now-dates[0]).total_seconds() > 7*86400:
        raise ValueError('Recent search start must be within the last seven days')
    token = os.environ.get('X_BEARER_TOKEN')
    if not token:
        raise ValueError('Set X_BEARER_TOKEN securely; do not paste it into code')
    client = session or requests.Session()
    client.trust_env = False
    proxy = os.environ.get('RESEARCH_PROXY_URL')
    if proxy:
        if not proxy.startswith(('socks5h://','http://','https://')):
            raise ValueError('Unsupported proxy scheme')
        client.proxies.update({'http':proxy,'https':proxy})
    r = client.get('https://api.x.com/2/tweets/search/recent',
                   headers={'Authorization':f'Bearer {token}'},
                   params={'query':query,'start_time':start,'end_time':end,'max_results':10,
                           'tweet.fields':'created_at,lang'},
                   timeout=(10,30), allow_redirects=False)
    if r.status_code != 200:
        raise RuntimeError(f'HTTP {r.status_code}; stop and inspect access/billing/rate limits. '
                           f'Reset={r.headers.get("x-rate-limit-reset", "unspecified")}')
    payload = r.json()
    if payload.get('errors'):
        raise RuntimeError('API returned errors; preserve a restricted diagnostic record')
    rows = payload.get('data', [])
    if not isinstance(rows, list):
        raise ValueError('Unexpected data shape')
    meta = dict(query=query,start=start,end=end,captured_at_utc=now.isoformat(),
                endpoint='/2/tweets/search/recent',max_results=10,
                returned_rows=len(rows),next_token=payload.get('meta',{}).get('next_token'),
                completeness='single_page_not_full_coverage',
                rate_remaining=r.headers.get('x-rate-limit-remaining'))
    return rows, meta


if __name__ == '__main__':
    p=argparse.ArgumentParser();p.add_argument('--query',required=True)
    p.add_argument('--start',required=True);p.add_argument('--end',required=True)
    p.add_argument('--out',type=Path,required=True);a=p.parse_args()
    rows,meta=collect(a.query,a.start,a.end)
    a.out.mkdir(parents=True,exist_ok=True)
    (a.out/'tweets_raw.json').write_text(json.dumps(rows,ensure_ascii=False,indent=2),encoding='utf-8')
    (a.out/'collection.json').write_text(json.dumps(meta,indent=2),encoding='utf-8')
    print(f'Saved {len(rows)} rows; one page only. See collection.json for coverage.')

Conclusion

Build the pipeline around an approved source, preserved text, explicit scoring rules and reviewed outputs. The reproducible example shows both useful labels and a sarcasm failure, while the collector keeps coverage and cost visible. For an authorized routing requirement, generate a Socks5.IO endpoint and verify the Python client’s exit before collection. Scale only after the data sample, model quality and review workflow support the decision you intend to make.

FAQs

Permission depends on the access path, platform terms, dataset license, personal-data handling and intended use. Prefer an approved API, licensed export or explicitly authorized collection workflow. Public visibility alone does not grant unrestricted collection or redistribution rights. Follow the X Developer Policy, retain only needed fields and implement applicable deletion requirements. For consequential commercial or regulated use, assess the jurisdiction and contract rather than relying on a general tutorial.

Latest articles

Global proxy network illustration

Plug into the global proxy network — every connection faster and more stable

Start for Free