Skip to main content

Quick Start

Get started with Advanced iMessage Kit SDK in just a few minutes. This guide walks you through creating a simple auto-reply bot that responds to incoming messages.

Step 1: Install the SDK

If you haven’t already, install the SDK:
npm install @photon-ai/advanced-imessage-kit

Step 2: Initialize the SDK

Create a new file and import the SDK:
index.ts
import { SDK } from '@photon-ai/advanced-imessage-kit';

// Initialize the SDK with your server configuration
const sdk = SDK({
  serverUrl: process.env.SERVER_URL ?? 'http://localhost:1234',
  apiKey: process.env.API_KEY,
  logLevel: 'info',
});
The SDK() function is a singleton that returns the same instance across your application. You can call it multiple times without creating duplicate connections.

Step 3: Listen for Events

Set up event listeners to handle incoming messages:
index.ts
// Listen for when the SDK is ready
sdk.on('ready', () => {
  console.log('Connected to iMessage server!');
});

// Listen for incoming messages
sdk.on('new-message', async (message) => {
  console.log(`Received: ${message.text || '(no text)'}`);
  console.log(`From: ${message.handle?.address || 'unknown'}`);
  
  // Skip messages from yourself
  if (message.isFromMe) {
    return;
  }
  
  // Get the chat to reply to
  const chat = message.chats?.[0];
  if (!chat) {
    return;
  }
  
  try {
    // Send a reply
    const response = await sdk.messages.sendMessage({
      chatGuid: chat.guid,
      message: `Hey! I received your message: "${message.text}"`,
    });
    
    console.log(`Replied: ${response.guid}`);
  } catch (error) {
    console.error('Failed to send reply:', error);
  }
});

// Handle errors
sdk.on('error', (error) => {
  console.error('SDK error:', error.message);
});

Step 4: Connect to the Server

Establish the connection to the iMessage server:
index.ts
await sdk.connect();

// Graceful shutdown
process.on('SIGINT', async () => {
  console.log('\nShutting down...');
  await sdk.close();
  process.exit(0);
});

Complete Example

Here’s the full auto-reply bot in one file:
auto-reply.ts
import { SDK } from '@photon-ai/advanced-imessage-kit';

async function main() {
  const sdk = SDK({
    serverUrl: process.env.SERVER_URL ?? 'http://localhost:1234',
    apiKey: process.env.API_KEY,
    logLevel: 'info',
  });

  sdk.on('ready', () => {
    console.log('Auto-reply bot is running!');
  });

  sdk.on('new-message', async (message) => {
    console.log(`\nReceived: ${message.text || '(no text)'}`);
    console.log(`From: ${message.handle?.address || 'unknown'}`);

    // Skip messages from self
    if (message.isFromMe) {
      return;
    }

    // Get chat guid from message
    const chat = message.chats?.[0];
    if (!chat) {
      return;
    }

    try {
      const originalText = message.text || message.attributedBody?.[0]?.string || '';
      const replyText = `Hey! ${originalText}`;

      const response = await sdk.messages.sendMessage({
        chatGuid: chat.guid,
        message: replyText,
      });

      console.log(`Replied: ${response.guid}`);
    } catch (error) {
      console.error('Failed to reply:', error);
    }
  });

  await sdk.connect();

  // Graceful shutdown
  process.on('SIGINT', async () => {
    console.log('\nShutting down...');
    await sdk.close();
    process.exit(0);
  });
}

main().catch(console.error);

Run Your Bot

Run the example:
node auto-reply.ts
Send a message to your iMessage account from another device or contact. You should see the bot respond automatically!

Understanding the Code

1

SDK Initialization

The SDK() function creates or returns the singleton instance with your server configuration. The serverUrl points to your Advanced iMessage Kit server, and apiKey authenticates your connection (if required).
2

Event Listeners

The SDK is event-driven. The ready event fires when connected and authenticated. The new-message event fires whenever a new message arrives in any chat.
3

Message Filtering

The message.isFromMe property identifies messages you sent, preventing the bot from replying to itself. The message.chats array contains the conversations this message belongs to.
4

Sending Messages

Use sdk.messages.sendMessage() to send a message. The chatGuid identifies the conversation, and messages are automatically queued to ensure delivery order.
5

Connection Management

Call await sdk.connect() to establish the WebSocket connection. The SDK handles automatic reconnection and message recovery if the connection drops.

Available Events

The SDK emits several events you can listen to:
  • ready - Connection established and authenticated
  • new-message - New message received
  • updated-message - Message status updated (delivered, read)
  • typing-indicator - Someone is typing
  • group-name-change - Group chat name changed
  • participant-added - Participant added to group
  • participant-removed - Participant removed from group
  • error - An error occurred
  • disconnect - Connection lost
See the Events API reference for the complete list of events and their payloads.

Next Steps

Configuration

Learn about all configuration options for the SDK

API Reference

Explore the complete API documentation

Examples

Browse more examples and use cases

Messages API

Deep dive into the Messages module

Build docs developers (and LLMs) love