Telnyx api

From tdimino/claude-code-minoan · View interactive version

Telnyx api is an AI agent skill from the GitHub repository tdimino/claude-code-minoan. Use this skill when working with Telnyx communication APIs for SMS/MMS messaging, voice calls, phone number management, messaging profiles, webhook integration, two-way SMS conversations, bulk sending, message scheduling, or production deployment of telephony features. v2.0 includes official Telnyx

How to use this skill

Skill file

Telnyx API - Comprehensive Communication Platform

v2.0 Enhancement: This skill now includes official Telnyx documentation, production-tested patterns from Twilio-Aldea (including Ed25519 signature validation with tweetnacl, provider-agnostic webhook handlers, and database idempotency), and comprehensive TypeScript examples for SMS/MMS messaging.

When to Use This Skill

Use this skill when working with Telnyx's communication APIs for:

This skill applies to building communication features in applications, setting up SMS notification systems, creating voice IVR systems, or integrating telephony capabilities.

Quick Reference

1. Send Simple SMS

const axios = require('axios');

async function sendSMS(to, from, text) {
  const response = await axios.post(
    'https://api.telnyx.com/v2/messages',
    { from, to, text },
    {
      headers: {
        'Authorization': `Bearer ${process.env.TELNYX_API_KEY}`,
        'Content-Type': 'application/json'
      }
    }
  );
  return response.data;
}

// Usage
await sendSMS('+14155552671', '+14155559999', 'Hello from Telnyx!');

2. Validate Phone Numbers (E.164 Format)

function validateE164(phoneNumber) {
  const e164Regex = /^\+[1-9]\d{1,14}$/;

  if (!e164Regex.test(phoneNumber)) {
    return {
      valid: false,
      error: 'Phone number must be in E.164 format (e.g., +14155552671)'
    };
  }

  return { valid: true };
}

// Normalize US phone numbers to E.164
function formatToE164(number) {
  let digits = number.replace(/\D/g, '');
  if (!digits.startsWith('1')) {
    digits = '1' + digits;
  }
  return '+' + digits;
}

3. Handle Incoming Messages (Webhook)

const express = require('express');
app.use(express.json());

app.post('/webhooks/telnyx', (req, res) => {
  const event = req.body.data;

  if (event.event_type === 'message.received') {
    const from = event.payload.from.phone_number;
    const text = event.payload.text;
    const to = event.payload.to[0].phone_number;

    console.log(`Received: "${text}" from ${from}`);

    // Auto-reply
    await sendSMS(from, to, 'Thanks for your message!');
  }

  res.status(200).send('OK');
});

4. Verify Webhook Signatures (Ed25519)

const nacl = require('tweetnacl');

function verifyWebhook(rawBody, signature, timestamp, publicKey) {
  // Check timestamp freshness (prevent replay attacks)
  const timestampMs = parseInt(timestamp);
  const now = Date.now();
  if (Math.abs(now - timestampMs) > 5 * 60 * 1000) {
    return false; // Reject if older than 5 minutes
  }

  // Construct signed payload
  const signedPayload = `${timestamp}|${rawBody}`;

  // Decode signature and public key from hex
  const signatureBytes = Buffer.from(signature, 'hex');
  const publicKeyBytes = Buffer.from(publicKey, 'hex');

  // Verify Ed25519 signature
  return nacl.sign.detached.verify(
    Buffer.from(signedPayload, 'utf8'),
    signatureBytes,
    publicKeyBytes
  );
}

// Usage in Express
app.post('/webhooks/telnyx', (req, res) => {
  const signature = req.headers['telnyx-signature-ed25519'];
  const timestamp = req.headers['telnyx-timestamp'];
  const rawBody = JSON.stringify(req.body);

  if (!verifyWebhook(rawBody, signature, timestamp, process.env.TELNYX_PUBLIC_KEY)) {
    return res.status(401).send('Invalid signature');
  }

  // Process webhook...
  res.status(200).send('OK');
});

5. Send with Error Handling and Retry

async function sendWithRetry(to, from, text, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await sendSMS(to, from, text);
    } catch (error) {
      if (error.response?.status >= 500 && attempt < maxRetries) {
        // Server error - retry with exponential backoff
        const delayMs = Math.pow(2, attempt) * 1000;
        console.log(`Retry ${attempt} in ${delayMs}ms...`);
        await new Promise(resolve => setTimeout(resolve, delayMs));
      } else {
        throw error;
      }
    }
  }
}

6. Bulk Sending with Rate Limiting

async function sendBulkSMS(recipients, from, text) {
  const delayMs = 100; // 10 messages/second
  const results = [];

  for (const recipient of recipients) {
    try {
      const result = await sendSMS(recipient, from, text);
      results.push({ success: true, to: recipient, id: result.data.id });
    } catch (error) {
      results.push({ success: false, to: recipient, error: error.message });
    }

    await new Promise(resolve => setTimeout(resolve, delayMs));
  }

  return results;
}

7. Idempotent Webhook Processing (Database)

// Using PostgreSQL with unique constraint
async function processWebhookIdempotent(event, client) {
  try {
    await client.query('BEGIN');

    // Try to insert event (will fail if duplicate due to unique constraint)
    await client.query(
      'INSERT INTO processed_webhooks (event_id, processed_at) VALUES ($1, NOW())',
      [event.id]
    );

    // Process event
    await handleEvent(event, client);

    await client.query('COMMIT');
  } catch (error) {
    await client.query('ROLLBACK');

    // If duplicate key error, event was already processed
    if (error.code === '23505') {
      console.log('Event already processed, skipping');
      return;
    }

    throw error;
  }
}

8. Two-Way Conversation State Machine

const conversations = new Map();

app.post('/webhooks/telnyx', async (req, res) => {
  const event = req.body.data;

  if (event.event_type === 'message.received') {
    const from = event.payload.from.phone_number;
    const to = event.payload.to[0].phone_number;
    const text = event.payload.text.toLowerCase();

    let state = conversations.get(from) || 'start';
    let reply;

    switch (state) {
      case 'start':
        reply = "Welcome! What's your name?";
        conversations.set(from, 'asked_name');
        break;

      case 'asked_name':
        reply = `Nice to meet you, ${text}! How can I help?`;
        conversations.set(from, 'helping');
        break;

      case 'helping':
        reply = 'Thanks! A human will respond shortly.';
        conversations.delete(from);
        break;
    }

    await sendSMS(from, to, reply);
  }

  res.status(200).send('OK');
});

9. Check 10DLC Campaign Status

#!/bin/bash
# Monitor campaign approval status

CAMPAIGN_ID="your-campaign-id"
API_KEY="your-api-key"

STATUS=$(curl -s "https://api.telnyx.com/v2/10dlc/campaign/${CAMPAIGN_ID}" \
  -H "Authorization: Bearer ${API_KEY}" \
  | jq -r '.campaignStatus')

echo "Campaign status: ${STATUS}"

# Status values:
# - TCR_ACCEPTED: Campaign Registry approved (not yet ready)
# - MNO_PENDING: Waiting for carrier approval
# - MNO_PROVISIONED: Fully approved and ready for production

10. Handle Common Errors

function handleTelnyxError(error) {
  if (!error.response) {
    return { type: 'NETWORK_ERROR', retriable: true };
  }

  const status = error.response.status;
  const errorData = error.response.data.errors?.[0];

  switch (status) {
    case 400:
    case 422:
      // Validation error - fix input
      return {
        type: 'VALIDATION_ERROR',
        message: errorData?.detail || 'Invalid request',
        retriable: false
      };

    case 401:
      // Check API key
      return { type: 'AUTH_ERROR', retriable: false };

    case 429:
      // Rate limit - wait and retry
      return {
        type: 'RATE_LIMIT',
        retriable: true,
        retryAfter: 60
      };

    case 500:
    case 502:
    case 503:
      // Server error - retry with backoff
      return { type: 'SERVER_ERROR', retriable: true };

    default:
      return { type: 'UNKNOWN_ERROR', retriable: false };
  }
}

Key Concepts

1. E.164 Phone Number Format

International phone number format: +[country code][number]

2. Messaging Profiles

A configuration container that groups numbers and defines webhook settings. Benefits:

3. Message Encoding and Segmentation

4. Webhook Events

Real-time notifications about message status:

5. 10DLC Campaign Approval Stages

Critical understanding for US messaging:

  1. TCR_ACCEPTED - Campaign Registry approved (can't send yet)
  2. MNO_PENDING - Waiting for carrier approval (1-3 days)
  3. MNO_PROVISIONED - Fully approved and ready (can associate numbers and send)

6. Authentication

All API requests require Bearer token authentication:

Authorization: Bearer YOUR_API_KEY

Store API keys in environment variables, never hardcode.

Reference Files

The references/ directory contains detailed documentation:

authentication.md

Complete guide to API key management and security:

messaging-api.md

Full Messaging API reference:

webhooks.md

Comprehensive webhook reference:

error-codes.md

Complete error reference and handling:

best-practices.md

Production deployment patterns:

number-management.md

Phone number operations:

10dlc.md

10DLC (10-Digit Long Code) registration and compliance:

Official Telnyx Documentation (NEW)

Complete official documentation extracted from developers.telnyx.com:

Production Patterns (NEW)

Real-world patterns from Twilio-Aldea production codebase:

Code Examples (NEW)

Production-ready TypeScript examples:

GitHub Repository (NEW)

`references/github/README.md`

Official Telnyx Node.js SDK README from GitHub (team-telnyx/telnyx-node, 62 stars)

`references/github/issues.md`

16 GitHub issues showing common problems and solutions:

`references/github/CHANGELOG.md`

Complete SDK version history with breaking changes and migrations

`references/github/releases.md`

81 GitHub releases with detailed SDK changelog

`references/github/file_structure.md`

Repository structure (2,129 files) showing SDK source code organization

Working with This Skill

For Beginners

Start Here:

  1. Use Quick Reference Example #1 (Send Simple SMS)
  2. Set up environment variables for API key
  3. Use Quick Reference Example #2 (Validate Phone Numbers)
  4. Test sending to your own phone number
  5. Set up Quick Reference Example #3 (Handle Incoming Messages)
  6. Test two-way messaging with ngrok

Key Concepts to Learn:

Reference Files:

Common Beginner Mistakes:

For Intermediate Users

Focus Areas:

  1. Implement Quick Reference Example #4 (Verify Webhook Signatures with Ed25519)
  2. Use Quick Reference Example #5 (Error Handling with Retry)
  3. Build conversation flows with Quick Reference Example #8 (State Machine)
  4. Create a messaging profile (see best-practices.md)
  5. Implement Quick Reference Example #7 (Database Idempotency)

Key Concepts to Master:

Reference Files:

Production Considerations:

For Advanced Users

Advanced Patterns:

  1. Implement bulk messaging from best-practices.md with queue system (Bull/Redis)
  2. Build provider-agnostic handlers (Pattern 2 in production-patterns.md)
  3. Set up comprehensive error logging (Pattern 7 in production-patterns.md)
  4. Implement debugger mode for cost-free testing (Pattern 6)
  5. Optimize message costs with encoding strategies
  6. Build IVR systems with Call Control API
  7. Set up number pools for high-volume messaging
  8. Implement comprehensive monitoring and alerting

Key Topics:

Reference Files:

Architecture Patterns:

API Essentials

Base URL

https://api.telnyx.com/v2

Authentication Header

Authorization: Bearer YOUR_API_KEY

Environment Variables

# .env file
TELNYX_API_KEY=KEY019A080F468AAFD4AF4F6888D7795244_xxx
TELNYX_PUBLIC_KEY=your_public_key_for_webhook_validation
TELNYX_MESSAGING_PROFILE_ID=abc85f64-5717-4562-b3fc-2c9600000000

Rate Limits

Common Response Structure

{
  "data": {
    "id": "message-uuid",
    "type": "SMS",
    "from": { "phone_number": "+18445550001" },
    "to": [{ "phone_number": "+18665550001", "status": "queued" }],
    "text": "Hello!",
    "cost": { "amount": "0.0051", "currency": "USD" }
  }
}

Quick Start Checklist

Navigation by Experience Level

Beginners (Getting Started)

  1. Start with Quick Reference Example #1 (Send Simple SMS)
  2. Review references/authentication.md for API setup
  3. Study references/messaging-api.md for message API basics
  4. Use Quick Reference Example #2 (Validate Phone Numbers)
  5. Set up webhooks with Quick Reference Example #3
  6. Test locally with ngrok

Intermediate (Building Features)

  1. Implement Ed25519 signature validation (Quick Reference #4)
  2. Study references/webhooks.md for advanced webhook patterns
  3. Use messaging profiles (see best-practices.md)
  4. Implement idempotency (Quick Reference #7)
  5. Build conversation state machines (Quick Reference #8)
  6. Review assets/examples/webhook-handler.ts for complete implementation

Advanced (Production Deployment)

  1. Build provider-agnostic handlers (production-patterns.md Pattern 2)
  2. Implement error logging and monitoring (production-patterns.md Pattern 7)
  3. Design multi-provider architectures with unified interfaces
  4. Optimize for production with all 8 patterns from production-patterns.md
  5. Study Twilio-Aldea patterns for SMS-based AI platform architecture
  6. Set up monitoring, alerting, and metrics collection

Key Enhancements in v2.0

Official Documentation Integration

Production Patterns

Code Examples

Data Sources

Version History

Additional Resources

Common Patterns

Pattern: Message with Tracking

const tracker = new Map();

async function sendTrackedMessage(to, from, text) {
  const response = await sendSMS(to, from, text);
  tracker.set(response.data.data.id, {
    to, from, text,
    status: 'queued',
    sentAt: new Date()
  });
  return response;
}

// In webhook handler
app.post('/webhooks/telnyx', (req, res) => {
  const event = req.body.data;
  if (event.event_type === 'message.delivered') {
    const msg = tracker.get(event.payload.id);
    if (msg) msg.status = 'delivered';
  }
  res.status(200).send('OK');
});

Pattern: Format to E.164

function formatToE164(number, defaultCountryCode = '1') {
  let digits = number.replace(/\D/g, '');
  if (!digits.startsWith(defaultCountryCode)) {
    digits = defaultCountryCode + digits;
  }
  return '+' + digits;
}

// Examples
formatToE164('415-555-2671');      // +14155552671
formatToE164('(415) 555-2671');    // +14155552671
formatToE164('+1 415-555-2671');   // +14155552671

Pattern: Optimize Message Cost

// Prefer GSM-7 encoding (cheaper, longer)
function optimizeForGSM7(text) {
  // Replace unicode quotes with GSM-7 quotes
  return text
    .replace(/[""]/g, '"')
    .replace(/['']/g, "'")
    .replace(/[—–]/g, '-')
    .replace(/…/g, '...');
}

Support and Troubleshooting

Getting Help

  1. Check error-codes.md for specific error messages
  2. Review best-practices.md for common patterns
  3. Visit https://status.telnyx.com/ for service status
  4. Contact support through Mission Control Portal
  5. Check 10dlc.md if having issues with US A2P messaging

Common Issues

Debugging Tips

// Enable request/response logging
axios.interceptors.request.use(request => {
  console.log('Request:', request.url, request.data);
  return request;
});

axios.interceptors.response.use(
  response => {
    console.log('Response:', response.status, response.data);
    return response;
  },
  error => {
    console.error('Error:', error.response?.data);
    return Promise.reject(error);
  }
);
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.