• This repository has been archived on 04/Jun/2018
  • Stars
    star
    193
  • Rank 201,081 (Top 4 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 9 years ago
  • Updated almost 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A better Slack client, with RTM API support.

PHP Slack API Client

Build Version License Code Coverage Code Quality Downloads

This is an API client for Slack for PHP clients, with support for the Real Time Messaging API (RTM API) using web sockets.

Project status

This project is based on some outdated and unmaintained libraries, and itself is not being actively maintained.

Overview

This library was created primarily for Slackyboy, but was branched off into its own codebase so it could be used in other projects as well. I created this client because existing clients were either too complicated to use, or buggy, or incomplete. This is also the first PHP client I am aware of to support Slack's RTM API.

Installation

Install with Composer, obviously:

$ composer require coderstephen/slack-client

Please note that the current version has unstable dependencies.

In order to install those dependencies, you can set "minimum-stability" in your composer.json, and recommend that you set "prefer-stable":

{
    "minimum-stability": "dev",
    "prefer-stable": true
}

Usage

First, you need to create a client object to connect to the Slack servers. You will need to acquire an API token for your app first from Slack, then pass the token to the client object for logging in. Since this library uses React, you must also pass in an event loop object:

$loop = \React\EventLoop\Factory::create();

$client = new \Slack\ApiClient($loop);
$client->setToken('YOUR-TOKEN-HERE');
// ...
$loop->run();

Assuming your token is valid, you are good to go! You can now use wrapper methods for accessing most of the Slack API. Below is an example of posting a message to a channel as the logged in user:

$client->getChannelById('C025YTX9D')->then(function (\Slack\Channel $channel) use ($client) {
    $client->send('Hello from PHP!', $channel);
});

Advanced messages

Slack supports messages much more rich than plain text through attachments. The easiest way to create a custom message is with a MessageBuilder:

use Slack\Message\{Attachment, AttachmentBuilder, AttachmentField};

$message = $client->getMessageBuilder()
    ->setText('Hello, all!')
    ->setChannel($someChannelObject)
    ->addAttachment(new Attachment('My Attachment', 'attachment text'))
    ->addAttachment(new Attachment('Build Status', 'Build failed! :/', 'build failed', 'danger'))
    ->addAttachment(new AttachmentBuilder()
        ->setTitle('Some Fields')
        ->setText('fields')
        ->setColor('#BADA55')
        ->addField(new AttachmentField('Title1', 'Text', false))
        ->addField(new AttachmentField('Title2', 'Some other text', true))
        ->create()
    ]))
    ->create();

$client->postMessage($message);

Check the API documentation for a list of all methods and properties that messages, attachments, and fields support.

Asynchronous requests and promises

All client requests are made asynchronous using React promises. As a result, most of the client methods return promises. This lets you easily compose request orders and handle them as you need them. Since it uses React, be sure to call $loop->run() or none of the requests will be sent.

React allows the client to perform well and prevent blocking the entire thread while making requests. This is especially useful when writing real-time apps, like Slack chat bots.

Real Time Messaging API

You can also connect to Slack using the Real Time Messaging API. This is often useful for creating Slack bots or message clients. The real-time client is like the regular client, but it enables real-time incoming events. First, you need to create the client:

$client = new \Slack\RealTimeClient();
$client->setToken('YOUR-TOKEN-HERE');
$client->connect();

Then you can use the client as normal; RealTimeClient extends ApiClient, and has the same API for sending requests. You can attach a callback to handle incoming Slack events using RealTimeClient::on():

$client->on('file_created', function($data) {
    echo 'A file was created called ' . $data['file']['name'] . '!\n';
});

Below is a very simple, complete example:

$loop = React\EventLoop\Factory::create();

$client = new Slack\RealTimeClient($loop);
$client->setToken('YOUR-TOKEN-HERE');

// disconnect after first message
$client->on('message', function ($data) use ($client) {
    echo "Someone typed a message: ".$data['text']."\n";
    $client->disconnect();
});

$client->connect()->then(function () {
    echo "Connected!\n";
});

$loop->run();

See the Slack API documentation for a list of possible events.

Documentation

You can view the complete API documentation here.

Running tests

You can run automated unit tests using PHPUnit after installing dependencies:

$ vendor/bin/phpunit

Where to get help

Need help? Just send me an email with your questions. Be sure to add "Slack client" to the message subject line so I know how I can help you out.

License

This library is licensed under the MIT license. See the LICENSE file for details.

More Repositories

1

isahc

The practical HTTP client that is fun to use.
Rust
698
star
2

castaway

Safe, zero-cost downcasting for limited compile-time specialization.
Rust
145
star
3

sluice

Asynchronous byte buffers and pipes for concurrent I/O programming.
Rust
98
star
4

rote

Automate everything.
Rust
67
star
5

threadfin

A thread pool for running multiple tasks on a configurable group of threads.
Rust
50
star
6

tmux-zen

Achieve true terminal zen with tmux and Oh My Fish.
Shell
45
star
7

docker-swarm-deploy-action

Deploy a stack to a remote Docker swarm.
Shell
37
star
8

retest

Command-line regular expression tester
Rust
30
star
9

riptide

The Riptide Programming Language: Shell scripting redesigned.
Rust
29
star
10

stability

Rust API stability attributes for the rest of us.
Rust
26
star
11

slackyboy

A helpful, programmable chat bot for Slack
PHP
22
star
12

dockerfiles

Repository for my public Docker images.
Dockerfile
21
star
13

mathpad

Interactive scratchpad calculator for VS Code
TypeScript
21
star
14

atom-gtk-dark-theme

Toggles the dark theme variant for Atom windows on GTK+3
JavaScript
18
star
15

dotfiles

Dotfiles for my personal UNIX-based machines
Shell
16
star
16

windows-registry

A small library for accessing and manipulating the Windows registry.
PHP
14
star
17

eguikit

A small library of assorted, reusable widgets for egui.
Rust
14
star
18

wakeful

Utilities to aid implementing wakers and working with tasks.
Rust
13
star
19

evflow

Main Evflow event loop library
PHP
12
star
20

respk

Manage resource files using a fast, custom open format designed especially for use in games.
Rust
12
star
21

pushbullet-gnome

[ABANDONED] GNOME extension for sending and receiving Pushbullet notifications
JavaScript
9
star
22

edmunds-sdk

An implementation of an Edmunds SDK for PHP.
PHP
8
star
23

git-pocket

Save and sync uncommitted changes in a working directory
Shell
6
star
24

naru

Cross platform, intuitive file archiver command.
Rust
6
star
25

blog

My personal website and blog.
HTML
5
star
26

appimagezip

Rust implementation of the AppImage specification that uses Zip as the backing image file system.
Rust
5
star
27

fmbq-timer

Timer app tailored for Free Methodist Bible Quizzing
TypeScript
5
star
28

sqs-pull

Move AWS SQS messages from one queue to another quickly with filtering
Rust
4
star
29

walrus

A lightweight compiler for the Decaf programming language
C
4
star
30

robo-ftp

[ABANDONED] FTP(S) task for Robo
PHP
3
star
31

imagen

A random image generator.
Rust
3
star
32

autoclipper

An automatic Evernote article clipper that accepts an article URL
PHP
3
star
33

environ

Simple package for getting environment and platform information. [Unmaintained]
PHP
3
star
34

clogger

Simple console logger that is configurable at runtime for command line apps.
Rust
2
star
35

plugin-termux

Make Termux less broken
Shell
2
star
36

libnntp

Asynchronous implementation of the NNTP news protocol
PHP
2
star
37

android-wakelock

Safe and ergonomic Rust bindings to the Android WakeLock API
Rust
2
star
38

switchbox

[ABANDONED] Quick and extensible configuration library that can load and save in JSON, YAML, INI, and more
PHP
2
star
39

evernote-gnome-client

[ABANDONED] Client for Evernote Web that integrates nicely with GNOME
JavaScript
2
star
40

ingots

Ingots provides a standard interface between Rust web applications and web servers.
Rust
2
star
41

ddns-update

A small utility to update a DNS record with a public IP
C#
1
star
42

cs460-chat-server

Chat server
Python
1
star
43

websnip

Self-hosted web service to save any web article as a clean PDF
Rust
1
star
44

smplinfo

Command-line WAV file metadata reader/writer for samplers
Rust
1
star
45

sagebind

Experiment (ab)using GitHub Actions for syncing social media data
JavaScript
1
star