messages

package
v2.0.17 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 4, 2026 License: MPL-2.0 Imports: 12 Imported by: 1

README

Messages

The Messages module provides functionality to interact with the Webex Messages API, allowing you to send, retrieve, update, and delete messages in Webex spaces, as well as listen for new messages in real-time.

Overview

Messages in Webex are the primary way users communicate within spaces (rooms). This module allows you to:

  1. Send messages to spaces or directly to other users
  2. Retrieve messages by ID
  3. List messages in a space
  4. Update existing messages
  5. Delete messages
  6. Listen for new messages in real-time (Retrieves conversation messages as an encrypted string)

Installation

This module is part of the Webex Go SDK. To use it, import the SDK and the messages package:

import (
    "github.com/WebexCommunity/webex-go-sdk/v2"
    "github.com/WebexCommunity/webex-go-sdk/v2/messages"
)

Usage

Initializing the Client
client, err := webex.NewClient(accessToken, nil)
if err != nil {
    log.Fatalf("Error creating client: %v", err)
}

// Access the messages client
messagesClient := client.Messages()
Sending a Message

To send a message to a space:

message := &messages.Message{
    RoomID: "ROOM_ID",
    Text:   "Hello, World!",
}

createdMessage, err := client.Messages().Create(message)
if err != nil {
    log.Fatalf("Error sending message: %v", err)
}

fmt.Printf("Message sent with ID: %s\n", createdMessage.ID)

To send a direct message to a person (by ID or email):

// By person ID
message := &messages.Message{
    ToPersonID: "PERSON_ID",
    Text:       "Hello, this is a direct message!",
}

// Or by email
message := &messages.Message{
    ToPersonEmail: "person@example.com",
    Text:          "Hello, this is a direct message!",
}
Sending a Message with Markdown

You can use Markdown formatting for richer text formatting:

message := &messages.Message{
    RoomID:   "ROOM_ID",
    Markdown: "# Hello\n**This** is a _formatted_ message.",
}
Sending a Message with Attachments

You can include attachments like adaptive cards:

message := &messages.Message{
    RoomID: "ROOM_ID",
    Text:   "This is a fallback text for clients that don't support cards",
    Attachments: []messages.Attachment{
        {
            ContentType: "application/vnd.microsoft.card.adaptive",
            Content: map[string]interface{}{
                "type":    "AdaptiveCard",
                "version": "1.0",
                "body": []map[string]interface{}{
                    {
                        "type": "TextBlock",
                        "text": "Card title",
                        "size": "large",
                    },
                    {
                        "type": "TextBlock",
                        "text": "Card content",
                    },
                },
                "actions": []map[string]interface{}{
                    {
                        "type":  "Action.Submit",
                        "title": "Submit",
                    },
                },
            },
        },
    },
}
Retrieving a Message

To get details about a specific message:

message, err := client.Messages().Get("MESSAGE_ID")
if err != nil {
    log.Fatalf("Error getting message: %v", err)
}

fmt.Printf("Message text: %s\n", message.Text)
fmt.Printf("Sent by: %s\n", message.PersonEmail)
fmt.Printf("Created at: %v\n", message.Created)
Listing Messages in a Space

To retrieve messages from a space:

options := &messages.ListOptions{
    RoomID: "ROOM_ID",
    Max:    10, // Optional: limit to 10 messages
}

page, err := client.Messages().List(options)
if err != nil {
    log.Fatalf("Error listing messages: %v", err)
}

for _, message := range page.Items {
    fmt.Printf("Message from %s: %s\n", message.PersonEmail, message.Text)
}

You can use additional options for more specific queries:

options := &messages.ListOptions{
    RoomID:          "ROOM_ID",
    MentionedPeople: "me", // Messages that mention you
    BeforeMessage:   "MESSAGE_ID", // Messages before a specific message
    ThreadID:        "THREAD_ID", // Messages in a specific thread
}
Updating a Message

To update an existing message:

updatedMessage := &messages.Message{
    Text: "Updated text for the message",
}

result, err := client.Messages().Update("MESSAGE_ID", updatedMessage)
if err != nil {
    log.Fatalf("Error updating message: %v", err)
}

fmt.Printf("Message updated: %s\n", result.Text)
Deleting a Message

To delete a message:

err = client.Messages().Delete("MESSAGE_ID")
if err != nil {
    log.Fatalf("Error deleting message: %v", err)
}

fmt.Println("Message deleted successfully")
Real-time Message Listening

One of the powerful features of this module is the ability to listen for new messages in real-time:

// Define a message handler function
messageHandler := func(message *messages.Message) {
    fmt.Printf("New message from %s: %s\n", message.PersonEmail, message.Text)
    
    // You can respond to messages here
    if message.Text == "Hello bot" {
        response := &messages.Message{
            RoomID: message.RoomID,
            Text:   "Hello human!",
        }
        client.Messages().Create(response)
    }
}

// Start listening for messages
err = client.Messages().Listen(messageHandler)
if err != nil {
    log.Fatalf("Error starting message listener: %v", err)
}

// When you're done listening (e.g., when your program is shutting down)
client.Messages().StopListening()

Data Structures

Message Structure

The Message structure contains the following fields:

Field Type Description
ID string Unique identifier for the message
RoomID string ID of the room where the message was sent
ParentID string ID of the parent message (for threaded replies)
ToPersonID string ID of the recipient (for direct messages)
ToPersonEmail string Email of the recipient (for direct messages)
Text string Plain text content of the message
Markdown string Markdown-formatted content of the message
HTML string HTML-formatted content of the message
Files []string Array of file URLs attached to the message
PersonID string ID of the person who sent the message
PersonEmail string Email of the person who sent the message
Created *time.Time Timestamp when the message was created
Updated *time.Time Timestamp when the message was last updated
MentionedPeople []string Array of person IDs mentioned in the message
MentionedGroups []string Array of group names mentioned in the message
Attachments []Attachment Array of attachments (like adaptive cards)
ListOptions

When listing messages, you can use the following filter options:

Option Type Description
RoomID string Filter messages by room ID (required)
MentionedPeople string Filter messages where specific people are mentioned
Before string Filter messages before a specific date (ISO8601)
BeforeMessage string Filter messages before a specific message by ID
Max int Maximum number of messages to return
ThreadID string Filter messages within a specific thread

Complete Example

Here's a complete example that demonstrates the major features of the Messages module:

package main

import (
    "fmt"
    "log"
    "os"
    "os/signal"
    "syscall"

    "github.com/WebexCommunity/webex-go-sdk/v2"
    "github.com/WebexCommunity/webex-go-sdk/v2/messages"
)

func main() {
    // Get access token from environment
    accessToken := os.Getenv("WEBEX_ACCESS_TOKEN")
    if accessToken == "" {
        log.Fatal("WEBEX_ACCESS_TOKEN environment variable is required")
    }

    // Create client
    client, err := webex.NewClient(accessToken, nil)
    if err != nil {
        log.Fatalf("Error creating client: %v", err)
    }

    // Get a room ID to work with
    roomID := os.Getenv("WEBEX_ROOM_ID")
    if roomID == "" {
        log.Fatal("WEBEX_ROOM_ID environment variable is required")
    }

    // Send a message to the room
    message := &messages.Message{
        RoomID: roomID,
        Text:   "Hello from the Webex Go SDK!",
    }

    createdMessage, err := client.Messages().Create(message)
    if err != nil {
        log.Fatalf("Error sending message: %v", err)
    }
    fmt.Printf("Message sent: ID=%s\n", createdMessage.ID)

    // List recent messages in the room
    options := &messages.ListOptions{
        RoomID: roomID,
        Max:    5,
    }
    
    page, err := client.Messages().List(options)
    if err != nil {
        log.Fatalf("Error listing messages: %v", err)
    }

    fmt.Printf("Recent messages in the room:\n")
    for i, msg := range page.Items {
        fmt.Printf("%d. %s: %s\n", i+1, msg.PersonEmail, msg.Text)
    }

    // Set up a message listener
    fmt.Println("\nStarting message listener...")
    messageHandler := func(message *messages.Message) {
        fmt.Printf("New message from %s: %s\n", message.PersonEmail, message.Text)
        
        // Auto-respond to messages containing "hello"
        if client.Messages() != nil && message.PersonID != createdMessage.PersonID {
            lowercase := strings.ToLower(message.Text)
            if strings.Contains(lowercase, "hello") {
                response := &messages.Message{
                    RoomID: message.RoomID,
                    Text:   "Hello! I'm a bot using the Webex Go SDK.",
                }
                _, err := client.Messages().Create(response)
                if err != nil {
                    fmt.Printf("Error sending response: %v\n", err)
                }
            }
        }
    }

    err = client.Messages().Listen(messageHandler)
    if err != nil {
        log.Fatalf("Error starting message listener: %v", err)
    }

    fmt.Println("Listening for messages. Send a message in the space to test.")
    fmt.Println("Press Ctrl+C to exit.")

    // Wait for termination signal
    sigCh := make(chan os.Signal, 1)
    signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
    <-sigCh

    // Clean up before exiting
    fmt.Println("Stopping message listener...")
    client.Messages().StopListening()

    // Delete the message we sent at the beginning
    fmt.Printf("Deleting message with ID %s...\n", createdMessage.ID)
    err = client.Messages().Delete(createdMessage.ID)
    if err != nil {
        log.Printf("Error deleting message: %v", err)
    } else {
        fmt.Println("Message deleted successfully")
    }
}

Error Handling

All methods return structured errors from the webexsdk package. Use the convenience functions to check error types:

message, err := client.Messages().Get("MESSAGE_ID")
if err != nil {
    switch {
    case webexsdk.IsNotFound(err):
        log.Println("Message not found")
    case webexsdk.IsAuthError(err):
        log.Println("Invalid or expired access token")
    case webexsdk.IsRateLimited(err):
        log.Println("Rate limited — SDK retries automatically")
    default:
        log.Printf("Error: %v", err)
    }
}

See webexsdk/Readme.md for the full error type reference.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AdaptiveCard

type AdaptiveCard struct {
	ContentType string      `json:"contentType"`
	Content     interface{} `json:"content"`
}

AdaptiveCard represents an Adaptive Card attachment. See https://developer.webex.com/docs/buttons-and-cards for the card schema.

func NewAdaptiveCard

func NewAdaptiveCard(cardBody interface{}) AdaptiveCard

NewAdaptiveCard creates an AdaptiveCard attachment from a card body. The cardBody should be a map or struct matching the Adaptive Card schema (with "type": "AdaptiveCard", "version": "1.3", "body": [...], etc.).

type Attachment

type Attachment struct {
	ContentType string      `json:"contentType,omitempty"`
	Content     interface{} `json:"content,omitempty"`
}

Attachment represents a message attachment, such as an adaptive card

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the messages API client

func New

func New(webexClient *webexsdk.Client, config *Config) *Client

New creates a new Messages plugin

func (*Client) Create

func (c *Client) Create(message *Message) (*Message, error)

Create posts a new message and/or media content into a room

func (*Client) CreateWithAdaptiveCard

func (c *Client) CreateWithAdaptiveCard(message *Message, card AdaptiveCard, fallbackText string) (*Message, error)

CreateWithAdaptiveCard sends a message with an Adaptive Card attachment. The fallbackText is displayed on clients that don't support adaptive cards. The card parameter should be created via NewAdaptiveCard().

func (*Client) CreateWithAttachment

func (c *Client) CreateWithAttachment(message *Message, file *FileUpload) (*Message, error)

CreateWithAttachment sends a message with file attachments using multipart/form-data. This supports uploading local files directly to Webex (up to 100MB per file).

func (*Client) CreateWithBase64File

func (c *Client) CreateWithBase64File(message *Message, fileName string, base64Data string) (*Message, error)

CreateWithBase64File sends a message with a base64-encoded file attachment. This is a convenience wrapper around CreateWithAttachment for base64 data.

func (*Client) Delete

func (c *Client) Delete(messageID string) error

Delete deletes a message

func (*Client) Get

func (c *Client) Get(messageID string) (*Message, error)

Get returns a single message by ID

func (*Client) List

func (c *Client) List(options *ListOptions) (*MessagesPage, error)

List returns a list of messages in a room

func (*Client) Listen

func (c *Client) Listen(handler MessageHandler) error

Listen starts a real-time stream of message events The provided handler will be called for each new message event

func (*Client) StopListening

func (c *Client) StopListening() error

StopListening stops the real-time stream of message events

func (*Client) Update

func (c *Client) Update(messageID string, message *Message) (*Message, error)

Update updates an existing message

type Config

type Config struct {
	// Any configuration settings for the messages plugin can go here
	MercuryConfig *mercury.Config
}

Config holds the configuration for the Messages plugin

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns the default configuration for the Messages plugin

type FileUpload

type FileUpload struct {
	// FileName is the name of the file (e.g., "report.pdf").
	// Required when using Base64Data.
	FileName string

	// Base64Data is the base64-encoded file content.
	// When set, the data is decoded and uploaded as a binary file.
	Base64Data string

	// FileBytes is the raw file content.
	// Use this when you already have the file in memory as bytes.
	FileBytes []byte
}

FileUpload represents a file to attach to a message. Provide either FilePath (local file) OR Base64Data + FileName.

type ListOptions

type ListOptions struct {
	RoomID          string `url:"roomId,omitempty"`
	MentionedPeople string `url:"mentionedPeople,omitempty"`
	Before          string `url:"before,omitempty"`
	BeforeMessage   string `url:"beforeMessage,omitempty"`
	After           string `url:"after,omitempty"`
	AfterMessage    string `url:"afterMessage,omitempty"`
	Max             int    `url:"max,omitempty"`
	ThreadID        string `url:"threadId,omitempty"`
	PersonID        string `url:"personId,omitempty"`
	PersonEmail     string `url:"personEmail,omitempty"`
	HasFiles        bool   `url:"hasFiles,omitempty"`
}

ListOptions contains the options for listing messages

type Message

type Message struct {
	ID              string                  `json:"id,omitempty"`
	RoomID          string                  `json:"roomId,omitempty"`
	RoomType        string                  `json:"roomType,omitempty"`
	ParentID        string                  `json:"parentId,omitempty"`
	ToPersonID      string                  `json:"toPersonId,omitempty"`
	ToPersonEmail   string                  `json:"toPersonEmail,omitempty"`
	Text            string                  `json:"text,omitempty"`
	Markdown        string                  `json:"markdown,omitempty"`
	HTML            string                  `json:"html,omitempty"`
	Files           []string                `json:"files,omitempty"`
	PersonID        string                  `json:"personId,omitempty"`
	PersonEmail     string                  `json:"personEmail,omitempty"`
	Created         *time.Time              `json:"created,omitempty"`
	Updated         *time.Time              `json:"updated,omitempty"`
	MentionedPeople []string                `json:"mentionedPeople,omitempty"`
	MentionedGroups []string                `json:"mentionedGroups,omitempty"`
	Attachments     []Attachment            `json:"attachments,omitempty"`
	IsVoiceClip     bool                    `json:"isVoiceClip,omitempty"`
	Errors          webexsdk.ResourceErrors `json:"errors,omitempty"`
}

Message represents a Webex message

type MessageHandler

type MessageHandler func(message *Message)

MessageHandler is a function that handles a message event

type MessagesPage

type MessagesPage struct {
	Items []Message `json:"items"`
	*webexsdk.Page
}

MessagesPage represents a paginated list of messages

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL