---
name: clawsim-agent
version: 2.0.0
author: Openclaw.ai
description: AI agent for automated virtual number purchasing and OTP extraction via 5sim.net API
triggers: ["sms verification", "otp automation", "virtual number", "5sim", "phone verification"]
---

# ClawSIM Agent Skill

AI agent that automates the complete lifecycle of SMS verification: buy virtual numbers, poll for incoming messages, extract OTP codes, and manage order completion via the 5sim.net API.

## Core Capabilities

### 1. Single Number Activation
- Purchase virtual number from 180+ countries
- Auto-poll status until SMS received (configurable interval: 1-10s)
- Extract OTP from response field `"code"` or regex parse `"text"`
- Auto-finish successful orders or auto-cancel on timeout
- Configurable timeout: 30-600 seconds

### 2. Auto-Retry Chain
- Define fallback country sequence (e.g., `philippines → india → russia → brazil`)
- If primary country times out, automatically retry with next in chain
- Prevents failed orders by cascading through available regions
- Each retry logged with detailed status

### 3. Bulk Activation Mode
- Concurrent processing: up to 10 parallel number purchases
- Batch configuration: 1-50 numbers per service
- Rate limit aware: respects 100 req/min API limit
- Progress tracking per number with success/fail stats
- Configurable purchase interval to avoid rate limits

### 4. Price Optimizer
- Real-time price comparison across all available countries
- Filter by minimum stock availability
- Sort by: lowest cost, highest stock, best success rate
- Auto-recommend optimal country/operator combination
- Visual price charts and comparison tables

### 5. History & Export
- Complete audit trail of all activations
- Filter by: date range, service, status (success/failed)
- Export formats: CSV, JSON
- Metrics: total orders, success rate, total spent, average wait time
- Configurable retention period

## API Integration

### Base Configuration
```yaml
api:
  base_url: https://5sim.net/v1
  auth: Bearer {API_TOKEN}
  rate_limit: 100/min
  timeout: 30s
```

### Authentication
All requests require JWT Bearer token in header:
```
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

Get API key from: https://5sim.net/settings/security

## Endpoints Used

### 1. Check Balance
```http
GET /v1/user/profile
Authorization: Bearer {token}
```

**Response:**
```json
{
  "balance": 24.80,
  "rating": 4
}
```

### 2. Get Available Countries
```http
GET /v1/guest/countries
```

**Response:**
```json
{
  "philippines": {
    "iso": {"ph": 1},
    "prefix": {"+63": 1},
    "text_en": "Philippines",
    "virtual4": {"activation": 1}
  }
}
```

### 3. Get Prices
```http
GET /v1/guest/prices?country={country}&product={service}
```

**Response:**
```json
{
  "philippines": {
    "google": {
      "virtual4": {
        "cost": 0.09,
        "count": 780
      }
    }
  }
}
```

### 4. Buy Activation Number
```http
GET /v1/user/buy/activation/{country}/{operator}/{product}
Authorization: Bearer {token}
```

**Parameters:**
- `country`: philippines, usa, russia, india, etc.
- `operator`: any, virtual1, virtual4, virtual18, etc.
- `product`: google, whatsapp, telegram, twitter, tiktok, etc.

**Response:**
```json
{
  "id": 11631253,
  "phone": "+63917xxxxxxx",
  "product": "google",
  "price": 0.09,
  "status": "PENDING",
  "expires": "2024-10-13T08:28:38Z",
  "country": "philippines"
}
```

### 5. Check Order Status (Polling)
```http
GET /v1/user/check/{order_id}
Authorization: Bearer {token}
```

**Response:**
```json
{
  "id": 11631253,
  "phone": "+63917xxxxxxx",
  "status": "RECEIVED",
  "sms": [
    {
      "created_at": "2024-10-13T08:20:38Z",
      "sender": "Google",
      "text": "Your verification code is 489271",
      "code": "489271"
    }
  ]
}
```

**Status Values:**
- `PENDING` - Waiting for SMS
- `RECEIVED` - SMS arrived, code available
- `TIMEOUT` - Exceeded time limit
- `CANCELED` - Cancelled by system/user
- `FINISHED` - Order completed successfully

### 6. Finish Order
```http
GET /v1/user/finish/{order_id}
Authorization: Bearer {token}
```

**Response:**
```json
{
  "status": "FINISHED"
}
```

### 7. Cancel Order
```http
GET /v1/user/cancel/{order_id}
Authorization: Bearer {token}
```

## Agent Workflow

### Standard Single Activation Flow

```mermaid
graph TD
    A[Start] --> B[Check Balance ≥ Cost]
    B -->|Insufficient| C[Error: Low Balance]
    B -->|OK| D[GET /buy/activation]
    D --> E[Receive Order ID + Phone]
    E --> F[Start Polling Loop]
    F --> G[GET /check/order_id]
    G --> H{Status?}
    H -->|PENDING| I[Wait 3s]
    I --> J{Timeout?}
    J -->|No| G
    J -->|Yes| K[Cancel Order]
    H -->|RECEIVED| L[Extract OTP]
    L --> M[GET /finish/order_id]
    M --> N[Log Success]
    H -->|TIMEOUT| K
    K --> O[Log Failed]
```

### Auto-Retry Chain Flow

```mermaid
graph TD
    A[Start with Country 1] --> B[Attempt Purchase]
    B --> C{Success?}
    C -->|Timeout| D{More Countries?}
    D -->|Yes| E[Try Next Country]
    E --> B
    D -->|No| F[All Retries Exhausted]
    C -->|SMS Received| G[Extract OTP & Finish]
```

### Bulk Mode Flow

```mermaid
graph TD
    A[Bulk Job Start] --> B[Create Queue of N Numbers]
    B --> C[Spawn 10 Concurrent Workers]
    C --> D[Each Worker: Buy + Poll + Extract]
    D --> E{All Complete?}
    E -->|No| D
    E -->|Yes| F[Generate Summary Report]
    F --> G[Export Results]
```

## Configuration Examples

### Agent Config (YAML)
```yaml
clawsim:
  version: 2.0.0
  
  # Polling behavior
  polling:
    interval_seconds: 3
    max_timeout_seconds: 120
    max_retries: 40  # 3s * 40 = 120s
  
  # Auto-retry chain
  retry_chain:
    enabled: true
    countries:
      - philippines
      - india
      - russia
      - brazil
    max_attempts: 4
  
  # Bulk mode
  bulk:
    max_concurrent: 10
    max_quantity: 50
    interval_between_purchases: 3  # seconds
  
  # Notifications
  notifications:
    telegram:
      enabled: true
      bot_token: "{TELEGRAM_BOT_TOKEN}"
      chat_id: "{CHAT_ID}"
    webhook:
      enabled: true
      url: "https://yourdomain.com/webhook/otp"
      method: POST
  
  # Export
  export:
    auto_export: true
    format: csv  # csv or json
    destination: ./exports/
  
  # Tier
  tier: free  # free or paid
```

### Environment Variables
```bash
FIVESIM_API_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
CLAWSIM_TIER=free
TELEGRAM_BOT_TOKEN=1234567890:ABC...
TELEGRAM_CHAT_ID=987654321
WEBHOOK_URL=https://yourdomain.com/webhook/otp
```

## OTP Extraction Logic

### Primary Method: Direct Field
```javascript
// Extract from "code" field (most reliable)
const otp = response.sms[0].code;
// Returns: "489271"
```

### Fallback Method: Regex Parse
```javascript
// Extract from "text" field if "code" is empty
const text = response.sms[0].text;
// "Your verification code is 489271"

const otpRegex = /\b\d{4,8}\b/;
const match = text.match(otpRegex);
const otp = match ? match[0] : null;
// Returns: "489271"
```

### Common OTP Patterns
- 4 digits: `\b\d{4}\b`
- 6 digits: `\b\d{6}\b`
- 4-8 digits: `\b\d{4,8}\b`
- With separator: `\d{3}[-\s]?\d{3}`

## Error Handling

### Common Error Codes

| Code | Message | Action |
|------|---------|--------|
| 400 | Bad Request | Check parameters format |
| 401 | Unauthorized | Verify API token |
| 402 | Insufficient Balance | Top up account |
| 404 | Order Not Found | Verify order ID |
| 429 | Rate Limit Exceeded | Wait 60s before retry |
| 500 | Server Error | Retry after delay |

### Timeout Strategy
```javascript
const TIMEOUT_CONFIG = {
  default: 120,        // seconds
  fastServices: 60,    // google, telegram
  slowServices: 180,   // banking, govt services
  minTimeout: 30,
  maxTimeout: 600
};
```

### Balance Check Before Purchase
```javascript
async function canPurchase(cost) {
  const profile = await fetch('/v1/user/profile');
  const balance = profile.balance;
  
  if (balance < cost) {
    throw new Error(`Insufficient balance: $${balance} < $${cost}`);
  }
  
  if (balance < cost + 0.50) {
    console.warn('Low balance warning: less than $0.50 remaining');
  }
  
  return true;
}
```

## CLI Usage Examples

### Basic Single Purchase
```bash
clawsim buy \
  --country philippines \
  --service google \
  --timeout 120
```

### With Auto-Retry
```bash
clawsim buy \
  --country philippines \
  --service whatsapp \
  --retry "philippines,india,russia" \
  --timeout 90
```

### Bulk Mode
```bash
clawsim bulk \
  --service telegram \
  --quantity 10 \
  --country auto \
  --concurrent 5 \
  --export results.csv
```

### Price Check
```bash
clawsim price \
  --service google \
  --min-stock 100 \
  --sort cost
```

### Export History
```bash
clawsim export \
  --format csv \
  --filter "status:success,date:today" \
  --output history-$(date +%Y%m%d).csv
```

## Integration Examples

### Node.js
```javascript
const ClawSIM = require('clawsim-agent');

const agent = new ClawSIM({
  apiToken: process.env.FIVESIM_API_TOKEN,
  tier: 'free'
});

// Single purchase
const result = await agent.buy({
  country: 'philippines',
  service: 'google',
  operator: 'any',
  timeout: 120,
  retry: ['philippines', 'india', 'russia']
});

console.log(`OTP: ${result.otp}`);
console.log(`Phone: ${result.phone}`);
console.log(`Cost: $${result.cost}`);
```

### Python
```python
from clawsim import ClawSIMAgent

agent = ClawSIMAgent(
    api_token=os.getenv('FIVESIM_API_TOKEN'),
    tier='free'
)

# Single purchase
result = agent.buy(
    country='philippines',
    service='google',
    operator='any',
    timeout=120,
    retry=['philippines', 'india', 'russia']
)

print(f"OTP: {result['otp']}")
print(f"Phone: {result['phone']}")
print(f"Cost: ${result['cost']}")
```

### cURL
```bash
# Step 1: Buy number
ORDER_ID=$(curl -s -X GET \
  "https://5sim.net/v1/user/buy/activation/philippines/any/google" \
  -H "Authorization: Bearer $API_TOKEN" \
  | jq -r '.id')

# Step 2: Poll for SMS
while true; do
  STATUS=$(curl -s -X GET \
    "https://5sim.net/v1/user/check/$ORDER_ID" \
    -H "Authorization: Bearer $API_TOKEN" \
    | jq -r '.status')
  
  if [ "$STATUS" = "RECEIVED" ]; then
    OTP=$(curl -s -X GET \
      "https://5sim.net/v1/user/check/$ORDER_ID" \
      -H "Authorization: Bearer $API_TOKEN" \
      | jq -r '.sms[0].code')
    echo "OTP: $OTP"
    break
  fi
  
  sleep 3
done

# Step 3: Finish order
curl -s -X GET \
  "https://5sim.net/v1/user/finish/$ORDER_ID" \
  -H "Authorization: Bearer $API_TOKEN"
```

## Webhook Integration

### Webhook Payload (POST)
```json
{
  "event": "otp_received",
  "timestamp": "2024-10-13T08:20:38Z",
  "order_id": 11631253,
  "phone": "+63917xxxxxxx",
  "country": "philippines",
  "service": "google",
  "otp": "489271",
  "cost": 0.09,
  "duration_seconds": 18,
  "status": "success"
}
```

### Webhook Receiver Example (Express.js)
```javascript
app.post('/webhook/otp', (req, res) => {
  const { otp, phone, service } = req.body;
  
  console.log(`[ClawSIM] OTP received for ${service}: ${otp}`);
  console.log(`Phone: ${phone}`);
  
  // Forward to your application
  await yourApp.handleOTP(otp, phone, service);
  
  res.status(200).json({ received: true });
});
```

## Telegram Bot Integration

### Bot Commands
```
/start - Initialize ClawSIM bot
/buy <service> <country> - Purchase number
/balance - Check 5sim balance
/history - View recent activations
/export - Export history CSV
```

### Bot Notifications
```
🔑 [ClawSIM] OTP Received
Service: Google
Phone: +63 917-xxx-xxxx
OTP: 489271
Cost: $0.09
Duration: 18s
```

## Performance Optimization

### Concurrent Request Limits
- Free tier: 3 concurrent purchases
- Paid tier: 10 concurrent purchases
- Rate limit: 100 requests/minute globally

### Caching Strategy
```javascript
// Cache country availability for 5 minutes
const countryCache = new Map();
const CACHE_TTL = 300000; // 5 min

async function getCountries() {
  const cached = countryCache.get('countries');
  if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
    return cached.data;
  }
  
  const data = await fetch('/v1/guest/countries').json();
  countryCache.set('countries', { data, timestamp: Date.now() });
  return data;
}
```

### Polling Optimization
```javascript
// Adaptive polling: start fast, slow down over time
const pollIntervals = [1, 2, 3, 5, 5, 5]; // seconds
let pollCount = 0;

async function pollOrder(orderId) {
  while (pollCount < 40) {
    const interval = pollIntervals[Math.min(pollCount, 5)] * 1000;
    await sleep(interval);
    
    const status = await checkOrder(orderId);
    if (status === 'RECEIVED') return status;
    
    pollCount++;
  }
  throw new Error('Polling timeout');
}
```

## Security Best Practices

1. **Never hardcode API tokens** - use environment variables
2. **Rotate tokens regularly** - every 90 days minimum
3. **Use HTTPS only** - all API calls over TLS
4. **Validate webhook signatures** - verify sender authenticity
5. **Rate limit protection** - implement exponential backoff
6. **Log sanitization** - never log full phone numbers in production
7. **Balance alerts** - notify when balance < $5
8. **IP whitelist** - restrict API access to known IPs (if available)

## Monitoring & Logging

### Metrics to Track
- Success rate: `successful_otps / total_purchases`
- Average wait time: `sum(durations) / count`
- Cost per OTP: `total_spent / successful_otps`
- Timeout rate: `timeouts / total_purchases`
- Most reliable countries: `success_rate by country`
- Peak usage times: `purchases by hour`

### Log Format
```
[2024-10-13T08:20:38Z] [INFO] [ClawSIM] Order #11631253 created
[2024-10-13T08:20:38Z] [INFO] [5sim] Bought +63917xxxxxxx for google ($0.09)
[2024-10-13T08:20:41Z] [INFO] [Poll] Attempt 1/40 - status: PENDING
[2024-10-13T08:20:44Z] [INFO] [Poll] Attempt 2/40 - status: PENDING
[2024-10-13T08:20:56Z] [OK] [OTP] Extracted: 489271
[2024-10-13T08:20:56Z] [OK] [5sim] Order #11631253 finished
[2024-10-13T08:20:56Z] [Webhook] Sent to https://yourdomain.com/webhook/otp
```

## Troubleshooting

### Issue: No SMS Received
**Solutions:**
- Increase timeout (try 180s for slow services)
- Try different operator (virtual4, virtual18, etc.)
- Switch to different country
- Check service status: some services block certain operators

### Issue: Order Canceled Immediately
**Solutions:**
- Insufficient balance - top up account
- Service temporarily unavailable - try different country
- Operator out of stock - use `any` operator

### Issue: Rate Limit Error (429)
**Solutions:**
- Implement request queue with delays
- Reduce concurrent bulk jobs
- Spread purchases over time (min 600ms between requests)

### Issue: Wrong OTP Extracted
**Solutions:**
- Adjust regex pattern for specific service
- Check `sms[0].sender` to verify source
- Some services send multiple codes - use latest

## Roadmap

### v2.1.0 (Q2 2025)
- [ ] SMS forwarding rules engine
- [ ] Number pool management (rent & reuse)
- [ ] GraphQL API support
- [ ] Real-time dashboard WebSocket updates

### v2.2.0 (Q3 2025)
- [ ] AI-powered OTP extraction (handle non-standard formats)
- [ ] Multi-tenant support (team accounts)
- [ ] Advanced analytics dashboard
- [ ] Rental number SMS inbox history

### v3.0.0 (Q4 2025)
- [ ] White-label licensing
- [ ] Custom carrier integrations
- [ ] Enterprise SLA contracts
- [ ] GDPR compliance tooling

## Support

- Documentation: https://docs.openclaw.ai/clawsim
- API Reference: https://5sim.net/docs
- Issues: https://github.com/openclaw/clawsim/issues
- Community: https://discord.gg/openclaw

## License

MIT License - see LICENSE.txt

---

**ClawSIM v2.0** — Openclaw.ai  
Powered by 5sim.net API
