MLDM Monday | SlackR

Agenda

  1. About Slack
  2. Slack bot and Webhook

About Slack

My workflow

  • 善用手機app,推撥通知不漏接
  • TODO list: star and unstar
  • 閱:Add reaction

Free version

  • Search and browse 10k most recent messages
  • 10 service integrations

Slack Integration

  • Incoming Webhooks (一次性POST訊息到slack上)
  • Web API (可以傳圖傳檔、搜歷史記錄)
  • Realtime Message (RTM bot) (監聽channel上的訊息,運算後做出回覆)

Realtime Message R 做不到啦QQ

Incoming Webhooks

In [1]:
library(httr)
In [3]:
url = "https://hooks.slack.com/services/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"
httr::POST(url , 
           body = list(
               channel="#helms-deep",
               text="Siege team ready to charge! Waiting for your order" ), 
           encode = "json")
Out[3]:
Response [https://hooks.slack.com/services/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]
  Date: 2015-10-19 12:09
  Status: 200
  Content-Type: text/html
  Size: 2 B

Web API

In [11]:
library(slackr)

初始設定

In [12]:
slackr_setup(channel="#helms-deep", 
             api_token = "xoxp-12726022931-12726023107-12731895792-fbc7665d3c",
             icon_emoji = ":thumbsup:", username = "data-orc")

傳送數據

In [6]:
damage_report = data.frame(
    seige_team = c(55,66,55), 
    archers  = c(12,34,56), 
    healer=c(11,22,33), 
    row.names = c("injured", "dead", "respawned"))
In [7]:
damage_report
Out[7]:
seige_teamarchershealer
injured551211
dead663422
respawned555633
In [8]:
slackr(damage_report)

傳送圖

In [13]:
barplot(rowSums(damage_report))
dev.slackr("#helms-deep")
Out[13]:
Response [https://slack.com/api/files.upload]
  Date: 2015-10-19 13:00
  Status: 200
  Content-Type: application/json; charset=utf-8
  Size: 1.56 kB

Realtime Message bot

python-rtmbot 目錄結構

python-rtmbot/
├── doc
│   ├── example-config
│   ├── example-init
│   └── example-plugins ------------>範例程式,看過後比較知道怎麼寫
│       ├── canary.py
│       ├── counter.py
│       ├── repeat.py
│       └── todo.py
├── LICENSE.txt
├── plugins ---------------------->自己寫的code放這裡
│   └── warchief
│       └── repeat.py
├── README.md
├── requirements.txt
├── rtmbot.conf ----------------------------------------> token放這
└── rtmbot.py -------------------->主程式

撰寫Plugin範例

python-rtmbot/plugins/warchief/repeat.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

crontable = []
outputs = []


def process_message(data):
    if data['channel'] == 'C0CMFHF7Z' \
            and "text" in data \
            and data['text'].startswith("Warchief"):

        action = data['text'].replace("Warchief, ", "")
        reply = "Roger that! Orcs, let's %s!" % action

        outputs.append([data['channel'], reply])