• This repository has been archived on 15/Aug/2022
  • Stars
    star
    680
  • Rank 66,440 (Top 2 %)
  • Language
    Python
  • License
    MIT License
  • Created almost 10 years ago
  • Updated almost 3 years ago

Reviews

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

Repository Details

A framework for receiving and interacting with events from Slack's RTM API

python-rtmbot

This project is no longer under active development. If youโ€™re just getting started, we recommend taking a look at the Python SDK first. If youโ€™ve been using this project, only critical issues (such as security issues) will be addressed, but we advise planning to migrate to the Python SDK. You can still file an issue and ask us for help doing that!

๐Ÿ’ก If youโ€™re interested in maintaining this package in the future, please get in touch

Build Status Coverage Status

A Slack bot written in Python that connects via the RTM API.

Python-rtmbot is a bot engine. The plugins architecture should be familiar to anyone with knowledge of the Slack API and Python. The configuration file format is YAML.

This project is currently pre-1.0. As such, you should plan for it to have breaking changes from time to time. For any breaking changes, we will bump the minor version while we are pre-1.0. (e.g. 0.2.4 -> 0.3.0 implies breaking changes). If stability is important, you'll likely want to lock in a specific minor version)

Some differences to webhooks:

  1. Doesn't require a webserver to receive messages
  2. Can respond to direct messages from users
  3. Logs in as a slack user (or bot)
  4. Bot users must be invited to a channel

Dependencies

Installation

  1. Create your project
        mkdir myproject
        cd myproject
  1. Install rtmbot (ideally into a virtualenv)
        pip install rtmbot
  1. Create an rtmbot.conf file and create a bot for your team
        # Add the following to rtmbot.conf
        DEBUG: True # make this False in production
        SLACK_TOKEN: "xoxb-11111111111-222222222222222"
        ACTIVE_PLUGINS:
            - plugins.repeat.RepeatPlugin

DEBUG will adjust logging verbosity and cause the runner to exit on exceptions, generally making debugging more pleasant.

SLACK_TOKEN is needed to authenticate with your Slack team.

ACTIVE_PLUGINS RTMBot will attempt to import any Plugin specified in ACTIVE_PLUGINS (relative to your python path) and instantiate them as plugins. These specified classes should inherit from the core Plugin class.

For example, if your python path includes '/path/to/myproject' and you include plugins.repeat.RepeatPlugin in ACTIVE_PLUGINS, it will find the RepeatPlugin class within /path/to/myproject/plugins/repeat.py and instantiate it, then attach it to your running RTMBot.

A Word on Structure

To give you a quick sense of how this library is structured, there is a RtmBot class which does the setup and handles input and outputs of messages. It will also search for and register Plugins within the specified directory(ies). These Plugins handle different message types with various methods and can also register periodic Jobs which will be executed by the Plugins.

RtmBot
โ”œโ”€โ”€ Plugin
|      โ”œโ”€โ”€ Job
|      โ””โ”€โ”€ Job
โ”œโ”€โ”€ Plugin
โ””โ”€โ”€ Plugin
       โ””โ”€โ”€ Job

Add Plugins

Plugins can live within any python module, but we recommend just putting them in ./plugins. (Don't forget to add an __init__.py file to your directory to make it a module -- use touch __init__.py within your plugin directory to create one)

To add a plugin, create a file within your plugin directory (./plugins is a good place for it).

    mkdir plugins
    touch plugins/__init__.py
    cd plugins
    vi myplugin.py

Add your plugin content into this file. Here's an example that will just print all of the requests it receives to the console. See below for more information on available methods.

    from __future__ import print_function
    from rtmbot.core import Plugin

    class MyPlugin(Plugin):

        def catch_all(self, data):
            print(data)

You can install as many plugins as you like, and each will handle every event received by the bot independently.

To create an example 'repeat' plugin:

Open plugins/repeat.py

Add the following:

    from __future__ import print_function
    from __future__ import unicode_literals

    from rtmbot.core import Plugin


    class RepeatPlugin(Plugin):

        def process_message(self, data):
            if data['channel'].startswith("D"):
                self.outputs.append(
                    [data['channel'], 'from repeat1 "{}" in channel {}'.format(
                        data['text'], data['channel']
                    )]
                )

The repeat plugin will now be loaded by the bot on startup. Run rtmbot from console to start your RtmBot.

    rtmbot

Create Plugins

Incoming data

All events from the RTM websocket are sent to the registered plugins. To act on an event, create a function definition, inside your Plugin class, called process_(api_method) that accepts a single arg for data. For example, to handle incoming messages:

    def process_message(self, data):
        print data

This will print the incoming message json (dict) to the screen where the bot is running.

Plugins having a method defined as catch_all(self, data) will receive ALL events from the websocket. This is useful for learning the names of events and debugging.

For a list of all possible API Methods, look here: https://api.slack.com/rtm

Note: If you're using Python 2.x, the incoming data should be a unicode string, be careful you don't coerce it into a normal str object as it will cause errors on output. You can add from __future__ import unicode_literals to your plugin file to avoid this.

Outgoing data

RTM Output

Plugins can send messages back to any channel or direct message. This is done by appending a two item array to the Plugin's output array (myPluginInstance.output). The first item in the array is the channel or DM ID and the second is the message text. Example that writes "hello world" when the plugin is started:

    class myPlugin(Plugin):

        def process_message(self, data):
            self.outputs.append(["C12345667", "hello world"])
SlackClient Web API Output

Plugins also have access to the connected SlackClient instance for more complex output (or to fetch data you may need).

    def process_message(self, data):
        self.slack_client.api_call(
            "chat.postMessage", channel="#general", text="Hello from Python! :tada:",
            username="pybot", icon_emoji=":robot_face:"

Timed jobs

Plugins can also run methods on a schedule. This allows a plugin to poll for updates or perform housekeeping during its lifetime. Jobs define a run() method and return any outputs to be sent to channels. They also have access to a SlackClient instance that allows them to make calls to the Slack Web API.

For example, this will print "hello world" every 10 seconds. You can output multiple messages to the same or different channels by passing multiple pairs of [Channel, Message] combos.

    from rtmbot.core import Plugin, Job


    class myJob(Job):

        def run(self, slack_client):
            return [["C12345667", "hello world"]]


    class myPlugin(Plugin):

        def register_jobs(self):
            job = myJob(10)
            self.jobs.append(job)

Plugin misc

The data within a plugin persists for the life of the rtmbot process. If you need persistent data, you should use something like sqlite or the python pickle libraries.

More Repositories

1

python-slack-sdk

Slack Developer Kit for Python
Python
3,840
star
2

node-slack-sdk

Slack Developer Kit for Node.js
TypeScript
3,270
star
3

bolt-js

A framework to build Slack apps using JavaScript
TypeScript
2,736
star
4

hubot-slack

Slack Developer Kit for Hubot
CoffeeScript
2,300
star
5

bolt-python

A framework to build Slack apps using Python
Python
1,053
star
6

slack-github-action

Send data into Slack using this GitHub Action!
JavaScript
953
star
7

java-slack-sdk

Slack Developer Kit (including Bolt for Java) for any JVM language
Java
573
star
8

python-slack-events-api

Slack Events API adapter for Python (Flask required)
Python
342
star
9

Slack-Python-Onboarding-Tutorial

a simple python onboarding bot and tutorial for Slack
Python
251
star
10

slack-api-specs

Open API specifications for platform products by Slack
220
star
11

steno

๐Ÿ“ผ Slack app testing companion - Record and Replay your HTTP requests, both incoming and outgoing
TypeScript
184
star
12

deno-slack-sdk

SDK for building Run on Slack apps using Deno
TypeScript
160
star
13

template-slash-command-and-dialogs

Sample Slack app that uses a Slash Command and interactive message to create helpdesk tickets
JavaScript
141
star
14

node-slack-interactive-messages

Slack Buttons, Menus, and Dialogs made simpler for Node
JavaScript
133
star
15

build-this-bot-workshop

Learn how to build a bot on Slack using Python
127
star
16

reacjilator

A translation bot that translates a message when a user reacted with an emoji ๐Ÿ‡จ๐Ÿ‡ณ ๐Ÿ‡ฎ๐Ÿ‡น ๐Ÿ‡น๐Ÿ‡ญ ๐Ÿ‡ซ๐Ÿ‡ท ๐Ÿ‡ฏ๐Ÿ‡ต ๐Ÿ‡ฎ๐Ÿ‡ณ ๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿ‡ง๐Ÿ‡ฌ ๐Ÿ‡น๐Ÿ‡ผ ๐Ÿ‡ฆ๐Ÿ‡ช ๐Ÿ‡ฐ๐Ÿ‡ท
JavaScript
110
star
17

onboarding-example

A demonstration of how to build an onboarding app using Slack's Events API
JavaScript
99
star
18

node-tasks-app

Tasks App is a sample Task Management app built on the Slack Platform.
JavaScript
98
star
19

python-message-menu-example

A tutorial for adding Slack message menus to your Python app
Python
97
star
20

slack-platform-assets

Images, templates, and Sketch files to aid designing and presenting your Slack apps
94
star
21

node-slack-events-api

Slack Events API for Node
JavaScript
93
star
22

sample-message-menus-node

An example Slack app that demonstrates use of message menus
JavaScript
91
star
23

python-dialog-example

An example app to demonstrate Slack dialogs
Python
77
star
24

template-announcement-approvals

Sample Slack app that uses the Events API and interactive message to implement an approvals workflow
JavaScript
74
star
25

Slack-Ruby-Onboarding-Tutorial

An example Slack bot written in Ruby
Ruby
64
star
26

bolt-js-getting-started-app

Getting Started Slack app using โšก๏ธ Bolt for JavaScript
JavaScript
54
star
27

sample-app-unfurls

An example Slack app that demonstrates use of App Unfurls
JavaScript
45
star
28

app-interaction-patterns

A collection of common workflows and interaction patterns for Slack apps.
41
star
29

oauth-tutorial

Slack OAuth setup tutorial using a simple slash command bot
JavaScript
39
star
30

template-triage-bot

Triage Channel Stats w/ Bolt for JS & Shortcuts โšก๏ธ
JavaScript
39
star
31

template-actionable-notifications

Sample Slack app to illustrate how incoming webhooks and interactive messages can be used to build a helpdesk integration
JavaScript
35
star
32

deno-slack-api

Slack API Client for Deno Run on Slack projects
TypeScript
35
star
33

template-terms-of-service

Sample Slack app that uses the Events API and interactive messages to send new users a Terms of Service or welcome message
JavaScript
35
star
34

app-directory-assets

A collection of design assets to help build an app directory submission
34
star
35

template-incident-management

A sample of managing incidents via Slack
TypeScript
34
star
36

template-channel-webhooks

Sample Slack app that uses a Bot to create per-channel webhooks
JavaScript
31
star
37

TalkBot

Building a Twilio-powered Slack bot with Node.js
JavaScript
30
star
38

python-slack-discovery-sdk

This project aims to make using Slack's Discovery APIs easier.
Python
28
star
39

template-channel-naming

Sample Slack app that uses the Events API and interactive message to help enforce channel naming conventions
JavaScript
28
star
40

workflow-powerups

TypeScript
27
star
41

template-action-and-dialog

A sample Slack app "ClipIt", which allows user to clip a message using a message action
JavaScript
27
star
42

sample-message-menus-ruby

An example Slack app in Ruby that demonstrates use of message menus
Ruby
23
star
43

definition-app

A Slack app for storing and accessing company specific phrases
TypeScript
23
star
44

template-account-binding

A sample Slack app that shows you how to bind a Slack user to a user on another system
JavaScript
22
star
45

admin_app_management

Sample application to manage your applications within a Slack organization
TypeScript
20
star
46

pycon-2018

Sample app for Pycon 2018 Slack app workshop
Python
15
star
47

slack-reporting-tool

A Slack app to help administer workspaces by letting team members report offensive messages
TypeScript
15
star
48

deno-slack-runtime

Helper library for running a Run on Slack Deno function
TypeScript
13
star
49

pycon-2019

Pycon 2019 Workshop
Python
12
star
50

deno-slack-hooks

Helper library implementing the contract between the Slack CLI and Slack application SDKs
TypeScript
11
star
51

python-link-button-example

An example app using Slack link buttons and deep links
Python
10
star
52

deno-slack-hub

Connectors used to build coded workflows for Run on Slack apps using Deno
TypeScript
9
star
53

deno-slack-builder

Library for building a Run on Slack Deno project.
TypeScript
9
star
54

bolt-examples-aws-re-invent-2020

A collection of examples to get started with deploying modern โšก๏ธ Slack apps to AWS Lambda and Amazon Lightsail containers
Java
8
star
55

WeAreDevs

WeAreDevelopers Slack Workshop
Python
7
star
56

manifest-schema

Provide JSON schemas that define Slack's manifest.json file
Python
6
star
57

python-slack-hooks

Helper library implementing the contract between the Slack CLI and Bolt for Python
Python
5
star
58

template-message-linking

Sample Slack APP that uses the Events API to link to a conversation happening in one channel to another
JavaScript
5
star
59

bolt-python-getting-started-app

Getting Started Slack app using โšก๏ธ Bolt for Python
Python
4
star
60

easy-peasy-bot-custom-integration

DEPRECATED use https://github.com/slackapi/easy-peasy-bot instead
JavaScript
3
star
61

sample-incident-management

JavaScript
3
star
62

sample-code-index

An index of the most up-to-date sample code created by the Slack team
3
star
63

slack-health-score

A GitHub Action to report software project health score
JavaScript
3
star
64

deno-simple

TypeScript
2
star
65

deno-reverse-string

TypeScript
2
star
66

slack-app-time-off

Time-Off Request sample app for Slack's Next Generation Platform
TypeScript
1
star
67

deno-metadata-event

TypeScript
1
star
68

sunny-picnics

๐ŸŒค๐ŸŒณ๐ŸŒป๐Ÿงบ๐Ÿœ๐Ÿ‘’
1
star
69

deno-budget-calculator

TypeScript
1
star
70

deno-environment-variables

TypeScript
1
star
71

deno-testing-functions

TypeScript
1
star
72

template-ts-clip-message

TypeScript
1
star
73

slack-connect-sample

A sample app which shows off the functionality of the Slack Connect APIs.
JavaScript
1
star
74

deno-slack-protocols

Implements the rules for communication between Slack CLI and any Slack app development SDKs
TypeScript
1
star