Skip to content

Message Handling#

The bot automatically handles different types of WhatsApp messages and converts them into a format that OpenAI models can understand.

Supported message types#

  • Text: Plain text messages
  • Images: Photos with optional captions (supported on models with image processing capability)
  • Audio: Voice messages with automatic transcription
  • Video: Video messages with captions
  • Documents: File attachments
  • Polls: Messages with polls and poll updates
  • Location: Location sharing
  • Contacts: Contact sharing

Message handler registry#

The bot uses a registry of message handlers to handle different message types:

// Access the registry
const registry = bot.messageHandlers;

// Create a custom message handler
class CustomMessageHandler implements MessageHandler {
canHandle(message: Message): boolean {
return message.type === "custom-type";
}

async processMessage(message: Message): Promise<any> {
// Process the message
return "Processed content";
}
}

// Register a custom handler
bot.registerMessageHandler(new CustomMessageHandler());

// Replace an existing handler
bot.replaceHandler(TextMessageHandler, new CustomTextHandler());

Middleware#

The middleware system allows you to customize how messages are processed before being sent to the GPT and how responses are processed before being sent to the user.

Adding message middleware#

// Process messages before sending to GPT
bot.addMessageMiddleware(async (message, messageContent, messages, sessionData) => {
// Add user context to the conversation
if (message.type === "text" && message.chatId.endsWith("@c.us")) {
// Add user information from the database
const userInfo = await getUserInfo(message.chatId);

// Modify the current message content
const enhancedContent = `[User: ${userInfo.name}] ${messageContent}`;

return {
messageContent: enhancedContent,
messages
};
}

return {
messageContent,
messages
};
});

Adding middleware for responses#

// Process GPT responses before sending to the user
bot.addResponseMiddleware(async (response, messages, sessionData) => {
// Format or modify the response
const formattedResponse = response
.replace(/\bGPT\b/g, "Assistant")
.trim();

// You can also modify the messages that will be saved in the history
return {
response: formattedResponse,
messages
};
});