API

Overview

The Chat API provides endpoints for message handling, chat history management, and bot interactions. Built on Next.js 15 and deployed on Vercel, it follows a serverless-first architecture with multi-agent support.

Endpoints

Send Message

POST /api/telegram/message

// Request
{
  chatId: number;
  text: string;
  keyboard?: InlineKeyboard;
  agentId?: string;
}

// Response
204 No Content
400 Bad Request
401 Unauthorized
403 Forbidden
429 Too Many Requests
500 Internal Server Error

Webhook Handler

POST /api/telegram/webhook/{botname}

// Request
{
  update_id: number;
  message?: Message;
  callback_query?: CallbackQuery;
  chat_member?: ChatMemberUpdated;
}

// Response
200 OK
400 Bad Request
401 Unauthorized
500 Internal Server Error

Data Types

Message Types

interface Message {
  message_id: number;
  from?: User;
  chat: Chat;
  date: number;
  text?: string;
  new_chat_members?: User[];
  reply_to_message?: Message;
}

interface Chat {
  id: number;
  type: 'private' | 'group' | 'supergroup';
  title?: string;
}

interface User {
  id: number;
  first_name: string;
  username?: string;
  is_bot: boolean;
}

interface ChatHistoryEntry {
  messageId: number;
  userId: number;
  userFirstName: string;
  username?: string;
  role: 'user' | 'assistant';
  content: string;
  timestamp: number;
  chatId: number;
  replyToMessageId?: number;
  agentId: string;
}

Keyboard Types

interface InlineKeyboard {
  inline_keyboard: Array<Array<{
    text: string;
    url?: string;
    callback_data?: string;
  }>>;
}

Database Operations

Store Message

async function storeMessage({
  messageId,
  chatId,
  userId,
  userFirstName,
  username,
  role,
  content,
  timestamp,
  replyToMessageId,
  agentId
}: ChatHistoryEntry): Promise<void>

Get Chat History

async function getRecentChatHistory(
  chatId: number,
  agentId: string,
  limit: number = 20
): Promise<ChatMessageData[]>

Update Chat History

async function updateChatHistory(
  chatId: number,
  entry: ChatHistoryEntry,
  agent: Agent
): Promise<void>

Error Handling

Error Types

interface APIError {
  status: number;
  message: string;
  details?: unknown;
}

interface ErrorResponse {
  error: string;
  message: string;
  statusCode: number;
}

Common Errors

  • 400 Bad Request: Invalid message format or parameters

  • 401 Unauthorized: Invalid bot token or missing authentication

  • 403 Forbidden: Insufficient permissions or unauthorized agent

  • 429 Too Many Requests: Rate limit exceeded (function or message)

  • 500 Internal Server Error: Server-side error or external service failure

Rate Limiting

Function Calls

const RATE_LIMIT = {
  window: 60000, // 1 minute
  max: 5 // requests per window
};

const FUNCTION_COOLDOWN = 20; // seconds

Message Sending

const MESSAGE_LIMIT = {
  window: 1000, // 1 second
  max: 1 // message per window
};

Security

Authentication

  • Bot token validation per agent

  • User permission checks

  • Group membership verification

  • Agent authorization

Input Validation

  • Message content sanitization

  • Parameter validation

  • Type checking

  • SQL injection prevention

Error Messages

const errorMessages = {
  rateLimited: '⏳ Please wait a moment before trying again.',
  contentPolicy: '❌ This content is not allowed.',
  invalidInput: '❌ Please check your input and try again.',
  serverError: '❌ Something went wrong. Please try again later.',
  unauthorized: '❌ You are not authorized to perform this action.',
  invalidToken: '❌ Invalid or expired bot token.',
  functionDisabled: '❌ This function is currently disabled.',
  modelError: '❌ Error generating response. Please try again.',
  databaseError: '❌ Database operation failed. Please try again.'
};

Best Practices

  1. API Usage

    • Implement proper error handling

    • Follow rate limiting guidelines

    • Use appropriate content types

    • Validate all inputs

    • Handle timeouts gracefully

  2. Security

    • Validate all inputs

    • Sanitize responses

    • Handle errors securely

    • Use HTTPS only

    • Implement proper authentication

    • Follow least privilege principle

  3. Performance

    • Cache when possible

    • Use appropriate indexes

    • Monitor response times

    • Implement retry logic

    • Handle concurrent requests

    • Use connection pooling

  4. Multi-Agent Support

    • Validate agent configurations

    • Handle agent-specific settings

    • Maintain separate chat histories

    • Implement proper error boundaries

    • Monitor agent performance

Last updated