Swiftpack.co - Package - SvenTiigi/PerfectSlackAPIClient

Logo


Swift 3.2 Platform TravisBuild codecov codebeat badge Docs Release @SvenTiigi

PerfectSlackAPIClient is an API Client to access the Slack API from your Perfect Server Side Swift application. It is build on top of PerfectAPIClient, a network abstraction layer to perform network requests from your Perfect Server Side Swift application

Installation

To integrate using Apple's Swift Package Manager, add the following as a dependency to your Package.swift:

.package(url: "https://github.com/SvenTiigi/PerfectSlackAPIClient.git", from: "1.0.0")

Here's an example PackageDescription:

// swift-tools-version:4.0

import PackageDescription

let package = Package(
    name: "MyPackage",
    products: [
        .library(
            name: "MyPackage",
            targets: ["MyPackage"]
        )
    ],
    dependencies: [
        .package(url: "https://github.com/SvenTiigi/PerfectSlackAPIClient.git", from: "1.0.0")
    ],
    targets: [
        .target(
            name: "MyPackage",
            dependencies: ["PerfectSlackAPIClient"]
        ),
        .testTarget(
            name: "MyPackageTests",
            dependencies: ["MyPackage", "PerfectSlackAPIClient"]
        )
    ]
)

Setup

In order to send a message to your Slack-Channel, you have to generate a Webhook URL for your Slack-Workspace. Check out the Slack API Hello world example. After you successfully generated a Slack Webhook URL you can configure the SlackAPIClient.

// Configure the Webhook URL
SlackAPIClient.webhookURL = "YOUR_WEBHOOK_URL"

It is recommended to set the Webhook URL in your initialization code just before you start your PerfectHTTPServer.

Usage

The following example demonstrates how to send a SlackMessage.

import PerfectAPIClient
import PerfectSlackAPIClient

// Initialize SlackMessage
let message = SlackMessage()
message.text = "Hello Developer".toMarkdown(format: .code)

// Initialize SlackAttachment
let attachment = SlackAttachment()
attachment.title = "Mindblown ๐Ÿคฏ"
attachment.imageURL = "https://media.giphy.com/media/Um3ljJl8jrnHy/giphy.gif"

// Add the attachment to the message
message.attachments = [attachment]

// Send SlackMessage
SlackAPIClient.send(message).request { (result: APIClientResult<APIClientResponse>) in
    result.analysis(success: { (response: APIClientResponse) in
 ย  ย  ย  ย // Check out your Slack-Channel ๐Ÿ˜Ž
 ย  ย  ย  ย print(response.payload) // "ok"
    }, failure: { (error: APIClientError) in
        // SlackMessage could not be sent ๐Ÿ˜ฑ
        // Perform error.analysis(....) to get more information
    })
}

Fore more details on APIClientResult, APIClientResponse and error handling check out PerfectAPIClient.

SlackMessage

The SlackMessage offers two important features which will be explained in the upcoming sections.

Message Builder Preview

You can generate a Slack Message Builder URL from your SlackMessage to get a brief look of how your message will be presented in your Slack-Channel.

// Initialize SlackMessage
let message = SlackMessage(text: "Posted via PerfectSlackAPIClient")

// Initialize Attachment
let attachment = SlackAttachment()
attachment.title = "Awesome ๐Ÿ˜ฑ"
attachment.imageURL = "https://media0.giphy.com/media/90F8aUepslB84/giphy.gif"

// Add attachment to message
message.attachments = [attachment]

// Print Slack Message Builder Preview URL
print(message.messageBuilderPreviewURL)

The messageBuilderPreviewURL property generates the Slack Message API Builder URL and append the SlackMessage URL encoded JSON string. The example will generate this URL.

Message Builder Example Preview

Send

As an alternative way of sendind a SlackMessage, the object itself has a convienence function send to just send and forget or supply success and failure closure.

// Initialize SlackMessage
let message = SlackMessage(text: "Foo Bar")

// Send and forget
message.send()

// Success and failure closure
message.send(success: { (response: APIClientResponse) in
    // Success
}, failure: { (error: APIClientError) in
    // Failure
})

Subclassing

All models are designed as an open class in order to allow subclassing. For example if you wish to send an error to your Slack-Channel you can define a custom class which extends the SlackMessage and handles the conversion from a simple Error to a full SlackMessage.

import PerfectSlackAPIClient

public class SlackErrorMessage: SlackMessage {
    
    public init(error: Error) {
        // Initialize a SlackAttachment
        let attachment = SlackAttachment()
        attachment.title = "An error occured ๐Ÿ™ˆ"
        attachment.color = .danger
        attachment.imageURL = "https://media.giphy.com/media/3og0INyCmHlNylks9O/giphy.gif"
        // Init with localizedDescription and attachment
        super.init(text: error.localizedDescription, attachments: [attachment])
    }
    
    public required init?(map: Map) {
        super.init(map: map)
    }
    
}

Slack Messages API

All properties are fully documented with the Slack Messages API definition. The complete documentation can be found at https://api.slack.com/docs/messages.

Logging

If you wish to enable logging for the SlackAPIClient simply set logging to true.

// Enable logging (willPerformRequest and didRetrieveResponse)
SlackAPIClient.logging = true

Mocking

In order to mock the request and response for the SlackAPIClient under Unit or Integration tests you have to update the environment property of the SlackAPIClient and supply a mocked APIClientResult.

import XCTest
import PerfectSlackAPIClient

class TestClass: XCTestCase {

    override func setUp() {
        super.setUp()
        // Set to tests environment
        // The tests environment uses mockedResult if available
        SlackAPIClient.environment = .tests
    }
    
    override func tearDown() {
        super.tearDown()
        // Reset to default environment
        // The default environment. Performs real network requests
        SlackAPIClient.environment = .default
    }

    func test() {
    	// Set the mockedResult closure to return a mocked APIClientResult
	// When SlackAPIClient performs a request under tests environment
	// The given mocked APIClientResult will be used
    	SlackAPIClient.mockedResult = { (slackAPIClient: SlackAPIClient) in
            switch slackAPIClient {
            case .send:
                let mockedRequest = APIClientRequest(apiClient: slackAPIClient)
                let mockedResponse = APIClientResponse(
			url: slackAPIClient.getRequestURL(), 
			status: .ok, 
			payload: "ok", 
			request: mockedRequest
		)
                return .success(mockedResponse)
            }
        }
        // Your test logic ...
    }

}

Linux Build Notes

Ensure that you have installed libcurl.

sudo apt-get install libcurl4-openssl-dev

Dependencies

PerfectSlackAPIClient is using the following dependencies:

Contributing

Contributions are very welcome ๐Ÿ™Œ ๐Ÿค“

To-Do

  • [ ] Integrate the full Slack API
  • [ ] Improve Linux compatibility

License

MIT License

Copyright (c) 2018 Sven Tiigi

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Github

link
Stars: 8
Help us keep the lights on

Releases

1.1.3 - Jan 20, 2018

In this release all Models have been refactored from struct to open class to allow subclassing.

Subclassing

All models are designed as an open class in order to allow subclassing. For example if you wish to send an error to your Slack-Channel you can define a custom class which extends the SlackMessage and handles the conversion from a simple Error to a full SlackMessage.

import PerfectSlackAPIClient

public class SlackErrorMessage: SlackMessage {
    
    public init(error: Error) {
        // Initialize a SlackAttachment
        let attachment = SlackAttachment()
        attachment.title = "An error occured ๐Ÿ™ˆ"
        attachment.color = .danger
        attachment.imageURL = "https://media.giphy.com/media/3og0INyCmHlNylks9O/giphy.gif"
        // Init with localizedDescription and attachment
        super.init(text: error.localizedDescription, attachments: [attachment])
    }
    
    public required init?(map: Map) {
        super.init(map: map)
    }
    
}

1.1.2 - Jan 15, 2018

According to PerfectAPIClient package update and APIClient protocol changes the SlackAPIClient has been updated

1.1.1 - Jan 12, 2018

Send

As an alternative way of sendind a SlackMessage the object itself has a convienence function send to just send and forget or supply success and failure closure.

// Initialize SlackMessage
let message = SlackMessage(text: "Foo Bar")

// Send and forget
message.send()

// Success and failure closure
message.send(success: { (response: APIClientResponse) in
    // Success
}, failure: { (error: APIClientError) in
    // Failure
})

1.1.0 - Jan 12, 2018

According to Perfect Server Side Swift naming conventions the PerfectSlackAPIClient has been renamed to SlackAPIClient while the package itself remains the name PerfectSlackAPIClient.

1.0.2 - Jan 12, 2018

Added default initializers for all SlackMessage Models