Overview
Message events are emitted when messages are received, updated, or encounter errors during sending. All message events provide a MessageResponse object containing the complete message data.
Events
new-message
Emitted when a new message is received.
The complete message object Unique identifier for the message
The text content of the message
Unix timestamp (milliseconds) when the message was created
Whether the message was sent by you
The sender/recipient handle information
Array of chats this message belongs to
Array of attachments included in the message
Error code (0 if no error)
Unix timestamp when the message was read
Unix timestamp when the message was delivered
GUID of the message this is replying to
iMessage effect ID (e.g., “com.apple.messages.effect.CKConfettiEffect”)
GUID of associated message (for reactions, etc.)
Type of association (e.g., “like”, “love”, “dislike”)
Basic Usage
With Filtering
Auto-Reply
import { SDK } from 'advanced-imessage' ;
const client = SDK ();
client . on ( 'new-message' , ( message ) => {
console . log ( `New message from ${ message . handle ?. id } : ${ message . text } ` );
});
await client . connect ();
updated-message
Emitted when an existing message is updated (e.g., edited, read status changed, delivered).
The updated message object with the same structure as new-message
Track Read Status
Track Edits
import { SDK } from 'advanced-imessage' ;
const client = SDK ();
client . on ( 'updated-message' , ( message ) => {
if ( message . dateRead && message . isFromMe ) {
console . log ( `Your message was read: ${ message . text } ` );
}
});
await client . connect ();
message-send-error
Emitted when a message fails to send.
The message object that failed to send Error code indicating the type of failure
Unique identifier for the failed message
The text content that failed to send
Temporary GUID that was assigned when sending
Handle Send Errors
Retry Failed Messages
import { SDK } from 'advanced-imessage' ;
const client = SDK ();
client . on ( 'message-send-error' , ( message ) => {
console . error ( `Failed to send message: ${ message . text } ` );
console . error ( `Error code: ${ message . error } ` );
console . error ( `Message GUID: ${ message . guid } ` );
});
await client . connect ();
Event Methods
on()
Register a listener that will be called every time the event is emitted.
client . on ( 'new-message' , ( message ) => {
console . log ( message );
});
once()
Register a listener that will be called only once, then automatically removed.
client . once ( 'new-message' , ( message ) => {
console . log ( 'First message received:' , message );
});
off()
Remove a specific listener from an event.
const handler = ( message ) => {
console . log ( message );
};
client . on ( 'new-message' , handler );
// Later, remove the listener
client . off ( 'new-message' , handler );
You must pass the exact same function reference to off() that was passed to on(). Anonymous functions cannot be removed.