Collaboration hack with slackbot
PyCon HK 2018 - 2018.11.24
Kei IWASAKI at SQUEEZE Inc.
1 / 63
你好!
2 / 63
Who am I ?
3 / 63
Kei IWASAKI
Web Application/Infrastructure Engineer
working at SQUEEZE Inc in Japan.
From Tokyo, Japan.
Twitter: @laugh_k, Github: @laughk
Co-authors of "スラスラわかるPython"
4 / 63
スラスラわかる Python
surasura wakaru Python
Python Introductory Book in Japanese
5 / 63
My other activities related to Python
in Japan
Python mini hack-a-thon
manthly event in Tokyo
Lecturer of Python ⼊⾨者の集い(hands-on events for Python begginer)
PyCon JP
PyCon JP 2015: LT
PyCon JP 2016: talk speaker
PyCon JP 2017: panel discussion
6 / 63
https://suitebook.io/
7 / 63
Collaboration hack with slackbot
PyCon HK 2018 - 2018.11.24
Kei IWASAKI at SQUEEZE Inc.
8 / 63
Today's sample source code is here
https://github.com/laughk/pyconhk2018-sample-code
9 / 63
Talking about today.
1. About slackbot
2. How to use slackbot?
3. Let's Try slackbot
4. Examples of slackbot
10 / 63
About slackbot
11 / 63
Slack
https://slack.com
Collaboration Platform
Slack allows us to
collaborate with chat on
channels and direct
messages.
12 / 63
About slack"bot"
13 / 63
Bot ?
14 / 63
Chatbot
15 / 63
Slack with bot
Slack is providing bot intergrations.
https://my.slack.com/apps/A0F7YS25R-bots
16 / 63
Slack with bot
You can make a slack bot using RTM API etc.
https://my.slack.com/apps/A0F7YS25R-bots 17 / 63
But, this API is hard to use directly...
18 / 63
All right. There is a nice framework!
19 / 63
slackbot
https://github.com/lins05/slackbot
a slack bot framwork by Python.
20 / 63
Let's Try slackbot
21 / 63
Quick start
install slackbot
$ pip install slackbot
make slackbot_settings.py like below.
API_TOKEN = '<set a bot user token from your slack team>'
DEFAULT_REPLY = 'Hi :raising_hand: I'm Slackbot'
22 / 63
Quick start
make run.py
from slackbot.bot import Bot
def main():
bot = Bot()
bot.run()
if __name__ == '__main__':
main()
run!
$ python run.py
23 / 63
Quick start
invite bot user to your channel
call bot user
24 / 63
Good 👍
25 / 63
Let's Try More !
26 / 63
make custom plugin
add below to slackbot_settings.py
API_TOKEN = '<set a bot user token from your slack team>'
DEFAULT_REPLY = 'Hi :raising_hand: I'm Slackbot'
PLUGINS = [
'plugin'
]
27 / 63
make custom plugin
add below to slackbot_settings.py
API_TOKEN = '<set a bot user token from your slack team>'
DEFAULT_REPLY = 'Hi :raising_hand: I'm Slackbot'
PLUGINS = [
'plugin'
]
28 / 63
make custom plugin
make plugin.py like below
from slackbot.bot import respond_to, listen_to
@respond_to(r'parrots+(.+)')
def parrot(message, word):
message.reply(word)
@listen_to(r'HAHAHA')
def what_is_funny(message):
message.send('What is funny?')
29 / 63
30 / 63
Use the slackbot function below
listen_to
called when a message matching the pattern is sent on a channel/private
channel chat.
response_to
called when a message matching the pattern is sent to the bot.
31 / 63
listen_to
called when a message matching the pattern is sent on a channel/private channel
chat.
@listen_to(r'HAHAHA')
def what_is_funny(message):
message.send('What is funny?')
32 / 63
response_to
called when a message matching the pattern is sent to the bot.
@respond_to(r'parrots+(.+)')
def parrot(message, word):
message.reply(word)
33 / 63
Let's Try More! More!
34 / 63
slackbot x PeeWee(database)
PeeWee
http://docs.peewee-orm.com/en/latest/
simple and small ORM.
35 / 63
Let's make simple memo plugin with
PeeWee 💪
36 / 63
simple memo plugin with PeeWee
make data modeles, as models.py like below.
import os
from peewee import SqliteDatabase, Model, CharField, TextField
db = SqliteDatabase(os.path.join(os.path.dirname(__file__), 'bot_database.db'))
class Memo(Model):
name = CharField(primary_key=True)
text = TextField()
class Meta:
database = db
db.connect()
db.create_tables([Memo], safe=True)
37 / 63
simple memo plugin with PeeWee
add functions to plugin.py like below.
from models import Memo
...
@respond_to(r'memos+saves+(S+)s+(S.*)')
def memo_save(message, name, text):
memo, created = Memo.get_or_create(name=name, text=text)
memo.save()
message.reply(f'I remembered a memo "{name}"')
@respond_to(r'memos+shows+(S+)')
def memo_show(message, name):
memo = Memo.get_or_none(name=name)
if memo:
message.reply(f'memo "{name}" is belown```n{memo.text}n```n')
else:
message.reply(f'memo "{name}" ... hmm ..., I don't know ¯_(ツ)_/¯')
38 / 63
save and show memo
39 / 63
not exits memo
40 / 63
Good 🙌
41 / 63
Try! More! More! More!
42 / 63
slackbot x requests x Web API
43 / 63
slackbot x requests x Web API
requests
http://python-requests.org/
Python HTTP Requests for Humans
44 / 63
Weather API by OpenWeatherMap
https://openweathermap.org/current 45 / 63
Weather API by OpenWeatherMap
https://openweathermap.org/appid
You can get APPID for Free! 46 / 63
$ curl -Ls 
> 'https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=<Your AP
> python -m json.tool
{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 300,
"main": "Drizzle",
"description": "light intensity drizzle",
"icon": "09d"
}
],
-- -- snip -- --
}
47 / 63
Let's make simple weather information
plugin 🌄
48 / 63
make simple weather information plugin
add parameter information to slackbot_setting.py like below
API_TOKEN = '<set a bot user token from your slack team>'
DEFAULT_REPLY = 'Hi :raising_hand: I'm Slackbot'
PLUGINS = [
'plugin'
]
OPENWEATHERMAP_APPID = 'b6******************************' # put Your APPID
you can use a parameter
>>> from slackbot import settings
>>> settings.OPENWEATHERMAP_APPID
b6******************************
49 / 63
make simple weather information plugin
add functions to plugin.py like below.
import json, requests
from slackbot import settings
...
@respond_to(r'weathers+(S+)')
def show_weather(message, city):
url = 'http://api.openweathermap.org/data/2.5/weather'
result = requests.get(
f'{url}?q={city}&appid={settings.OPENWEATHERMAP_APPID}'
)
data_dict = json.loads(result.content.decode())
if result.status_code == 200:
message.reply('nCurrent Weathern'
f'{data_dict["name"]}: {data_dict["weather"][0]["description"]}')
else:
message.reply('Sorry, I could not get weather Information :sob:')
50 / 63
51 / 63
Great!!
52 / 63
Further applications examples
53 / 63
slackbot x AWS
boto3
https://github.com/boto/boto3
AWS SDK for Python.
54 / 63
show ec2 instance information from id
sample code: https://bit.ly/2PLI0Mu
55 / 63
slackbot x Gitbub
PyGithub
https://pygithub.readthedocs.io
Typed interactions with the GitHub API v3
56 / 63
reviewer assign plugin
sample code: https://bit.ly/2Bsii6S
57 / 63
slackbot x Slacker x PeeWee
Slacker
https://github.com/os/slacker
Full-featured Python interface for the Slack API
you can use slack function more than using slackbot (ex. getting slack userid)
58 / 63
Plusplus Plugin
count of Karma
you can Praise the team members!
this source code from pyconjpbot
https://github.com/pyconjp/pyconjpbot/blob/master/pyconjpbot/plugins/pluspl
59 / 63
You can let a slackbot do anything
else you can do with Python
60 / 63
Let's hack your collaboration
with Python !
61 / 63
References
lins05/slackbot: A chat bot for Slack (https://slack.com).
pyconjp/pyconjpbot: Slack bot for PyCon JP Slack
62 / 63
多謝
63 / 63

Collaboration hack with slackbot - PyCon HK 2018 - 2018.11.24

  • 1.
    Collaboration hack withslackbot PyCon HK 2018 - 2018.11.24 Kei IWASAKI at SQUEEZE Inc. 1 / 63
  • 2.
  • 3.
    Who am I? 3 / 63
  • 4.
    Kei IWASAKI Web Application/InfrastructureEngineer working at SQUEEZE Inc in Japan. From Tokyo, Japan. Twitter: @laugh_k, Github: @laughk Co-authors of "スラスラわかるPython" 4 / 63
  • 5.
    スラスラわかる Python surasura wakaruPython Python Introductory Book in Japanese 5 / 63
  • 6.
    My other activitiesrelated to Python in Japan Python mini hack-a-thon manthly event in Tokyo Lecturer of Python ⼊⾨者の集い(hands-on events for Python begginer) PyCon JP PyCon JP 2015: LT PyCon JP 2016: talk speaker PyCon JP 2017: panel discussion 6 / 63
  • 7.
  • 8.
    Collaboration hack withslackbot PyCon HK 2018 - 2018.11.24 Kei IWASAKI at SQUEEZE Inc. 8 / 63
  • 9.
    Today's sample sourcecode is here https://github.com/laughk/pyconhk2018-sample-code 9 / 63
  • 10.
    Talking about today. 1.About slackbot 2. How to use slackbot? 3. Let's Try slackbot 4. Examples of slackbot 10 / 63
  • 11.
  • 12.
    Slack https://slack.com Collaboration Platform Slack allowsus to collaborate with chat on channels and direct messages. 12 / 63
  • 13.
  • 14.
  • 15.
  • 16.
    Slack with bot Slackis providing bot intergrations. https://my.slack.com/apps/A0F7YS25R-bots 16 / 63
  • 17.
    Slack with bot Youcan make a slack bot using RTM API etc. https://my.slack.com/apps/A0F7YS25R-bots 17 / 63
  • 18.
    But, this APIis hard to use directly... 18 / 63
  • 19.
    All right. Thereis a nice framework! 19 / 63
  • 20.
  • 21.
  • 22.
    Quick start install slackbot $pip install slackbot make slackbot_settings.py like below. API_TOKEN = '<set a bot user token from your slack team>' DEFAULT_REPLY = 'Hi :raising_hand: I'm Slackbot' 22 / 63
  • 23.
    Quick start make run.py fromslackbot.bot import Bot def main(): bot = Bot() bot.run() if __name__ == '__main__': main() run! $ python run.py 23 / 63
  • 24.
    Quick start invite botuser to your channel call bot user 24 / 63
  • 25.
  • 26.
    Let's Try More! 26 / 63
  • 27.
    make custom plugin addbelow to slackbot_settings.py API_TOKEN = '<set a bot user token from your slack team>' DEFAULT_REPLY = 'Hi :raising_hand: I'm Slackbot' PLUGINS = [ 'plugin' ] 27 / 63
  • 28.
    make custom plugin addbelow to slackbot_settings.py API_TOKEN = '<set a bot user token from your slack team>' DEFAULT_REPLY = 'Hi :raising_hand: I'm Slackbot' PLUGINS = [ 'plugin' ] 28 / 63
  • 29.
    make custom plugin makeplugin.py like below from slackbot.bot import respond_to, listen_to @respond_to(r'parrots+(.+)') def parrot(message, word): message.reply(word) @listen_to(r'HAHAHA') def what_is_funny(message): message.send('What is funny?') 29 / 63
  • 30.
  • 31.
    Use the slackbotfunction below listen_to called when a message matching the pattern is sent on a channel/private channel chat. response_to called when a message matching the pattern is sent to the bot. 31 / 63
  • 32.
    listen_to called when amessage matching the pattern is sent on a channel/private channel chat. @listen_to(r'HAHAHA') def what_is_funny(message): message.send('What is funny?') 32 / 63
  • 33.
    response_to called when amessage matching the pattern is sent to the bot. @respond_to(r'parrots+(.+)') def parrot(message, word): message.reply(word) 33 / 63
  • 34.
    Let's Try More!More! 34 / 63
  • 35.
  • 36.
    Let's make simplememo plugin with PeeWee 💪 36 / 63
  • 37.
    simple memo pluginwith PeeWee make data modeles, as models.py like below. import os from peewee import SqliteDatabase, Model, CharField, TextField db = SqliteDatabase(os.path.join(os.path.dirname(__file__), 'bot_database.db')) class Memo(Model): name = CharField(primary_key=True) text = TextField() class Meta: database = db db.connect() db.create_tables([Memo], safe=True) 37 / 63
  • 38.
    simple memo pluginwith PeeWee add functions to plugin.py like below. from models import Memo ... @respond_to(r'memos+saves+(S+)s+(S.*)') def memo_save(message, name, text): memo, created = Memo.get_or_create(name=name, text=text) memo.save() message.reply(f'I remembered a memo "{name}"') @respond_to(r'memos+shows+(S+)') def memo_show(message, name): memo = Memo.get_or_none(name=name) if memo: message.reply(f'memo "{name}" is belown```n{memo.text}n```n') else: message.reply(f'memo "{name}" ... hmm ..., I don't know ¯_(ツ)_/¯') 38 / 63
  • 39.
    save and showmemo 39 / 63
  • 40.
  • 41.
  • 42.
    Try! More! More!More! 42 / 63
  • 43.
    slackbot x requestsx Web API 43 / 63
  • 44.
    slackbot x requestsx Web API requests http://python-requests.org/ Python HTTP Requests for Humans 44 / 63
  • 45.
    Weather API byOpenWeatherMap https://openweathermap.org/current 45 / 63
  • 46.
    Weather API byOpenWeatherMap https://openweathermap.org/appid You can get APPID for Free! 46 / 63
  • 47.
    $ curl -Ls > 'https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=<Your AP > python -m json.tool { "coord": { "lon": -0.13, "lat": 51.51 }, "weather": [ { "id": 300, "main": "Drizzle", "description": "light intensity drizzle", "icon": "09d" } ], -- -- snip -- -- } 47 / 63
  • 48.
    Let's make simpleweather information plugin 🌄 48 / 63
  • 49.
    make simple weatherinformation plugin add parameter information to slackbot_setting.py like below API_TOKEN = '<set a bot user token from your slack team>' DEFAULT_REPLY = 'Hi :raising_hand: I'm Slackbot' PLUGINS = [ 'plugin' ] OPENWEATHERMAP_APPID = 'b6******************************' # put Your APPID you can use a parameter >>> from slackbot import settings >>> settings.OPENWEATHERMAP_APPID b6****************************** 49 / 63
  • 50.
    make simple weatherinformation plugin add functions to plugin.py like below. import json, requests from slackbot import settings ... @respond_to(r'weathers+(S+)') def show_weather(message, city): url = 'http://api.openweathermap.org/data/2.5/weather' result = requests.get( f'{url}?q={city}&appid={settings.OPENWEATHERMAP_APPID}' ) data_dict = json.loads(result.content.decode()) if result.status_code == 200: message.reply('nCurrent Weathern' f'{data_dict["name"]}: {data_dict["weather"][0]["description"]}') else: message.reply('Sorry, I could not get weather Information :sob:') 50 / 63
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
    show ec2 instanceinformation from id sample code: https://bit.ly/2PLI0Mu 55 / 63
  • 56.
    slackbot x Gitbub PyGithub https://pygithub.readthedocs.io Typedinteractions with the GitHub API v3 56 / 63
  • 57.
    reviewer assign plugin samplecode: https://bit.ly/2Bsii6S 57 / 63
  • 58.
    slackbot x Slackerx PeeWee Slacker https://github.com/os/slacker Full-featured Python interface for the Slack API you can use slack function more than using slackbot (ex. getting slack userid) 58 / 63
  • 59.
    Plusplus Plugin count ofKarma you can Praise the team members! this source code from pyconjpbot https://github.com/pyconjp/pyconjpbot/blob/master/pyconjpbot/plugins/pluspl 59 / 63
  • 60.
    You can leta slackbot do anything else you can do with Python 60 / 63
  • 61.
    Let's hack yourcollaboration with Python ! 61 / 63
  • 62.
    References lins05/slackbot: A chatbot for Slack (https://slack.com). pyconjp/pyconjpbot: Slack bot for PyCon JP Slack 62 / 63
  • 63.