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_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 work with the free Basic tier.


Quick Start​

Prerequisites​

1. Clone the Repository​

git clone https://github.com/Alpha4-Labs/x-loyalty-bot.git
cd x-loyalty-bot
npm install

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
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 Portal β†’ Settings β†’ Profile
  2. Expand Authentication Methods β†’ X (Twitter)
  3. Enter your brand's Twitter handle (without @)
  4. Click Save Profile
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 Portal β†’ Settings β†’ Points Distribution
  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 Portal β†’ Settings β†’ Profile
  2. Expand Authentication Methods β†’ X (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 Settings β†’ Points Distribution β†’ Events tab
  2. Click Add Event
  3. Select a Twitter event type:
    • Tweet Mention - When someone mentions your handle
    • Tweet Like - When someone likes your tweet
    • Tweet Retweet - When someone retweets you
    • Tweet Reply - When someone replies to you
  4. Configure reward parameters
  5. Save

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 β†’ Settings β†’ Profile
  2. Find Authentication Methods β†’ X (Twitter)
  3. Enter your handle (without @)
  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.


Resources​

Support​