Convert Figma logo to code with AI

slack-go logoslack

Slack API in Go, originally by @nlopes; Maintainers needed, contact @parsley42

4,642
1,128
4,642
106

Top Related Projects

A framework to build Slack apps using Python

Slack Developer Kit for Node.js

Slack Developer Kit for Python

2,733

A framework to build Slack apps using JavaScript

Quick Overview

slack-go/slack is a Go library for interacting with the Slack API. It provides a comprehensive set of functions and types to build Slack applications, bots, and integrations using Go. The library supports both the Web API and Real Time Messaging (RTM) API.

Pros

  • Extensive coverage of Slack API features
  • Well-documented and actively maintained
  • Supports both Web API and RTM API
  • Type-safe implementation with Go structs for Slack objects

Cons

  • Learning curve for developers new to Slack API
  • Some advanced features may require additional setup
  • Occasional breaking changes between major versions
  • Limited built-in rate limiting (requires manual implementation)

Code Examples

Creating a new Slack client:

api := slack.New("YOUR_SLACK_BOT_TOKEN")

Sending a message to a channel:

channelID := "C1234567890"
_, _, err := api.PostMessage(channelID, slack.MsgOptionText("Hello, Slack!", false))
if err != nil {
    log.Fatal(err)
}

Listening for events using the RTM API:

rtm := api.NewRTM()
go rtm.ManageConnection()

for msg := range rtm.IncomingEvents {
    switch ev := msg.Data.(type) {
    case *slack.MessageEvent:
        fmt.Printf("Message: %v\n", ev.Text)
    case *slack.RTMError:
        fmt.Printf("Error: %s\n", ev.Error())
    }
}

Getting Started

  1. Install the library:

    go get -u github.com/slack-go/slack
    
  2. Import the library in your Go code:

    import "github.com/slack-go/slack"
    
  3. Create a new Slack app and obtain a bot token from the Slack API website.

  4. Initialize a Slack client with your bot token:

    api := slack.New("YOUR_SLACK_BOT_TOKEN")
    
  5. Start using the library to interact with Slack, such as sending messages or listening for events.

Competitor Comparisons

A framework to build Slack apps using Python

Pros of Bolt-python

  • Simplified API with built-in support for common Slack app patterns
  • Easier handling of events, commands, and interactive components
  • Better documentation and more comprehensive examples

Cons of Bolt-python

  • Limited to Python, while slack-go is for Go developers
  • May have slightly higher overhead due to abstraction layer
  • Less flexibility for advanced custom implementations

Code Comparison

Bolt-python:

from slack_bolt import App

app = App(token="YOUR_BOT_TOKEN")

@app.message("hello")
def message_hello(message, say):
    say(f"Hey there <@{message['user']}>!")

app.start(port=3000)

slack-go:

api := slack.New("YOUR_BOT_TOKEN")
rtm := api.NewRTM()
go rtm.ManageConnection()

for msg := range rtm.IncomingEvents {
    switch ev := msg.Data.(type) {
    case *slack.MessageEvent:
        if ev.Text == "hello" {
            rtm.SendMessage(rtm.NewOutgoingMessage(fmt.Sprintf("Hey there <@%s>!", ev.User), ev.Channel))
        }
    }
}

Both libraries provide functionality for building Slack apps, but Bolt-python offers a more streamlined approach with its decorator-based event handling. slack-go provides lower-level access to the Slack API, which may be preferable for developers who need more control or are working in Go environments.

Slack Developer Kit for Node.js

Pros of node-slack-sdk

  • Official Slack SDK, ensuring up-to-date API support and compatibility
  • Comprehensive documentation and examples for JavaScript/TypeScript developers
  • Supports both web API and real-time messaging (RTM) functionality

Cons of node-slack-sdk

  • Limited to JavaScript/TypeScript environments, less versatile than Go
  • May have a steeper learning curve for developers new to Node.js ecosystem
  • Potentially slower performance compared to Go implementation

Code Comparison

node-slack-sdk (JavaScript):

const { WebClient } = require('@slack/web-api');
const web = new WebClient(token);
(async () => {
  const result = await web.chat.postMessage({ channel: 'C1234', text: 'Hello!' });
  console.log(result);
})();

slack-go/slack (Go):

api := slack.New(token)
channelID, timestamp, err := api.PostMessage(
    "C1234",
    slack.MsgOptionText("Hello!", false),
)
if err != nil {
    fmt.Printf("%s\n", err)
}

Both libraries provide similar functionality for posting messages, but with syntax and patterns specific to their respective languages. The node-slack-sdk uses Promises and async/await, while slack-go/slack uses Go's error handling approach.

Slack Developer Kit for Python

Pros of python-slack-sdk

  • Official Slack SDK, ensuring better long-term support and compatibility
  • More comprehensive documentation and examples
  • Supports both synchronous and asynchronous operations

Cons of python-slack-sdk

  • Limited to Python, while slack-go can be used in Go projects
  • May have a steeper learning curve for developers new to Python

Code Comparison

python-slack-sdk:

from slack_sdk import WebClient

client = WebClient(token="YOUR_TOKEN")
response = client.chat_postMessage(channel="#random", text="Hello, Slack!")

slack-go:

api := slack.New("YOUR_TOKEN")
channelID, timestamp, err := api.PostMessage("#random", slack.MsgOptionText("Hello, Slack!", false))

Both libraries provide similar functionality for posting messages, but with syntax specific to their respective languages. The python-slack-sdk offers a more object-oriented approach, while slack-go uses a more functional style.

2,733

A framework to build Slack apps using JavaScript

Pros of bolt-js

  • Built and maintained by Slack, ensuring up-to-date API support
  • Simplified event handling and middleware system
  • Supports both JavaScript and TypeScript

Cons of bolt-js

  • Limited to Node.js environment
  • Less flexible for custom implementations
  • Steeper learning curve for developers new to Slack's concepts

Code Comparison

bolt-js:

const { App } = require('@slack/bolt');

const app = new App({
  token: process.env.SLACK_BOT_TOKEN,
  signingSecret: process.env.SLACK_SIGNING_SECRET
});

app.message('hello', async ({ message, say }) => {
  await say(`Hey there <@${message.user}>!`);
});

slack:

import (
    "github.com/slack-go/slack"
)

api := slack.New(os.Getenv("SLACK_BOT_TOKEN"))

rtm := api.NewRTM()
go rtm.ManageConnection()

for msg := range rtm.IncomingEvents {
    switch ev := msg.Data.(type) {
    case *slack.MessageEvent:
        if ev.Text == "hello" {
            rtm.SendMessage(rtm.NewOutgoingMessage("Hey there!", ev.Channel))
        }
    }
}

The bolt-js example shows a more concise way to handle messages, while the slack example offers more granular control over event handling. bolt-js abstracts away some complexities, making it easier for quick implementations, whereas slack provides a lower-level API for more customized solutions.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Slack API in Go Go Reference

This is the original Slack library for Go created by Norberto Lopes, transferred to a GitHub organization.

You can also chat with us on the #slack-go, #slack-go-ja Slack channel on the Gophers Slack.

logo

This library supports most if not all of the api.slack.com REST calls, as well as the Real-Time Messaging protocol over websocket, in a fully managed way.

Project Status

There is currently no major version released. Therefore, minor version releases may include backward incompatible changes.

See CHANGELOG.md or Releases for more information about the changes.

Installing

go get

$ go get -u github.com/slack-go/slack

Example

Getting all groups

import (
	"fmt"

	"github.com/slack-go/slack"
)

func main() {
	api := slack.New("YOUR_TOKEN_HERE")
	// If you set debugging, it will log all requests to the console
	// Useful when encountering issues
	// slack.New("YOUR_TOKEN_HERE", slack.OptionDebug(true))
	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)
	}
}

Getting User Information

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)
}

Minimal Socket Mode usage:

See https://github.com/slack-go/slack/blob/master/examples/socketmode/socketmode.go

Minimal RTM usage:

As mentioned in https://api.slack.com/rtm - for most applications, Socket Mode is a better way to communicate with Slack.

See https://github.com/slack-go/slack/blob/master/examples/websocket/websocket.go

Minimal EventsAPI usage:

See https://github.com/slack-go/slack/blob/master/examples/eventsapi/events.go

Socketmode Event Handler (Experimental)

When using socket mode, dealing with an event can be pretty lengthy as it requires you to route the event to the right place.

Instead, you can use SocketmodeHandler much like you use an HTTP handler to register which event you would like to listen to and what callback function will process that event when it occurs.

See ./examples/socketmode_handler/socketmode_handler.go

Contributing

You are more than welcome to contribute to this project. Fork and make a Pull Request, or create an Issue if you see any problem.

Before making any Pull Request please run the following:

make pr-prep

This will check/update code formatting, linting and then run all tests

License

BSD 2 Clause license