Advanced iMessage Kit

repository·main·Indexed 41 days ago

https://github.com/photon-hq/advanced-imessage-kit

A powerful TypeScript SDK for iMessage (v1.16.0) providing real-time messaging support. Features include sending text, replies, and attachments; managing group chats and contacts; scheduling messages; and creating interactive polls. It supports advanced capabilities such as message effects, text animations, and server monitoring via a remote iMessage server.

Tokens
12.9K
Snippets
42
Records
50
Agent score
51%

What's inside Advanced iMessage Kit

  1. Understand the chatGuid format

    main

    A chatGuid is the unique identifier for a conversation. It follows the format service;-;address.

    Common formats include:

    • iMessage DM: iMessage;-;+1234567890 or iMessage;-;email@example.com
    • SMS DM: SMS;-;+1234567890
    • Group chat: iMessage;+;chat123456789
    • Auto-detect: any;-;+1234567890 (The SDK will automatically detect the service type).
  2. Quick Start with Advanced iMessage Kit

    main

    To use the SDK, initialize it with the SDK function, provide a serverUrl, and call connect(). You can listen for real-time events like new-message using the .on() method and perform actions like sending messages via the messages namespace.

    import { SDK } from "@photon-ai/advanced-imessage-kit";
    
    const sdk = SDK({
      serverUrl: "http://localhost:1234",
    });
    
    await sdk.connect();
    
    sdk.on("new-message", (message) => {
      console.log("New message:", message.text);
    });
    
    await sdk.messages.sendMessage({
      chatGuid: "iMessage;-;+1234567890",
      message: "Hello World!",
    });
    
    await sdk.close();
  3. Best practices for SDK management

    main

    Resource Management

    Always perform a graceful shutdown by calling sdk.close() when the process terminates (e.g., on SIGINT) to prevent hanging connections.

    Message Deduplication

    To prevent memory leaks from the built-in message deduplication cache, periodically clear old messages using sdk.clearProcessedMessages(count). You can monitor the cache size with sdk.getProcessedMessageCount().

    Error Handling

    Wrap message sending in try/catch blocks. Errors often include a response.status field (e.g., 404 if a chatGuid is invalid).

    Auto-creating Chats

    When calling sdk.messages.sendMessage, if the chatGuid does not correspond to an existing chat, the SDK will automatically attempt to create the chat before sending the message.

    // Graceful shutdown
    process.on("SIGINT", async () => {
      await sdk.close();
      process.exit(0);
    });
    
    // Prevent memory leaks
    sdk.clearProcessedMessages(1000);
    
    // Error handling
    try {
      await sdk.messages.sendMessage({ chatGuid: "invalid", message: "hi" });
    } catch (error) {
      if (error.response?.status === 404) console.error("Chat not found");
    }
  4. Configure the Advanced iMessage Kit SDK

    main

    The SDK function accepts a ClientConfig object to customize behavior.

    • serverUrl: The URL of the remote iMessage server (defaults to http://localhost:1234).
    • apiKey: API key for server authentication.
    • logLevel: Controls verbosity. Options: "debug" | "info" | "warn" | "error" (defaults to "info").
    • logToFile: Boolean to enable/disable writing logs to ~/Library/Logs/AdvancedIMessageKit (defaults to true).
    interface ClientConfig {
      serverUrl?: string; // Server URL, defaults to "http://localhost:1234"
      apiKey?: string; // API key (if server requires authentication)
      logLevel?: "debug" | "info" | "warn" | "error"; // Log level, defaults to "info"
      logToFile?: boolean; // Enable writing logs to ~/Library/Logs/AdvancedIMessageKit (default true)
    }
  5. Connect to the iMessage server

    main

    After initializing the SDK, you must call connect() to establish a connection via Socket.IO. The SDK is designed to prioritize WebSocket transport to prevent message duplication issues common with polling.

    Once connected and authenticated, the SDK will emit a ready event. You should wait for this event before attempting to perform operations.

    const sdk = SDK();
    
    sdk.on('ready', () => {
      console.log('SDK is ready to use!');
    });
    
    await sdk.connect();
  6. Initialize the AdvancedIMessageKit SDK

    main

    You can interact with the iMessage SDK using the AdvancedIMessageKit class. It is recommended to use the getInstance() method to ensure a singleton instance is used throughout your application. You can pass a ClientConfig object to configure the server URL, API key, and logging behavior.

    Configuration Options (ClientConfig):

    • serverUrl: The URL of your iMessage server (defaults to http://localhost:1234).
    • apiKey: The API key for authentication. If omitted, the SDK operates in 'legacy mode'.
    • logLevel: The logging level (e.g., 'info', 'debug').
    • logToFile: Boolean indicating whether to log to a file (defaults to true).
    import { SDK } from '@photon-ai/advanced-imessage-kit';
    
    const sdk = SDK({
      serverUrl: 'https://your-imessage-server.com',
      apiKey: 'your-api-key',
      logLevel: 'info',
      logToFile: true
    });
  7. Explore iMessage Kit examples

    main

    The repository contains a comprehensive suite of examples categorized by functionality. Use these as templates for implementing specific iMessage features in your own applications.

    Getting Started

    • Listening: listen-simple.ts (formatted output) or listen-advanced.ts (full JSON).
    • Sending Messages: message-send.ts (text), message-attachment.ts (attachments), or message-audio.ts (audio).

    Message Operations

    • Management: message-reply.ts (reply), message-unsend.ts (unsend), message-edit.ts (edit), and message-reaction.ts (Tapbacks).
    • Advanced Messaging: message-effects.ts (effects), message-styled.ts (styles/animations), and message-search.ts (search).
    • History & Metadata: message-history.ts and message-destination-caller-id.ts.

    Chats & Groups

    • Chat Management: chat-fetch.ts (list chats), chat-participants.ts (group members), and chat-group.ts (group management).
    • UI/UX: message-typing.ts (typing indicators) and background-set.ts/background-remove.ts (chat backgrounds).

    Contacts & Services

    • Contacts: contact-list.ts (get contacts) and message-contact-card.ts (share cards).
    • Service Monitoring: service-check.ts (availability) and message-service-check.ts (service types).

    Attachments & Media

    • Media Handling: attachment-download.ts (downloading) and message-sticker.ts/message-reply-sticker.ts (stickers).

    Polls

    • Poll Lifecycle: poll-create.ts (create), poll-vote.ts (vote), poll-unvote.ts (unvote), and poll-add-option.ts (add options).

    Server & Advanced

    • System & Stats: server-info.ts (logs/info) and message-stats.ts (statistics).
    • Specialized Features: findmy-friends.ts, findmy-watch.ts, and auto-reply-hey.ts (auto-reply bot).
  8. Query handles and check service availability

    main

    A Handle is a messaging address (phone or email). Use sdk.handles to interact with them.

    • queryHandles(options): Search for handles. Options include address (filter), with: ["chats"] (include related data), offset, and limit.
    • getHandle(handleGuid): Fetches a specific handle.
    • getHandleAvailability(address, service): Checks if an address supports a specific service like "imessage" or "facetime". This is useful for deciding whether to send an iMessage or an SMS.
    • getHandleFocusStatus(handleGuid): Retrieves the current Focus status of a contact.
    const hasIMessage = await sdk.handles.getHandleAvailability("+1234567890", "imessage");
    const chatGuid = hasIMessage ? `iMessage;-;+1234567890` : `SMS;-;+1234567890`;
  9. Set and manage chat backgrounds

    main

    You can customize the background image for individual chats using sdk.chats.setBackground.

    • Set via file path: Pass { filePath: "/path/to/image.png" }.
    • Set via base64: Pass { fileData: "base64_string" }.
    • Get info: getBackground(chatGuid) returns an object containing hasBackground (boolean), backgroundId, and imageUrl.
    • Remove: removeBackground(chatGuid) clears the custom background.
    // Set a background image (using file path)
    await sdk.chats.setBackground("chat-guid", {
      filePath: "/path/to/image.png",
    });