Build Slack apps, in Swift

Last update: Jul 31, 2022

SlackKit

Build Status

Swift Version Plaforms License MIT SwiftPM compatible Carthage compatible CocoaPods compatible

SlackKit: Slack Apps in Swift

Description

SlackKit makes it easy to build Slack apps in Swift.

It's intended to expose all of the functionality of Slack's Real Time Messaging API as well as the web APIs that are accessible to bot users. SlackKit also supports Slack’s OAuth 2.0 flow including the Add to Slack and Sign in with Slack buttons, incoming webhooks, slash commands, and message buttons.

Installation

Swift Package Manager

Add SlackKit to your Package.swift

let package = Package(
	dependencies: [
		.package(url: "https://github.com/pvzig/SlackKit.git", .upToNextMinor(from: "4.6.0"))
	]
)

When built using Swift Package Manager, SlackKit includes the vapor websocket framework by default which requires libressl.

You can install it with homebrew: brew install libressl

For additional details, see the SKRTMAPI readme.

Carthage

Add SlackKit to your Cartfile:

github "pvzig/SlackKit"

SlackKit is now using .xcframeworks. When building your dependencies with carthage, please specify a platform: carthage bootstrap --use-xcframeworks --platform macos

CocoaPods

Add SlackKit to your Podfile:

pod 'SlackKit'

Usage

To use the library in your project import it:

import SlackKit

The Basics

Create a bot user with an API token:

import SlackKit

let bot = SlackKit()
bot.addRTMBotWithAPIToken("xoxb-SLACK-BOT-TOKEN")
// Register for event notifications
bot.notificationForEvent(.message) { (event, _) in
	// Your bot logic here
	print(event.message)
}

or create a ready-to-launch Slack app with your application’s Client ID and Client Secret:

import SlackKit

let bot = SlackKit()
let oauthConfig = OAuthConfig(clientID: "CLIENT_ID", clientSecret: "CLIENT_SECRET")
bot.addServer(oauth: oauthConfig)

or just make calls to the Slack Web API:

import SlackKit

let bot = SlackKit()
bot.addWebAPIAccessWithToken("xoxb-SLACK-BOT-TOKEN")
bot.webAPI?.authenticationTest(success: { (success) in
	print(success)
}, failure: nil)

Slash Commands

After configuring your slash command in Slack (you can also provide slash commands as part of a Slack App), create a route, response middleware for that route, and add it to a responder:

let slackkit = SlackKit()
let middleware = ResponseMiddleware(token: "SLASH_COMMAND_TOKEN", response: SKResponse(text: "👋"))
let route = RequestRoute(path: "/hello", middleware: middleware)
let responder = SlackKitResponder(routes: [route])
slackkit.addServer(responder: responder)

When a user enters that slash command, it will hit your configured route and return the response you specified.

Message Buttons

Add message buttons to your responses for additional interactivity.

To send messages with actions, add them to an attachment and send them using the Web API:

let helloAction = Action(name: "hello", text: "🌎")
let attachment = Attachment(fallback: "Hello World", title: "Welcome to SlackKit", callbackID: "hello_world", actions: [helloAction])
slackkit.webAPI?.sendMessage(channel: "CXXXXXX", text: "", attachments: [attachment], success: nil, failure: nil)

To respond to message actions, add a RequestRoute with MessageActionMiddleware using your app’s verification token to your SlackKitResponder:

let response = ResponseMiddleware(token: "SLACK_APP_VERIFICATION_TOKEN", response: SKResponse(text: "Hello, world!"))
let actionRoute = MessageActionRoute(action: helloAction, middleware: response)
let actionMiddleware = MessageActionMiddleware(token: "SLACK_APP_VERIFICATION_TOKEN", routes:[actionRoute])
let actions = RequestRoute(path: "/actions", middleware: actionMiddleware)
let responder = SlackKitResponder(routes: [actions])
slackkit.addServer(responder: responder)

OAuth

Slack has many different oauth scopes that can be combined in different ways. If your application does not request the proper OAuth scopes, your API calls will fail.

If you authenticate using OAuth and the Add to Slack or Sign in with Slack buttons this is handled for you.

For local development of things like OAuth, slash commands, and message buttons, you may want to use a tool like ngrok.

Advanced Usage

Don’t need the whole banana? Want more control over the low-level implementation details? Use the extensible frameworks SlackKit is built on:

Framework Description
SKClient Write your own client implementation
SKRTMAPI Connect to the Slack RTM API
SKServer Spin up a server for a Slack app
SKWebAPI Access the Slack Web API

Examples

You can find the source code for several example applications here.

Tutorials

Get In Touch

Twitter: @pvzig

Email: [email protected]

GitHub

https://github.com/pvzig/SlackKit
Comments
  • 1. Unknown error (404) when sending message with question mark at the end

    When trying to send message (bot.webApi?.sendMessage()) with text that has question mark (?) I get failure with unknownError type. When I removed this question mark my message got through. I think there is something wrong with escaping this sign from request url and it's messing with url query.

    Reviewed by ghost at 2017-07-20 09:01
  • 2. How to observer changes in client?

    I'm a bit confused how one would observe changes on the Client. A callback api would be appreciated. Essentially when messages are handled my client, state changes and etc. how would one go about observing these changes in a controller?

    Reviewed by hamin at 2015-12-18 20:07
  • 3. channels.history is deprecated, should we migrate to conversations.history instead?

    I've just started playing around with SKWebAPI, and it seems like channelsHistory() fails since the whole family if channels* API methods is now deprecated and doesn't work for new apps already.

    I'd love to work on this and port the deprecated methods from channel* to conversations*, but I'm fairly new to Swift and will need your help reviewing my PRs. Should I work on that?

    Reviewed by nategadzhi at 2020-10-10 03:27
  • 4. Issue with `slackFormatEscaping`

    Hi :)

    I have some issues with the slackFormatEscaping function When I use it I am unable to make mentions because it escape the characters but after when URLQueryItem convert params it encodes this to Percent-encoding

    For the moment I have fork all the repositories to remove this function, Am I wrong or Am i missing something ?

    Reviewed by PoissonBallon at 2018-03-14 17:00
  • 5. Add support for Attachments

    I actually need support for Attachments in the app I'm working on. @muratayusuke's fork has this actually already done along with a bunch of other enhancements: https://github.com/muratayusuke/SlackKit/commit/0baf74dacb98c6a4d3186ef4ce2370bc5741e40d

    Would love to see a PR @muratayusuke to pull his fork's changes into upstream. If not I can always make a PR just for the Attachment support but really it would just be duplicating @muratayusuke's efforts. Thoughts?

    Reviewed by hamin at 2016-02-27 18:42
  • 6. Slack API expects token passed in Authorization header instead of a GET parameter?

    The code I'm running to run is simple:

    let bot = SlackKit()
    bot.addWebAPIAccessWithToken(token)
    bot.webAPI?.conversationsList(success: { channels, nextCursor in
        print(channels)
    }, failure: { error in
        print(error.localizedDescription)
    })
    

    I traced the URLRequest being sent and it seems like the url is: https://slack.com/api/conversations.list?token=xoxb-SLACK-BOT-TOKEN

    I tried sending this same request with Postman and got this response:

    {
        "ok": false,
        "error": "invalid_auth"
    }
    

    But when I send a request to https://slack.com/api/conversations.list with the following header:

    Authorization: Bearer xoxb-SLACK-BOT-TOKEN
    

    it returns the expected response:

    {
        "ok": true,
        "channels": [
            {
    ...
    

    So I'm not sure why I'm the only one having the issue, but maybe it's because I created my app on the Slack Api portal yesterday and it uses this new header auth style?

    If that's the case, then it looks this library needs to be updated to pass the token in the Authorization header for new Slack Apps.

    Edit: Here's the changelog where they deprecated querystring authentication: https://api.slack.com/changelog/2020-11-no-more-tokens-in-querystrings-for-newly-created-apps

    Reviewed by katzenbaer at 2021-12-28 13:42
  • 7. Build fails on Ubuntu 18.04

    Ubuntu 18.04.03, Swift 5.0.2, SlackKit "upToNextMinor 4.3.0"

    Build silently fails, final output from swift build --verbose is like this:

    /usr/bin/clang -target x86_64-unknown-linux --sysroot / -fPIC -g -O0 -DSWIFT_PACKAGE=1 -DDEBUG=1 -fblocks -fmodules -fmodule-name=CNIOOpenSSL -I /home/pseudo/gaijinbot/.build/checkouts/swift-nio-ssl/Sources/CNIOOpenSSL/include -fmodule-map-file=/home/pseudo/gaijinbot/.build/checkouts/swift-nio-ssl-support/module.modulemap -fmodules-cache-path=/home/pseudo/gaijinbot/.build/x86_64-unknown-linux/debug/ModuleCache -MD -MT dependencies -MF /home/pseudo/gaijinbot/.build/x86_64-unknown-linux/debug/CNIOOpenSSL.build/shims.c.d -c /home/pseudo/gaijinbot/.build/checkouts/swift-nio-ssl/Sources/CNIOOpenSSL/shims.c -o /home/pseudo/gaijinbot/.build/x86_64-unknown-linux/debug/CNIOOpenSSL.build/shims.c.o :

    . $

    Reviewed by khakionion at 2019-08-25 05:46
  • 8. iOS: Cocoapods framework not found SlackKit

    I try install this framework via Cocoapods for iOS application. But can not import be cause of error:

    Showing Recent Messages :-1: framework not found SlackKit

    Reviewed by tandinhle at 2019-03-07 19:55
  • 9. `sendEphemeral` should have an equivalent `sendThreadedEphemeral`

    Much like sendMessage has sendThreadedMessage. There is currently no way to respond in a thread with an ephemeral message.

    Alternatively, networkInterface could be exposed or another extension point could be added for library consumers, such as an "additionalParameters" function parameter that would allow passing in additional fields to help build the payload.

    Or perhaps there's something else I missed that might allow us to do this?

    Reviewed by allenhumphreys at 2019-03-06 15:02
  • 10. Type 'SlackKit' does not conform to protocol 'RTMAdapter'

    After dependencies update a few days ago I've got the error:

    Type 'SlackKit' does not conform to protocol 'RTMAdapter'
    

    Error repeats even after fresh install. Adding a stub for connectionClosed(with error: Error, instance: SKRTMAPI) method fixes the problem, but not sure that this is the proper solution (: Looks

    Is it only my problem or there some bug of SlackKit conformance to SKRTMAPI? Thanks in advance!

    Reviewed by ihityouback at 2018-02-12 11:25
  • 11. Unable to build with Swift Package Manager

    Attempts to build recent versions of SlackKit fail when using SPM.

    Using the following steps, building an application including SlackKit fails when specifying version 4.2.0 rather than 4.1.0 (which still works):

    mkdir x6
    cd x6
    swift package init --type executable
    

    edit Package.swift to include dependencies

    swift package generate-xcodeproj
    open x6.xcodeproj
    

    build project using Xcode UI

    $ swift --version
    Apple Swift version 4.2.1 (swiftlang-1000.11.42 clang-1000.11.45.1)
    Target: x86_64-apple-darwin18.2.0
    

    Xcode Version 10.1 (10B61)

    Build errors are in dependencies of packages required by SlackKit. e.g.

    ... x6/.build/checkouts/swift-nio-ssl.git--5028798909648298346/Sources/CNIOOpenSSL/include/c_nio_openssl.h:17:10: fatal error: 'openssl/conf.h' file not found
    #include <openssl/conf.h>
             ^~~~~~~~~~~~~~~~
    1 error generated.
    

    I see this problem on both of my systems. Hopefully this isn't an embarrassing pilot error on my behalf.

    slackkit.bug.txt

    Reviewed by ObscureBug at 2019-02-25 04:50
  • 12. incomplete definition of type 'struct bio_st'

    Wanted to take advantage of this framework and set it up in my SPM - I did install (homebrew) libressl as suggested, but am still getting some errors upon adding SlackKit as a dependency in my project targets:

    Screen Shot 2022-06-02 at 4 56 48 PM

    I also attempted a suggestion to just remove exclude the vapor websocket framework - but that didn't seem to work either.

    Any guidance would be greatly appreciated!

    Reviewed by sherryshao at 2022-06-02 23:58
  • 13. Process exited with status 132

    Hello there, I've use and build a simple bot an the package works awesome!

    After using it locally and working, I've try to build the app in Heroku, I've followed some examples and re-do every step (even as a new app from scratch) But I always get this without any more clues about what's wrong.

    2022-02-11T23:01:20.474572+00:00 heroku[run.6574]: State changed from starting to up
    2022-02-11T23:01:21.567919+00:00 heroku[run.6574]: Process exited with status 132
    2022-02-11T23:01:21.649681+00:00 heroku[run.6574]: State changed from up to complete
    

    Can anyone help me out here?

    Reviewed by yreaction at 2022-02-11 23:05
  • 14. Dependency resolution in a new Vapor App

    Hey, sorry this is a bit rushed. Thanks for the great package. I hit a dependency resolution issue when trying to use this in a new Vapor Project (on 4.55.0).


    Steps to reproduce

    • vapor new TestProject
    • Add SlackKit
    • see error below

    I think the issue is in the dependency on an older version of WebSocket, which now has a 2.0.0 that's incompatible with the latest vapor.

    One option that might be nice could be to have 2 packages that people could depend on

    • SlackAPI - No dependencies
    • SlackKit - Dependencies on Swifter, StarScream, etc

    That would avoid the dependency hassle for consumers who want to just hit the Slack API, but would probably be a bit more work to maintain.

    Workaround

    I've published a 5.0.0 workaround tag over on my fork that removes the libraries/targets I didn't need. Posted in case anyone else hits this issue.

      Dependencies could not be resolved because root depends on 'fluent' 4.0.0..<5.0.0 and root depends on 'SlackKit' 4.8.1..<4.9.0.
      'SlackKit' is incompatible with 'fluent' because 'SlackKit' >= 4.8.1 practically depends on 'swift-nio' 1.9.5..<2.0.0 (1).
      'fluent' >= 4.0.0 practically depends on 'swift-nio' 2.0.0..<3.0.0 because 'fluent' 4.4.0 depends on 'fluent-kit' 1.16.0..<2.0.0 and 'fluent-kit' >= 1.16.0 depends on 'swift-nio' 2.33.0..<3.0.0.
      'fluent' {4.0.0..<4.4.0, 4.4.1..<5.0.0} practically depends on 'swift-nio' 2.0.0..<3.0.0 because 'fluent-kit' >= 1.0.0-rc.2.2 depends on 'sql-kit' 3.1.0..<4.0.0 and 'sql-kit' >= 3.0.0-beta.1 depends on 'swift-nio' 2.0.0..<3.0.0.
      'fluent' {4.0.0..<4.4.0, 4.4.1..<5.0.0} practically depends on 'fluent-kit' 1.0.0..<2.0.0 because 'fluent' 4.3.0..<4.4.0 depends on 'fluent-kit' 1.12.0..<2.0.0.
      'fluent' {4.0.0..<4.3.0, 4.4.1..<5.0.0} practically depends on 'fluent-kit' 1.0.0..<2.0.0 because 'fluent' 4.0.0..<4.3.0 depends on 'fluent-kit' 1.0.0..<2.0.0 and no versions of 'fluent' match the requirement 4.4.1..<5.0.0.
      'websocket' 1.1.0..<2.0.0 practically depends on 'swift-nio' 1.9.5..<2.0.0 because 'websocket' 1.1.0..<2.0.0-beta.1 depends on 'swift-nio' 1.9.5..<2.0.0 and no versions of 'websocket' match the requirement 2.0.0-beta.1..<2.0.0.
         (1) As a result, 'SlackKit' >= 4.8.1 practically depends on 'swift-nio' 1.9.5..<2.0.0 because 'SlackKit' >= 4.8.1 depends on 'websocket' 1.1.2..<2.0.0.
    
    Reviewed by iainsmith at 2022-02-03 14:07
The Swift-est way to build native mobile apps that connect to Salesforce.
The Swift-est way to build native mobile apps that connect to Salesforce.

Swiftly Salesforce is the Swift-est way to build native mobile apps that connect to Salesforce: Written entirely in Swift. Very easy to install and up

Jul 21, 2022
A Swift Framework build for the Ark Ecosystem
A Swift Framework build for the Ark Ecosystem

Introduction Overview SwiftyArk is a simple, lightweight framework for the Ark Ecosystem. SwiftyArk provides a simple wrapper for accessing Ark accoun

May 12, 2019
Wanikani-swift - Unofficial Swift client for the WaniKani API

WaniKani A Swift library and client for the WaniKani REST API. It currently supp

Feb 2, 2022
AWS Full Stack Swift with Apple CarPlay
 AWS Full Stack Swift with Apple CarPlay

This application demonstrates a full-stack Apple CarPlay app that uses Swift for both the UI and the backend services in AWS. The app accesses Lambda functions written in Swift and deployed from Docker images. The app accesses Amazon Location Service and a 3rd party weather api to display information in the vicinity of the user.

Jul 23, 2022
A Swift wrapper for Foursquare API. iOS and OSX.

Das Quadrat Das Quadrat is Foursquare API wrapper written in Swift. Features Supports iOS and OSX. Covers all API endpoints. Authorization process imp

Jun 18, 2022
Pokeapi wrapper, written in Swift

PokemonKit What is this? PokemonKit is a swift wrapper for Pokeapi. PokemonKit use Alamofire and PromiseKit for async web requests handling. Usage imp

Jun 11, 2022
👤 Framework to Generate Random Users - An Unofficial Swift SDK for randomuser.me
👤 Framework to Generate Random Users - An Unofficial Swift SDK for randomuser.me

RandomUserSwift is an easy to use Swift framework that provides the ability to generate random users and their accompanying data for your Swift applic

Jan 29, 2022
Swift client for Unsplash
Swift client for Unsplash

Unsplash API client written in Swift. Unsplash offers 2 APIs: Source API (unlimited requests) Official API JSON API (5000 requests / hour) JSON API is

Jun 2, 2022
An Elegant Spotify Web API Library Written in Swift for iOS and macOS
An Elegant Spotify Web API Library Written in Swift for iOS and macOS

Written in Swift 4.2 Spartan is a lightweight, elegant, and easy to use Spotify Web API wrapper library for iOS and macOS written in Swift 3. Under th

Jul 8, 2022
An Elegant Financial Markets Library Written in Swift
An Elegant Financial Markets Library Written in Swift

Notice As of May 20th, 2017, it appears that Yahoo is dropping support for a few features that BigBoard supports or there is an outage on their end ca

Jun 3, 2022
Swift Wrapper For Bittrex API

BittrexApiKit Swift client for Bittrex api. It support all APIs with most recent changes. more info here let api = Bittrex(apikey: "api key", secretke

Apr 5, 2021
iOS/macOS Cross-platform Ark-Ecosystem Framework in Swift | Powered by Ѧrk.io |
iOS/macOS Cross-platform Ark-Ecosystem Framework in Swift | Powered by Ѧrk.io |

a macOS & iOS Swift Framework for Ark.io. What is ARKKit? ARKKit is wrapper for interacting with the Ark Ecosystem. It is written purely in Swift 4.0,

Jun 28, 2022
Instagram API client written in Swift
Instagram API client written in Swift

SwiftInstagram is a wrapper for the Instagram API written in Swift. It allows you to authenticate users and request data from Instagram effortlessly.

Jul 26, 2022
The Waterwheel Swift SDK provides classes to natively connect iOS, macOS, tvOS, and watchOS applications to Drupal 7 and 8.
The Waterwheel Swift SDK provides classes to natively connect iOS, macOS, tvOS, and watchOS applications to Drupal 7 and 8.

Waterwheel Swift SDK for Drupal Waterwheel makes using Drupal as a backend with iOS, macOS, tvOS, or watchOS enjoyable by combining the most used feat

Jul 26, 2022
A Swift library for the Forecast.io Dark Sky API
A Swift library for the Forecast.io Dark Sky API

Requirements To use ForecastIO, all you need is an API key for the Dark Sky API. ForecastIO supports iOS (≥9.0), macOS (≥10.10), watchOS (≥2.0), and t

Jul 26, 2022
A Jamf Classic communication framework written in Swift
A Jamf Classic communication framework written in Swift

JamfKit JamfKit is an iOS / macOS / tvOS framework to communicate with the JSS API offered by any Jamf host. Summary Features Installation Carthage Co

Mar 31, 2022
Swift 3 framework for accessing data in Event Registry (http://eventregistry.org/)

PPEventRegistryAPI Swift 3 framework for accessing data in Event Registry (http://eventregistry.org/) Supported API calls Log In Get Event By Identifi

Nov 1, 2016
A swift SDK for Medium's OAuth2 API

Medium SDK - Swift A library to allow access to Medium API for any Swift iOS application. Features Medium.com authorization & token handling Login sta

Jan 22, 2022
A Twitter framework for iOS & OS X written in Swift
A Twitter framework for iOS & OS X written in Swift

Getting Started Installation If you're using Xcode 6 and above, Swifter can be installed by simply dragging the Swifter Xcode project into your own pr

Jul 26, 2022