Skip to main content
Unlimited Flexibility: Custom messages enable you to create any type of content beyond standard text, image, video, and file messages. Use structured JSON data to build polls, location sharing, interactive cards, booking widgets, and any specialized content your application requires.

Custom Message Overview

Custom messages provide unlimited flexibility for creating specialized content types using structured JSON data. Perfect for building interactive elements, complex data visualization, and application-specific functionality.

Flexible Structure

JSON-based data format
  • Free-form JSON object structure
  • Support for nested objects and arrays
  • Complex data type handling
  • Schema validation capabilities

Interactive Content

Rich user experiences
  • Surveys
  • Location sharing and maps
  • Booking and reservation widgets
  • Custom UI components

Implementation Guide

  • Basic Custom Messages
  • Interactive Content
  • Advanced Custom Messages
Simple custom data structuresCreate custom messages with structured JSON data for various use cases and interactive content.

Required Parameters

ParameterTypeDescription
subChannelIdStringTarget subchannel identifier for the custom message
dataObject/JSONFree-form JSON object containing your custom data structure

Optional Parameters

ParameterTypeDescription
tagsArray<String>Message categorization and filtering tags
parentIdStringParent message ID for threaded conversations
metadataObjectAdditional properties for extended functionality

Code Examples

// Basic custom message with simple data
let pollData: [String: Any] = [
    "type": "poll",
    "question": "What's your favorite programming language?",
    "options": [
        ["id": "swift", "text": "Swift", "votes": 0],
        ["id": "kotlin", "text": "Kotlin", "votes": 0],
        ["id": "typescript", "text": "TypeScript", "votes": 0],
        ["id": "python", "text": "Python", "votes": 0]
    ],
    "multiple_choice": false,
    "expires_at": "2024-01-20T23:59:59Z"
]

let options = AmityCustomMessageCreateOptions(
    subChannelId: "subChannel-123",
    data: pollData,
    tags: ["poll", "survey", "team"],
    parentId: nil
)

do {
    let message = try await messageRepository.createCustomMessage(options: options)
    print("Custom poll message sent: \(message.messageId)")
    
    // Access custom data
    if let customData = message.data as? [String: Any] {
        print("Poll question: \(customData["question"] ?? "")")
    }
} catch {
    print("Failed to send custom message: \(error)")
}
JSON Structure: Custom message data supports any valid JSON structure including nested objects, arrays, and primitive types. Design your data schema to match your UI requirements.

Custom Message Use Cases

Interactive voting and feedback collectionPoll Features
  • Single/Multiple Choice: Support for both single selection and multiple selection polls
  • Anonymous Voting: Optional anonymous voting for sensitive topics
  • Time-Limited Polls: Set expiration dates for time-sensitive decisions
  • Real-Time Results: Live vote counting and results display
Survey Capabilities
  • Multi-Question Surveys: Complex surveys with various question types
  • Conditional Logic: Show/hide questions based on previous answers
  • Progress Tracking: Visual progress indicators for long surveys
  • Response Analytics: Detailed analytics on survey responses
Question Types
  • Rating Scales: 1-5 or 1-10 rating questions
  • Open Text: Free-form text responses
  • Multiple Choice: Single or multiple selection options
  • Yes/No: Simple binary questions
Poll Data Structure
{
  "type": "poll",
  "question": "Which feature should we prioritize?",
  "options": [
    {"id": "feature_a", "text": "Feature A", "votes": 0},
    {"id": "feature_b", "text": "Feature B", "votes": 0}
  ],
  "settings": {
    "multiple_choice": false,
    "anonymous": true,
    "expires_at": "2024-01-20T23:59:59Z"
  }
}
Location sharing and event managementLocation Sharing
  • GPS Coordinates: Precise latitude/longitude coordinates
  • Address Information: Human-readable addresses and venue details
  • Interactive Maps: Embedded map views with directions
  • Location Metadata: Additional context like floor, room, or landmarks
Event Management
  • Event Details: Date, time, duration, and timezone information
  • Venue Information: Location details with capacity and amenities
  • Registration System: RSVP functionality with attendee limits
  • Calendar Integration: Export to calendar applications
Use Cases
  • Meeting Coordination: Share meeting locations and details
  • Event Announcements: Company events and social gatherings
  • Emergency Coordination: Share emergency meeting points
  • Field Work: Location updates for remote teams
Location Data Structure
{
  "type": "location",
  "coordinates": {"lat": 37.7749, "lng": -122.4194},
  "address": "123 Tech Street, San Francisco, CA",
  "venue_details": {
    "name": "Conference Center",
    "floor": "2nd Floor",
    "room": "Room A"
  }
}
Structured content displays and interactive widgetsRich Card Features
  • Visual Hierarchy: Title, subtitle, and body content organization
  • Media Integration: Images, videos, and file attachments
  • Action Buttons: Interactive buttons for user actions
  • Custom Styling: Colors, layouts, and branding options
Widget Types
  • Booking Widgets: Appointment and reservation systems
  • Product Showcases: Product information with pricing
  • Status Updates: Project status and progress indicators
  • Announcement Cards: Important updates with rich formatting
Interactive Elements
  • Buttons: Call-to-action buttons with custom actions
  • Forms: Embedded forms for data collection
  • Media Players: Audio and video playback controls
  • External Links: Deep links to other applications
Rich Card Structure
{
  "type": "rich_card",
  "title": "Q4 Performance Report",
  "content": {"summary": "...", "metrics": [...]},
  "actions": [
    {"type": "button", "label": "View Report", "action": "open_url"}
  ],
  "styling": {"color_scheme": "success"}
}
Enterprise workflow integration and automationApproval Workflows
  • Multi-Step Approvals: Complex approval chains with multiple approvers
  • Conditional Logic: Different approval paths based on criteria
  • Deadline Management: Time limits for approval decisions
  • Audit Trail: Complete history of approval actions
Task Management
  • Task Assignment: Assign tasks with due dates and priorities
  • Progress Tracking: Status updates and completion tracking
  • Dependencies: Task dependencies and blocking relationships
  • Resource Allocation: Resource and time estimates
Integration Features
  • External Systems: Connect to HR, CRM, and project management tools
  • API Webhooks: Trigger external actions based on message interactions
  • Data Synchronization: Keep external systems in sync
  • Reporting: Generate reports from workflow data
Approval Workflow Structure
{
  "type": "approval_request",
  "workflow_id": "expense_approval",
  "request_details": {...},
  "approval_chain": [
    {"step": 1, "approver": "manager", "status": "pending"}
  ],
  "metadata": {"department": "sales", "amount": 1250.00}
}

Best Practices

Designing effective custom message schemasSchema Design Principles
  • Consistent Structure: Use consistent field names and data types across similar message types
  • Extensibility: Design schemas that can be extended without breaking existing implementations
  • Validation: Include validation rules and constraints in your schema design
  • Documentation: Maintain clear documentation of your custom message schemas
Performance Considerations
  • Size Limits: Keep custom message data under reasonable size limits (recommended < 50KB)
  • Nesting Depth: Avoid excessive nesting that can impact parsing performance
  • Required vs Optional: Minimize required fields to reduce validation overhead
  • Indexing: Design data structure to support efficient searching and filtering
Version Management
  • Schema Versioning: Include version information in your custom message schema
  • Backward Compatibility: Ensure new versions are backward compatible when possible
  • Migration Strategies: Plan for data migration when schema changes are required
  • Deprecation: Properly deprecate old schema versions with clear timelines
Schema Design Example
interface CustomMessageSchema {
  version: string;
  type: string;
  required_fields: string[];
  optional_fields: string[];
  validation_rules: {
    [field: string]: {
      type: string;
      min_length?: number;
      max_length?: number;
      enum_values?: string[];
    };
  };
}
Creating intuitive custom message interfacesUI Design Guidelines
  • Visual Consistency: Maintain consistent visual design across all custom message types
  • Loading States: Provide appropriate loading indicators for interactive elements
  • Error Handling: Display clear error messages for failed interactions
  • Accessibility: Ensure custom messages are accessible to all users
Interaction Design
  • Touch Targets: Ensure interactive elements have appropriate touch target sizes
  • Feedback: Provide immediate feedback for user interactions
  • Progressive Disclosure: Show complex information progressively to avoid overwhelming users
  • Contextual Actions: Provide relevant actions based on user permissions and context
Mobile Optimization
  • Responsive Design: Ensure custom messages work well on all screen sizes
  • Touch Gestures: Support appropriate touch gestures for mobile interactions
  • Performance: Optimize rendering performance for complex custom messages
  • Network Awareness: Handle poor network conditions gracefully
Testing Strategy
  • Cross-Platform Testing: Test custom messages across all supported platforms
  • User Testing: Conduct user testing to validate custom message designs
  • Performance Testing: Test performance with large datasets and complex interactions
  • Accessibility Testing: Verify accessibility compliance and usability
Implementation Strategy: Start with simple custom message types like polls or location sharing, then progressively build more complex interactive content. Always validate your data schema and implement proper error handling for the best user experience.