Skip to main content

Twitter/X Integration

Reward your community for engaging with your brand on Twitter/X. Track mentions, and reward users with LTZ tokens automatically.

Overview

The Twitter Loyalty Bot is a Cloudflare Worker that polls the Twitter API for brand mentions and triggers rewards through the Loyalteez platform.

FeatureDescription
ServerlessRuns on Cloudflare Workers (free tier usually sufficient)
AutomaticPolls every 15 minutes via cron trigger
Smart DeduplicationHigh water mark + KV storage prevents duplicate rewards
Partner Portal IntegrationTwitter handle configured in Partner Portal (single source of truth)
ConfigurableSet reward amounts and limits in Partner Portal

Supported Event Types

Event TypeDescriptionAPI Tier Required
tweet_mentionUser mentions @YourBrandBasic (Free)
tweet_replyUser replies to your tweetBasic (Free)
tweet_quoteUser quote-tweets your contentBasic (Free)
tweet_hashtagUser uses brand hashtag in campaignBasic (Free)
tweet_thread_replyUser replies in brand's threadBasic (Free)
twitter_daily_engagementFirst engagement of the day (streak)Basic (Free)
tweet_likeUser likes your tweetPro ($100/mo)
tweet_retweetUser retweets your contentPro ($100/mo)
info

Likes and retweets require Twitter API Pro tier due to endpoint restrictions. Mentions, replies, quotes, and hashtags work with the free Basic tier.

Quote Tweets

Quote tweets are when users share your content with their own commentary. This is tracked automatically when users quote-tweet any of your brand's tweets.

  • Event Type: tweet_quote
  • Detection: Automatically searches for tweets that quote your brand's tweets using Twitter Search API
  • Reward: Configurable in Partner Portal (default: 75 LTZ)
  • Streak Integration: Automatically records engagement for streak tracking
  • API Requirement: Basic tier (Free) - no elevated access needed
  • Frequency: Polled every 15 minutes via cron trigger

How It Works:

The bot searches for tweets matching the pattern: url:twitter.com/{YourBrand}/status -from:{YourBrand}. This finds all tweets that quote your brand's tweets while excluding your own tweets.

Configuration Example:

In Partner Portal → Automation → Events, configure the tweet_quote event:

Event: tweet_quote
Reward: 75 LTZ
Cooldown: 24 hours (prevents spam)
Max Claims: 10 per user

Streak Integration:

Quote tweets automatically record engagement via the shared streak service. Users who quote-tweet daily build streaks, which multiply their rewards (e.g., 7-day streak = 1.5x multiplier).

Hashtag Campaigns

Track and reward users who use your brand hashtags in their tweets. Perfect for running promotional campaigns and brand awareness initiatives.

  • Event Type: tweet_hashtag
  • Configuration: Set up campaigns in Partner Portal with:
    • Hashtag (e.g., #LoyalteezLaunch)
    • Reward amount (e.g., 50 LTZ)
    • Start and end dates
    • Max claims per user
  • Streak Integration: Rewards include streak multipliers
  • API Requirement: Basic tier (Free)
  • Frequency: Polled every 15 minutes via cron trigger

How It Works:

  1. Create Campaign: Set up hashtag campaigns in Partner Portal
  2. Automatic Detection: Bot searches for tweets containing your hashtag
  3. Reward Distribution: Users are automatically rewarded when they use the hashtag
  4. Campaign Period: Only rewards tweets during the campaign's active period

Configuration Example:

In Partner Portal, create a hashtag campaign:

{
"hashtag": "#LoyalteezLaunch",
"reward": 100,
"start_date": "2024-01-01T00:00:00Z",
"end_date": "2024-01-31T23:59:59Z",
"max_claims_per_user": 5,
"exclude_brand_tweets": true
}

Campaign Features:

  • Time-Limited: Campaigns automatically activate and deactivate based on start/end dates
  • Deduplication: Each tweet is only rewarded once
  • User Limits: Set maximum claims per user to prevent abuse
  • Streak Integration: Hashtag tweets count toward daily engagement streaks

Use Cases:

  • Product launches (e.g., #NewProduct2024)
  • Event promotion (e.g., #Conference2024)
  • Brand awareness (e.g., #BrandName)
  • Contests and giveaways (e.g., #WinPrize)

Thread Participation

Reward users who participate in your tweet threads:

  • Event Type: tweet_thread_reply
  • Detection: Tracks replies to tweets in your conversation threads
  • Reward: Configurable in Partner Portal (default: 20 LTZ)
  • Streak Integration: Counts toward daily engagement streaks

Streak System

Users who engage daily on Twitter automatically build streaks, which multiply their rewards. The streak system uses the shared streak service API for cross-platform consistency.

How It Works:

  1. Passive Tracking: All engagement types (mentions, replies, quotes, hashtags, likes) count toward streaks
  2. Daily Engagement: Users who engage at least once per day (within 36-hour grace period) maintain their streak
  3. Multipliers: Streak multipliers apply to all Twitter rewards:
    • 3-day streak: 1.25x multiplier
    • 7-day streak: 1.5x multiplier
    • 14-day streak: 1.75x multiplier
    • 30-day streak: 2.0x multiplier
  4. Cross-Platform: Streaks are shared across all platforms (Discord, Telegram, Twitter, Farcaster, etc.)

Example:

User has a 7-day streak:

  • Base reward for mention: 50 LTZ
  • With 1.5x multiplier: 75 LTZ total

Streak Milestones:

Users can claim milestone bonuses at:

  • 7 days: +100 LTZ bonus
  • 30 days: +500 LTZ bonus
  • 100 days: +2000 LTZ bonus
  • 365 days: +10000 LTZ bonus

Shared Services Integration:

The Twitter bot automatically calls the shared streak service API:

// Automatically recorded for all engagement types
await fetch('https://services.loyalteez.app/streak/record-activity', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
brandId: env.BRAND_ID,
userIdentifier: `twitter_${userId}@loyalteez.app`,
platform: 'twitter',
streakType: 'daily'
})
});

Configuration:

Streak settings are configured per brand in Partner Portal → Automation → Streak Configuration:

  • Grace period (default: 36 hours)
  • Multiplier thresholds
  • Milestone rewards

Quick Start

Prerequisites

1. Clone the Repository

git clone https://github.com/Alpha4-Labs/twitter-loyalty-bot.git
cd twitter-loyalty-bot
npm install
White-Label Template

This is a reference implementation designed for developers to clone, customize, and deploy. Perfect for learning how Twitter loyalty bots work or building custom engagement tracking.

2. Get Twitter API Credentials

  1. Go to Twitter Developer Portal
  2. Create a new Project and App
  3. Navigate to Keys and Tokens
  4. Generate a Bearer Token

X Developer Platform X Developer Platform home page

API Access Levels X API access levels and versions

caution

Store your Bearer Token securely. Never commit it to git!

3. Create KV Namespace

npx wrangler kv:namespace create TWITTER_BOT_KV

Copy the id from the output.

4. Configure

cp wrangler.example.toml wrangler.toml

Edit wrangler.toml:

[[kv_namespaces]]
binding = "TWITTER_BOT_KV"
id = "your_kv_id_here"

[vars]
BRAND_ID = "0xYourWalletAddress"
LOYALTEEZ_API_URL = "https://api.loyalteez.app"
SUPABASE_URL = "https://xcyhefjogmgttegqhhyi.supabase.co"
note

The Twitter handle is NOT configured here. It's configured in Partner Portal and read from Supabase at runtime.

5. Set Secrets

# Twitter Bearer Token from step 2
npx wrangler secret put TWITTER_BEARER_TOKEN

# Supabase key (get from Loyalteez team)
npx wrangler secret put SUPABASE_PUBLISH_KEY

6. Configure Twitter Handle in Partner Portal

  1. Go to Partner PortalIntegrationsChannelsX (Twitter)
  2. Enter your brand's Twitter handle (without @)
  3. Click Save
important

This is the single source of truth for your Twitter handle. The worker reads this value from Supabase on each poll.

7. Deploy

npm run deploy

8. Configure Events in Partner Portal

  1. Go to Partner PortalAutomation
  2. Click Add Event
  3. Select Tweet Mention (or other Twitter events)
  4. Configure:
    • Reward Amount: e.g., 50 LTZ
    • Cooldown: e.g., 1 hour (prevents spam)
    • Max Claims: e.g., 10 per user
  5. Save Configuration

How It Works

┌─────────────────┐     ┌──────────────────┐     ┌─────────────────┐
│ Twitter API │────▶│ Cloudflare │────▶│ Loyalteez │
│ Search API │ │ Worker (Cron) │ │ Event Handler │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │ │
│ ▼ │
│ ┌──────────────────┐ │
│ │ KV Store │ │
│ │ (Deduplication) │ │
│ └──────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────┐ │
└──────────────▶│ Supabase │◀────────────┘
│ (Config) │
└──────────────────┘
  1. Cron Trigger: Worker runs every 15 minutes
  2. Load Config: Fetches Twitter handle from Supabase (Partner Portal)
  3. High Water Mark: Only fetches tweets newer than last processed
  4. Search Mentions: Queries Twitter for @YourBrand mentions
  5. Check KV: Skip already-processed tweets (belt-and-suspenders)
  6. Send Event: Calls Loyalteez Event Handler
  7. Store: Updates high water mark and records tweet ID

First Run Behavior

On first deployment (no high water mark), the bot will:

  • Process only the 3 most recent mentions (to avoid mass-processing old tweets)
  • Set a high water mark for future polls
  • Subsequent polls only fetch tweets newer than the high water mark

API Endpoints

The worker exposes several HTTP endpoints for management and testing:

EndpointMethodDescription
/GETService info and available endpoints
/healthGETHealth check with config status
/configGETDebug endpoint showing configuration
/triggerPOSTManually trigger a poll (for testing)
/resetPOSTReset high water mark (start fresh)

Example: Manual Trigger

curl -X POST https://your-worker.workers.dev/trigger

Example: Reset High Water Mark

curl -X POST https://your-worker.workers.dev/reset

This resets the "last processed tweet" marker, causing the next poll to be treated as a first run (processes 3 most recent tweets).

Example: Health Check

curl https://your-worker.workers.dev/health

Response:

{
"status": "ok",
"service": "twitter-loyalty-bot",
"brand_id": "0x...",
"twitter_handle": "YourBrand",
"timestamp": "2024-11-24T..."
}

User Identification

Twitter users are mapped to Loyalteez wallets using a synthetic email format:

Example: [email protected]

  • Deterministic: Same Twitter user always gets the same wallet
  • Cross-Platform: Can be linked with other social identities
  • Claiming: Users visit the Perk Marketplace and connect their Twitter to claim rewards

Partner Portal Configuration

Adding Your Twitter Handle

  1. Go to Partner PortalSettingsProfile
  2. Expand Authentication MethodsX (Twitter)
  3. Enter your brand's Twitter handle (without @)
  4. Click Save Profile

The worker reads this value from Supabase on each poll, so changes take effect immediately.

Creating Twitter Events

  1. Go to SettingsPoints DistributionEvents tab
  2. Click Add Event
  3. Select a Twitter event type:
    • Tweet Mention - When someone mentions your handle
    • Tweet Reply - When someone replies to you
    • Tweet Quote - When someone quote-tweets your content
    • Tweet Hashtag - When someone uses your campaign hashtag
    • Tweet Thread Reply - When someone replies in your thread
    • Tweet Like - When someone likes your tweet (Pro tier)
    • Tweet Retweet - When someone retweets you (Pro tier)
  4. Configure reward parameters
  5. Save

Configuring Hashtag Campaigns

  1. Go to SettingsIntegrationsX (Twitter)
  2. Scroll to Hashtag Campaigns
  3. Click Add Campaign
  4. Configure:
    • Hashtag: e.g., #LoyalteezLaunch (include the #)
    • Reward Multiplier: e.g., 2.0 (doubles base reward)
    • Start Date: Campaign start date
    • End Date: Campaign end date
    • Max Claims Per User: Limit per user (e.g., 10)
  5. Save Campaign

The bot automatically polls for tweets using your hashtags and rewards users with the configured multiplier.


Advanced Configuration

Change Poll Frequency

Edit wrangler.toml:

[triggers]
crons = ["*/5 * * * *"] # Every 5 minutes (uses more API quota)
warning

More frequent polling consumes Twitter API quota faster. Basic tier allows only 10 requests per 15-minute window.

Custom Domain

[[routes]]
pattern = "x-bot.yourdomain.com/*"
zone_name = "yourdomain.com"

Service Bindings (Internal)

For direct worker-to-worker communication (bypasses public HTTP):

[[services]]
binding = "EVENT_HANDLER"
service = "loyalteez-event-handler"

API Rate Limits

Twitter API Tiers

TierRequests/15minMonthly TweetsCostRecommended Polling
Free1100$0Daily
Basic1010,000$100/moEvery 15 min
Pro4501,000,000$5,000/moEvery 5 min
Free Tier Limitations

The free tier is extremely restrictive:

  • Only 1 request per 15 minutes
  • Only 100 tweets per month
  • Use daily polling (0 12 * * *) to conserve quota
  • Suitable for demos only - upgrade to Basic for production

Calculation

Each poll uses 1-2 API requests:

  • 1 request for user ID lookup (cached for 24 hours in KV)
  • 1 request for mention search

Free tier with daily polling:

  • 1 poll/day × 1 request = 1 request/day ✅
  • 100 tweets/month ÷ ~10 tweets/poll = ~10 polls before cap
  • Daily polling sustainable for demos with light engagement

Basic tier with 15-min polling:

  • 96 polls/day × 1 request = 96 requests/day ✅
  • 10,000 tweets/month = comfortable headroom
tip

User IDs are cached in KV for 24 hours, so repeated polls for the same handle only use 1 search request after the first poll.


Troubleshooting

"Twitter API secrets not configured"

npx wrangler secret put TWITTER_BEARER_TOKEN

"Twitter handle not configured in Partner Portal"

  1. Go to Partner Portal → Integrations → Channels → X (Twitter)
  2. Enter your handle (without @)
  3. Save
  4. Save

"No config found for brand"

  • Verify BRAND_ID in wrangler.toml matches your Partner Portal wallet
  • Ensure SUPABASE_PUBLISH_KEY secret is set correctly

"Rate limit exceeded" (429 error)

Twitter Basic tier has 10 requests per 15-minute window. If you hit this:

  • Wait 15 minutes for the rate limit to reset
  • Reduce poll frequency in wrangler.toml
  • Consider upgrading to Pro tier for high-engagement brands

No rewards appearing

  1. Verify BRAND_ID matches your Partner Portal wallet
  2. Confirm tweet_mention event exists in Partner Portal
  3. Check worker logs: npx wrangler tail
  4. Verify Twitter handle is set in Partner Portal

High water mark issues

If old tweets are being processed or new tweets are being skipped:

# Reset the high water mark
curl -X POST https://your-worker.workers.dev/reset

Next poll will be treated as first run (processes 3 most recent tweets).

View Real-Time Logs

npx wrangler tail

Security Best Practices

  1. Never commit secrets - Use npx wrangler secret put
  2. Use .gitignore - Excludes wrangler.toml, .env, node_modules
  3. Use example files - wrangler.example.toml for templates
  4. Rotate tokens - Regenerate Bearer Token if compromised
  5. Don't commit wrangler.toml - Contains your KV ID and brand-specific config

Example Use Cases

1. Brand Awareness Campaign

Reward users 100 LTZ for mentioning your brand:

Event: tweet_mention
Reward: 100 LTZ
Cooldown: 24 hours
Max Claims: 5 per user

2. Product Launch Buzz

Higher rewards for launch week engagement:

Event: tweet_mention
Reward: 250 LTZ
Cooldown: 1 hour
Max Total Claims: 1000 (first 1000 users)

3. Community Building

Daily engagement rewards:

Event: tweet_mention
Reward: 25 LTZ
Cooldown: 24 hours
Max Claims: Unlimited

Environment Variables Reference

VariableDescriptionWhere to Set
BRAND_IDYour Loyalteez wallet addresswrangler.toml
LOYALTEEZ_API_URLAPI endpointwrangler.toml
SUPABASE_URLSupabase instance URLwrangler.toml
TWITTER_BEARER_TOKENTwitter API Bearer TokenSecret
SUPABASE_PUBLISH_KEYSupabase public keySecret
note

Twitter handle is NOT an environment variable. It's configured in Partner Portal and read from Supabase at runtime.


Shared Services Integration

The Twitter bot integrates with Loyalteez Shared Services for streak tracking:

Streak Integration

All Twitter engagements automatically record activity for streak tracking:

// In polling/quotes.js, polling/hashtags.js, etc.
const streakResult = await recordTwitterEngagement(env, userId, 'engagement');

// Streak multiplier is included in reward metadata
metadata: {
streak_multiplier: streakResult.multiplier,
current_streak: streakResult.currentStreak
}

Benefits:

  • Users build streaks across all engagement types
  • Streak multipliers apply to all Twitter rewards
  • Cross-platform streak tracking (same user on Discord/Telegram/Twitter)

See Streak Service API Reference for details.

Resources

Support