slack-go/slack Go Library

repository·master·Indexed 26 days ago

https://github.com/slack-go/slack

A comprehensive Go implementation of the Slack API. It supports REST calls, Real-Time Messaging (RTM) via WebSockets, and Socket Mode. The library includes functionality for managing user groups, user information, and extensive Admin API capabilities such as channel management (creation, archiving, and search), IDP group access restrictions, and role assignment management.

Tokens
53.2K
Snippets
83
Records
470
Agent score
89%

What's inside slack-go/slack

  1. Use Socket Mode, RTM, or EventsAPI

    master

    The library provides support for multiple communication protocols. For most modern applications, Socket Mode is recommended over RTM.

    Refer to the following example paths for minimal implementations:

    • Socket Mode: examples/socketmode/socketmode.go
    • RTM (Websocket): examples/websocket/websocket.go
    • EventsAPI: examples/eventsapi/events.go
    • Socket Mode Event Handler (Experimental): Use SocketmodeHandler to register specific event types and callback functions, similar to an HTTP handler. See examples/socketmode_handler/socketmode_handler.go.
  2. Initialize a Slack API client

    master

    Create a new Slack client using slack.New(token). You can optionally enable debugging to log all requests to the console using slack.OptionDebug(true), which is useful for troubleshooting.

    import (
        "github.com/slack-go/slack"
    )
    
    api := slack.New("YOUR_TOKEN_HERE")
    // To enable debugging:
    // api := slack.New("YOUR_TOKEN_HERE", slack.OptionDebug(true))
  3. Manage Slack Calls

    master
    The slack package provides methods to manage Slack Calls via the calls.* API methods. You can create, retrieve, update, end, and manage participants for a call using the Client methods. Most methods have both a standard version and a Context version (e.g., AddCall and AddCallContext) for better control over request lifecycles.
  4. Manage Do Not Disturb (DND) status

    master
    The slack package provides several methods to manage and query Do Not Disturb (DND) settings and snooze modes. You can end DND sessions, end snooze modes, get DND information for specific users or teams, and set snooze durations.
  5. Configure HTTP retries in slack-go

    master

    Retries are disabled by default. To enable them, use OptionRetry or OptionRetryConfig when initializing your Slack client. Retries improve reliability during network flakiness or when Slack is busy.

    Important Limitations:

    • Requests that stream the body (like file uploads) cannot be retried because the body can only be sent once.
    • Regular API calls (form or JSON) are retryable if the request body can be replayed (i.e., req.GetBody is implemented).
  6. Use Context-aware API methods

    master
    For all major chat operations (PostMessage, DeleteMessage, UpdateMessage, etc.), the library provides ...Context variants (e.g., PostMessageContext). These allow you to pass a context.Context to manage timeouts, cancellations, and deadlines for the underlying HTTP requests.
  7. Get user information

    master

    Use api.GetUserInfo(userID) to retrieve details about a specific user, such as their ID, real name, and email.

    import (
        "fmt"
        "github.com/slack-go/slack"
    )
    
    func main() {
        api := slack.New("YOUR_TOKEN_HERE")
        user, err := api.GetUserInfo("U023BECGF")
        if err != nil {
            fmt.Printf("%s\n", err)
            return
        }
        fmt.Printf("ID: %s, Fullname: %s, Email: %s\n", user.ID, user.Profile.RealName, user.Profile.Email)
    }
  8. Get all user groups

    master

    Use api.GetUserGroups to retrieve groups. You can pass options such as slack.GetUserGroupsOptionIncludeUsers(bool) to control whether user information is included in the response.

    import (
        "fmt"
        "github.com/slack-go/slack"
    )
    
    func main() {
        api := slack.New("YOUR_TOKEN_HERE")
        groups, err := api.GetUserGroups(slack.GetUserGroupsOptionIncludeUsers(false))
        if err != nil {
            fmt.Printf("%s\n", err)
            return
        }
        for _, group := range groups {
            fmt.Printf("ID: %s, Name: %s\n", group.ID, group.Name)
        }
    }
  9. Configure HTTP retries

    master

    Retries are disabled by default. You can configure them using:

    • OptionRetry(n): Enables retries specifically for 429 (Too Many Requests) errors.
    • OptionRetryConfig(cfg): Provides full control over connection retries, 429 retries, and optional 5xx retries.

    If using a custom HTTP client, pass retry options after OptionHTTPClient.

  10. Configure message posting with PostMessageParameters

    master

    The PostMessageParameters struct allows for a single-object configuration of a message. While most users use MsgOption functions, you can use MsgOptionPostMessageParameters to pass this struct.

    Fields include:

    • Username (string)
    • AsUser (bool)
    • Parse (string: "full" or "none")
    • ThreadTimestamp (string)
    • ReplyBroadcast (bool)
    • LinkNames (int)
    • UnfurlLinks (bool)
    • UnfurlMedia (bool)
    • IconURL (string)
    • IconEmoji (string)
    • Markdown (bool)
    • EscapeText (bool)
    • Channel (string)
    • User (string)
    • MetaData (SlackMetadata)
    • FileIDs ([]string)
  11. Use RetryConfig to customize retry behavior

    master

    The RetryConfig struct allows you to fine-tune how the client handles retries. You can use DefaultRetryConfig() to get a sensible starting point.

    Fields:

    • MaxRetries: Maximum number of retry attempts (0 = no retries).
    • Handlers: A slice of RetryHandler to consult. If nil, only rate limits (429) are retried.
    • RetryAfterDuration: Wait time for 429 errors when the Retry-After header is missing or invalid.
    • RetryAfterJitter: Random jitter [0, RetryAfterJitter] added to 429 waits.
    • BackoffInitial: Initial backoff duration for 5xx and connection errors.
    • BackoffMax: Maximum cap for the backoff duration.
    • BackoffJitter: Random jitter [0, BackoffJitter] added to exponential backoff.