· Nacho Coll · Guides  · 9 min basahin

X Alerts API: Programmatic Subscriptions at Notification History

Mag-build ng custom integrations sa ibabaw ng WALLAWHATS. Mag-add at mag-remove ng X subscriptions, mag-route ng alerts sa mga channel, mag-pull ng notification history — lahat via REST.

Mag-build ng custom integrations sa ibabaw ng WALLAWHATS. Mag-add at mag-remove ng X subscriptions, mag-route ng alerts sa mga channel, mag-pull ng notification history — lahat via REST.

Kapag naging mission-critical na ang real-time X (Twitter) alerts para sa business mo, umabot na sa limit ang manual dashboard management. Kung nag-build ka man ng customer intelligence dashboards, nag-automate ng brand monitoring workflows, o gumagawa ng custom notification systems para sa trading desks, kailangan mo ng programmatic control sa inyong X alert subscriptions.

May REST API ang WALLAWHATS na nagbibigay-daan sa’yo na mag-create, mag-manage, at mag-audit ng X alert subscriptions nang hindi na kailangan hawakan ang web interface. Mag-add o mag-remove ng mga monitored accounts, mag-pull ng notification history kasama ng delivery status, at i-integrate ang real-time X alerts sa kahit anong system na naka-HTTP.

API keys management page with create / revoke controls

Bakit Gamitin ang WALLAWHATS API?

Maganda ang dashboard para sa manual workflows, pero ang API access ay nag-unlock ng automation scenarios na lampas sa human management:

Customer Intelligence Platforms: Automatic na mag-subscribe sa mga newly identified na competitor executives, product leads, o industry analysts habang na-discover sila through research tools o CRM integrations.

Trading at Financial Workflows: Programmatically i-monitor ang regulatory accounts, CEO handles, o sector-specific journalists base sa portfolio changes o market events—walang manual subscription management.

Brand Monitoring at Scale: Mag-add o mag-remove ng brand mention tracking habang nag-launch ng mga bagong campaigns, nag-ship ng products, o nag-develop ng crisis situations.

Multi-Tenant SaaS Applications: White-label na real-time X monitoring para sa mga customers mo, na may programmatic subscription management sa likod.

Compliance at Audit Systems: Mag-pull ng complete notification history kasama ng delivery status para sa regulatory reporting, internal audit trails, o SLA monitoring.

API Authentication at Access

Lahat ng WALLAWHATS plan ay may kasamang API access na may scaling key quotas:

  • Free: 1 API key
  • Pro: 1 API key
  • Pro+: 2 API keys
  • Business: 5 API keys
  • Enterprise: 20 API keys

Gumagamit ng x-api-key header ang authentication (hindi Authorization: Bearer). I-generate ang keys mo sa API section ng dashboard, at i-treat sila na parang passwords—may full account privileges sila.

curl -H "x-api-key: your_api_key_here" \
     https://api.wallawhats.com/subscriptions

Core API Endpoints

May limang main resource groups ang WALLAWHATS API para sa building integrations:

Subscription Management

Mag-create ng bagong subscription:

POST /subscriptions
Content-Type: application/json
x-api-key: your_api_key_here

{
  "xUsername": "elonmusk"
}

I-list lahat ng subscriptions:

GET /subscriptions
x-api-key: your_api_key_here

Mag-remove ng subscription:

DELETE /subscriptions/elonmusk
x-api-key: your_api_key_here

Note na ang delete endpoint ay tumatanggap ng X handle bilang path parameter—hindi internal subscription ID.

Notification History at Audit

Mag-pull ng notification history kasama ng delivery status:

GET /notifications?from=1704067200000&to=1704153600000
x-api-key: your_api_key_here

Ang notifications endpoint ay nagre-return ng paginated results na ang bawat row ay kumakatawan sa isang alert na na-deliver sa isang channel. Ang status values ay kasama ang:

  • queued: Alert accepted, naghihintay ng delivery
  • sent: Na-dispatch sa channel provider
  • delivered: Confirmed na natanggap ng destination
  • read: Binuksan ng recipient (WhatsApp lang, kailangan enabled ang read receipts)
  • failed: Hindi successful ang delivery attempt

Channel Management

I-list ang mga configured channels:

GET /channels
x-api-key: your_api_key_here

Mag-add ng bagong channel:

POST /channels
Content-Type: application/json
x-api-key: your_api_key_here

{
  "type": "email",
  "destination": "alerts@yourcompany.com"
}

Mag-remove ng channel:

DELETE /channels/channel_id_here
x-api-key: your_api_key_here

Tweet Snapshots

I-access ang snapshot gallery:

GET /snapshots
x-api-key: your_api_key_here

Mag-delete ng specific snapshot:

DELETE /snapshots/tweet_id_here
x-api-key: your_api_key_here

Mag-build ng Integrations: Code Examples

Node.js Integration

Narito ang Node.js example na nag-add ng subscription at nag-poll para sa mga bagong notifications:

const axios = require('axios');

class WallaWhatsClient {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseURL = 'https://api.wallawhats.com';
  }

  async addSubscription(xUsername) {
    try {
      const response = await axios.post(
        `${this.baseURL}/subscriptions`,
        { xUsername },
        { headers: { 'x-api-key': this.apiKey } }
      );
      return response.data;
    } catch (error) {
      throw new Error(`Failed to add subscription: ${error.response?.data?.message || error.message}`);
    }
  }

  async getNotifications(from, to, lastKey = null) {
    try {
      let url = `${this.baseURL}/notifications?from=${from}&to=${to}`;
      if (lastKey) url += `&lastKey=${lastKey}`;
      
      const response = await axios.get(url, {
        headers: { 'x-api-key': this.apiKey }
      });
      return response.data;
    } catch (error) {
      throw new Error(`Failed to fetch notifications: ${error.response?.data?.message || error.message}`);
    }
  }

  async listSubscriptions() {
    try {
      const response = await axios.get(
        `${this.baseURL}/subscriptions`,
        { headers: { 'x-api-key': this.apiKey } }
      );
      return response.data;
    } catch (error) {
      throw new Error(`Failed to list subscriptions: ${error.response?.data?.message || error.message}`);
    }
  }
}

// Usage example
async function monitorCompetitor() {
  const client = new WallaWhatsClient('your_api_key_here');
  
  // Mag-add ng bagong subscription
  await client.addSubscription('vercel');
  console.log('Now monitoring @vercel');
  
  // I-check ang recent notifications
  const oneDayAgo = Date.now() - (24 * 60 * 60 * 1000);
  const notifications = await client.getNotifications(oneDayAgo, Date.now());
  
  console.log(`Found ${notifications.items.length} recent alerts`);
  notifications.items.forEach(notification => {
    console.log(`${notification.xUsername}: ${notification.status} at ${notification.timestamp}`);
  });
}

Python Integration

Para sa Python workflows, narito ang class na nag-handle ng subscription management at notification polling:

import requests
import time
from datetime import datetime, timedelta

class WallaWhatsAPI:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = 'https://api.wallawhats.com'
        self.headers = {'x-api-key': api_key}

    def add_subscription(self, x_username):
        """Mag-add ng bagong X account para i-monitor"""
        response = requests.post(
            f'{self.base_url}/subscriptions',
            json={'xUsername': x_username},
            headers=self.headers
        )
        response.raise_for_status()
        return response.json()

    def remove_subscription(self, x_username):
        """Mag-remove ng X account sa monitoring"""
        response = requests.delete(
            f'{self.base_url}/subscriptions/{x_username}',
            headers=self.headers
        )
        response.raise_for_status()
        return response.status_code == 200

    def get_notifications(self, from_ms, to_ms, last_key=None):
        """Mag-fetch ng notification history na may pagination"""
        params = {'from': from_ms, 'to': to_ms}
        if last_key:
            params['lastKey'] = last_key
            
        response = requests.get(
            f'{self.base_url}/notifications',
            params=params,
            headers=self.headers
        )
        response.raise_for_status()
        return response.json()

    def get_all_notifications(self, from_ms, to_ms):
        """Kunin lahat ng notifications sa isang time range, may pagination handling"""
        all_notifications = []
        last_key = None
        
        while True:
            batch = self.get_notifications(from_ms, to_ms, last_key)
            all_notifications.extend(batch['items'])
            
            if not batch.get('lastKey'):
                break
            last_key = batch['lastKey']
        
        return all_notifications

    def list_subscriptions(self):
        """Kunin lahat ng current subscriptions"""
        response = requests.get(
            f'{self.base_url}/subscriptions',
            headers=self.headers
        )
        response.raise_for_status()
        return response.json()

# Example: Daily audit report
def generate_daily_report():
    api = WallaWhatsAPI('your_api_key_here')
    
    # Kunin ang yesterday's notifications
    end_time = int(time.time() * 1000)
    start_time = end_time - (24 * 60 * 60 * 1000)
    
    notifications = api.get_all_notifications(start_time, end_time)
    
    # I-group by account at status
    report = {}
    for notification in notifications:
        account = notification['xUsername']
        status = notification['status']
        
        if account not in report:
            report[account] = {'total': 0, 'delivered': 0, 'failed': 0}
        
        report[account]['total'] += 1
        if status in ['delivered', 'read']:
            report[account]['delivered'] += 1
        elif status == 'failed':
            report[account]['failed'] += 1
    
    # I-print ang summary
    print(f"Daily Alert Report - {datetime.now().strftime('%Y-%m-%d')}")
    print("-" * 50)
    for account, stats in report.items():
        success_rate = (stats['delivered'] / stats['total']) * 100 if stats['total'] > 0 else 0
        print(f"@{account}: {stats['total']} alerts, {success_rate:.1f}% delivered")

Pag-unawa sa Channel Routing

Ginagamit ng WALLAWHATS ang global channel routing model—lahat ng alert mula sa bawat subscription ay nag-fan out sa lahat ng enabled at verified channels. Hindi mo ma-route ang specific accounts sa specific destinations via API (tulad ng “@elonmusk → WhatsApp, @vercel → email”).

Ang channel selection ay nangyayari sa account level sa Channels page. Kapag nag-add ka ng channel via API, nagiging available siya para sa lahat ng alerts kapag na-verify na. Kapag nag-remove ka ng channel, tumitigil siyang tumanggap ng alerts mula sa lahat ng subscriptions.

Ginagawa nitong simple ang automation habang pinapigil ang alert fragmentation. Hindi na kailangan ng integration code mo na mag-track ng per-subscription routing rules—i-manage lang kung aling accounts ang i-monitor at aling channels ang i-enable.

Rate Limits at Velocity Caps

May user-level velocity caps ang WALLAWHATS para mapigilan ang alert spam during high-activity periods:

  • Free: 2 alerts/hour
  • Pro: 5 alerts/hour
  • Pro+: 15 alerts/hour
  • Business: 30 alerts/hour
  • Enterprise: 100 alerts/hour

Kapag na-exceed ang velocity caps, ang additional tweets ay nabi-buffer sa digest messages at na-deliver every 15 minutes. Makikita ng API integration mo ang mga ito bilang separate notification records—isa para sa immediate alert, at isa para sa bawat digest batch.

Ang API mismo ay hindi nag-impose ng separate rate limits sa subscription management o notification queries. Pero iwasan ang pag-hammer sa endpoints na may unnecessary requests—i-cache ang subscription lists locally at i-batch efficiently ang notification queries.

Error Handling at Troubleshooting

Common API error patterns at kung paano i-handle:

Authentication failures (401):

  • I-verify na tama ang API key mo at hindi na-revoke
  • I-ensure na ginagamit mo ang x-api-key header, hindi Authorization

Subscription conflicts (409):

  • Account already monitored: Existing na ang subscription, i-treat as success
  • Account protected/private: Tinatanggihan ng WALLAWHATS ang mga ito by design

Rate limiting (429):

  • Mag-back off exponentially bago mag-retry
  • I-check kung malapit ka na sa plan limits sa monitored accounts

Channel verification issues:

  • Kailangan ng OTP verification ng mga bagong channels bago makatanggap ng alerts
  • Hindi gagana ang programmatically added channels hanggang ma-complete ng user ang verification

Pag-monitor at Pag-alert sa Inyong Integrations

Dahil nagiging critical infrastructure ang WALLAWHATS kapag na-integrate sa business workflows, i-monitor ang integration health:

Subscription Drift Detection:

// I-check kung ang expected subscriptions ay active pa rin
async function auditSubscriptions(expectedHandles) {
  const current = await client.listSubscriptions();
  const currentHandles = current.map(s => s.xUsername);
  
  const missing = expectedHandles.filter(h => !currentHandles.includes(h));
  if (missing.length > 0) {
    console.warn(`Missing subscriptions: ${missing.join(', ')}`);
  }
  
  return missing;
}

Delivery Success Rate Monitoring:

def check_delivery_health():
    # I-check ang last 6 hours
    end_time = int(time.time() * 1000)
    start_time = end_time - (6 * 60 * 60 * 1000)
    
    notifications = api.get_all_notifications(start_time, end_time)
    if not notifications:
        return None
    
    delivered = sum(1 for n in notifications if n['status'] in ['delivered', 'read'])
    total = len(notifications)
    success_rate = (delivered / total) * 100
    
    if success_rate < 95:
        # I-alert ang ops team mo
        print(f"WARNING: Delivery success rate dropped to {success_rate:.1f}%")
    
    return success_rate

Integration Patterns at Best Practices

Webhook-Style Processing: Kahit walang direct webhooks ang WALLAWHATS, pwede kang mag-poll sa notifications endpoint para sa mga bagong alerts at i-process sila in near-real-time:

async function pollForNewAlerts() {
  const lastCheck = localStorage.getItem('lastNotificationCheck') || Date.now() - 300000;
  const now = Date.now();
  
  const notifications = await client.getNotifications(lastCheck, now);
  
  for (const notification of notifications.items) {
    if (notification.status === 'delivered') {
      // I-process ang alert - i-send sa Slack, i-update ang database, etc.
      await processAlert(notification);
    }
  }
  
  localStorage.setItem('lastNotificationCheck', now);
}

// Mag-poll every 30 seconds
setInterval(pollForNewAlerts, 30000);

Conditional Subscription Management: Dynamically mag-add o mag-remove ng subscriptions base sa external triggers:

def update_competitor_monitoring(portfolio_companies):
    """I-update ang X monitoring base sa current portfolio"""
    current_subs = {s['xUsername'] for s in api.list_subscriptions()}
    
    # Accounts na dapat nating i-monitor
    target_accounts = set()
    for company in portfolio_companies:
        if company.get('ceo_twitter_handle'):
            target_accounts.add(company['ceo_twitter_handle'])
        if company.get('company_twitter_handle'):
            target_accounts.add(company['company_twitter_handle'])
    
    # Mag-add ng missing subscriptions
    for account in target_accounts - current_subs:
        try:
            api.add_subscription(account)
            print(f"Started monitoring @{account}")
        except Exception as e:
            print(f"Failed to add @{account}: {e}")
    
    # Mag-remove ng outdated subscriptions
    for account in current_subs - target_accounts:
        api.remove_subscription(account)
        print(f"Stopped monitoring @{account}")

Ang WALLAWHATS API ay nag-transform ng real-time X alerts mula sa manual dashboard tool tungo sa programmable infrastructure component. Kung nag-build ka man ng custom intelligence workflows, nag-automate ng brand monitoring, o gumagawa ng white-label notification services, ang API ay nagbibigay ng control at audit capabilities na kailangan para sa production integration.

Gusto mo bang i-expand ang monitoring mo beyond competitors? I-check ang guide namin sa monitoring crypto Twitter para sa market signals o alamin kung paano ginagamit ng mga journalists ang WALLAWHATS para sa real-time source monitoring.

Never miss an important post again. Mag-create ng free account — 1 WhatsApp number, real-time alerts, walang credit card required.

Bumalik sa Blog

Kaugnay na Artikulo

Tingnan Lahat ng Artikulo »