Python 으로 Slackbot 개발하기

50
협업툴 슬랙(SLACK)으로 실전 챗봇 만들기 ABCD, 한성일 오픈소스진흥협회 파이썬으로 Slack bot 개발해보기
  • Upload

    -
  • Category

    Internet

  • view

    562
  • download

    5

Transcript of Python 으로 Slackbot 개발하기

Page 1: Python 으로 Slackbot 개발하기

�협업툴�슬랙(SLACK)으로�실전�챗봇�만들기

ABCD, 한성일

오픈소스진흥협회

파이썬으로 Slack bot 개발해보기

Page 2: Python 으로 Slackbot 개발하기

0.�챗봇이란?

Page 3: Python 으로 Slackbot 개발하기

챗봇이란?

대신 응답해주는 채팅로봇

인공지능

빅데이터

자연어처리

프로그래밍

나이가�어떻게�되시나요?

텍스트�

음성�

묻지�마세요..

응답요청

Chatbot

머신러닝

Page 4: Python 으로 Slackbot 개발하기

챗봇�예

심심이 페이스북 챗봇

Page 5: Python 으로 Slackbot 개발하기

어디에�쓸까요?

가장 쉽게 떠오르는 곳은 콜 센터입니다.

Page 6: Python 으로 Slackbot 개발하기

또 어디가 있을까요?

물건주문, 호텔예약, 비서…

Page 7: Python 으로 Slackbot 개발하기

생각보다 구현이 간단할지 모릅니다. !!

Page 8: Python 으로 Slackbot 개발하기

1.�챗봇�플로우

Page 9: Python 으로 Slackbot 개발하기

챗봇�프레임웍

http://kitt.ai/ https://dev.botframework.com/

Page 10: Python 으로 Slackbot 개발하기

챗봇�플랫폼

라인 슬렉

텔레그램 페이스북

…..

Page 11: Python 으로 Slackbot 개발하기

일반적인�챗봇�플로우

http://www.lds.com/coepost/enabling-a-smart-user-experience-using-chatbots/

Page 12: Python 으로 Slackbot 개발하기

WEBHOOK

http://blog.restcase.com/webhooks-role-in-the-api-world/

우리의 서버

우리 서버로 클라이언트의 요청을 전달한다.

일반적인 웹개발과 유사

Page 13: Python 으로 Slackbot 개발하기

Slack 의 Webhook에 우리의 서버를 등록한다.

등록된 서버로 유입되는 정보(대화)를 분석한다.

결과를 연결된 클라이언트에게 전달한다.

Page 14: Python 으로 Slackbot 개발하기

2.�파이썬으로�슬렉챗봇�만들기

Page 15: Python 으로 Slackbot 개발하기

선작업

1. 파이썬 설치

https://realpython.com/blog/python/getting-started-with-the-slack-api-using-python-and-flask/

참고

2. 슬랙 커뮤니티 생성

Page 16: Python 으로 Slackbot 개발하기

선작업

heroku 가입이 되어있어야 함

https://heroku.com/

https://devcenter.heroku.com/articles/getting-started-with-nodejs#set-up

heroku CLI 가 설치되어있어야 함

Page 17: Python 으로 Slackbot 개발하기

파이썬 웹서버인 Flask 와 Slack client 를 설치

서버호스팅은 PaaS 서버인 Heroku를 사용

Page 18: Python 으로 Slackbot 개발하기

프로젝트�설정�-�VIRTUAL�ENV

$ mkdir slack-python-chatbot

$ cd slack-python-chatbot

$ virtualenv venv

$ source venv/bin/activate

Page 19: Python 으로 Slackbot 개발하기

서버설정

(venv) $ pip install slackclient

(venv) $ pip install flask

(venv) $ pip install gunicorn

(venv) $ pip freeze > requirements.txt

Page 20: Python 으로 Slackbot 개발하기

test.py�1�(로컬�서버�작동�확인)

#�-*-�coding:�utf-8�-*-�

import�os�

from�flask�import�Flask,�request,�Response�

app�=�Flask(__name__)�

@app.route('/',�methods=['GET'])�

def�test():�

����return�Response('It�works!')�

if�__name__�==�"__main__":�

����app.run(debug=True)

test.py

Page 21: Python 으로 Slackbot 개발하기

test.py�2�(로컬�서버�작동�확인)

(venv)$�python�chatbot.py

Page 22: Python 으로 Slackbot 개발하기

Procfile 파일을 생성 해주세요

heroku 에게 앱을 알려줌

chatbot은 파이썬 파일 네임

web: gunicorn chatbot:app

Procfile�생성

Page 23: Python 으로 Slackbot 개발하기

chatbot.py�1�(챗봇에�사용될�파일)

#�-*-�coding:�utf-8�-*-��import�os�from�flask�import�Flask,�request,�Response�from�slackclient�import�SlackClient�

app�=�Flask(__name__)�

SLACK_WEBHOOK_SECRET�=�os.environ.get('SLACK_WEBHOOK_SECRET')�SLACK_TOKEN�=�os.environ.get('SLACK_TOKEN',�None)�slack_client�=�SlackClient(SLACK_TOKEN)�

def�send_message(channel_id,�message):���slack_client.api_call(�������"chat.postMessage",�������channel=channel_id,�

������text=message,�������username='abcdBot',�������icon_emoji=':monkey_face:'���)

chatbot.py

Page 24: Python 으로 Slackbot 개발하기

chatbot.py�2

@app.route('/webhook',�methods=['POST'])�

def�inbound():�

��username�=�request.form.get('user_name')�

��if�request.form.get('token')�==�SLACK_WEBHOOK_SECRET�and�username�!=�'slackbot':�

����channel_name�=�request.form.get('channel_name')�

����channel_id�=�request.form.get('channel_id')�

����username�=�request.form.get('user_name')�

����text�=�request.form.get('text')�

����inbound_message�=�username�+�"�in�"�+�channel_name�+�"�says:�"�+�text�

����send_message(channel_id,�unicode("따라쟁이�놀이�",�'utf-8')�+�"�"�+�text)�

��return�Response(),�200�

@app.route('/',�methods=['GET'])�

def�test():�

����return�Response('It�works!')�

if�__name__�==�"__main__":�

����app.run(debug=True)

chatbot.py

Page 25: Python 으로 Slackbot 개발하기

Heroku 프로젝트 생성

Page 26: Python 으로 Slackbot 개발하기

HEROKU�프로젝트�생성

$ heroku login

Page 27: Python 으로 Slackbot 개발하기

(venv) $ git init

(venv) $ heroku create

(venv) $ git add .

(venv) $ git commit -m 'init'

(venv) $ git push heroku master

HEROKU�저장소�생성�및�반영

수정 할때마다 배포

.gitignore

.gitignore 파일을 생성해 주세요.

venv/

로컬 저장소 생성

venv 폴더를 git 에서 무시하라

라는 의미

heroku project 가 생성됩니다.

Page 28: Python 으로 Slackbot 개발하기

인증 토큰과 Webhook 토큰을 생성https://dashboard.heroku.com/

Page 29: Python 으로 Slackbot 개발하기

SLACK�토큰생성

https://api.slack.com/web

Page 30: Python 으로 Slackbot 개발하기

SLACK�토큰생성

https://api.slack.com/docs/oauth-test-tokens

Page 31: Python 으로 Slackbot 개발하기

WEBHOOK�설정

https://api.slack.com/outgoing-webhooks

Page 32: Python 으로 Slackbot 개발하기

WEBHOOK

https://abcds.slack.com/apps/new/A0F7VRG6Q-outgoing-webhooks

Page 33: Python 으로 Slackbot 개발하기

INTEGRATION�SETTINGS

https://abcds.slack.com/services/B37GEBQBZ?added=1

heroku 챗봇 프로젝트

URL+ /webhook

사용될 채널

웹훅 토큰

Page 34: Python 으로 Slackbot 개발하기

HEROKU�환경�변수로�토큰�저장

SLACK_TOKEN

SLACK_WEBHOOK_SECRET

Page 35: Python 으로 Slackbot 개발하기

구동화면

Page 36: Python 으로 Slackbot 개발하기

3.�조금�더해보기

Page 37: Python 으로 Slackbot 개발하기

날씨봇

https://darksky.net/dev/

Page 38: Python 으로 Slackbot 개발하기

FORECAST�KEY

Page 39: Python 으로 Slackbot 개발하기

FORECAST�KEY

Heroku 의 settings 에 FORCAST_TOKEN 추가

Page 40: Python 으로 Slackbot 개발하기

(venv) $ pip install python-forecastio

(venv) $ pip freeze > requirements.txt

FORECAST�모듈�설치

Page 41: Python 으로 Slackbot 개발하기

날씨�봇�소스�#1

#�-*-�coding:�utf-8�-*-�import�os�import�forecastio�from�flask�import�Flask,�request,�Response�from�slackclient�import�SlackClient�

app�=�Flask(__name__)�

SLACK_WEBHOOK_SECRET�=�os.environ.get('SLACK_WEBHOOK_SECRET')�SLACK_TOKEN�=�os.environ.get('SLACK_TOKEN',�None)�FORECAST_TOKEN�=�os.environ.get('FORECAST_TOKEN',�None)�slack_client�=�SlackClient(SLACK_TOKEN)�

def�send_message(channel_id,�message):���slack_client.api_call(�������"chat.postMessage",�������channel=channel_id,�������text=message,�������username='abcdBot',�������icon_emoji=':monkey_face:'���)

Page 42: Python 으로 Slackbot 개발하기

날씨�봇�소스�#2

@app.route('/webhook',�methods=['POST'])�def�inbound():���username�=�request.form.get('user_name')���if�request.form.get('token')�==�SLACK_WEBHOOK_SECRET�and�username�!=�'slackbot':�����channel_name�=�request.form.get('channel_name')�����channel_id�=�request.form.get('channel_id')�����username�=�request.form.get('user_name')�����text�=�request.form.get('text')�

����if�text�==�unicode("날씨",�'utf-8'):�������message�=�forecast()�����else:�������message�=�username�+�"�in�"�+�channel_name�+�"�says:�"�+�text�

����send_message(channel_id,�message)���return�Response(),�200

Page 43: Python 으로 Slackbot 개발하기

날씨�봇�소스�#3

def�forecast():���lat�=�37.5124413���lng�=�126.9540519�

��forecast�=�forecastio.load_forecast(FORECAST_TOKEN,�lat,�lng)���byHour�=�forecast.hourly()���return�byHour.summary�

@app.route('/',�methods=['GET'])�def�test():�����return�Response('It�works!')�

if�__name__�==�"__main__":�����app.run(debug=True)

Page 44: Python 으로 Slackbot 개발하기

$ git add .

$ git commit -m 'init'

$ git push heroku master

수정사항을 heroku 에 반영

Page 45: Python 으로 Slackbot 개발하기

날씨앱�테스트

Page 46: Python 으로 Slackbot 개발하기

다양한 확장이 가능합니다.

인공지능, 자연어처리, 음성인식…

Page 47: Python 으로 Slackbot 개발하기

Facebook 챗봇과 노드를 이용한 예제

http://www.slideshare.net/ssusercf5d12/ss-69518853

더해보기

Page 48: Python 으로 Slackbot 개발하기

https://github.com/snowkiwi/slack-python-bot-tutorial

소스는 이곳을 참고하세요.

Page 49: Python 으로 Slackbot 개발하기

Q & A

Page 50: Python 으로 Slackbot 개발하기

수고하셨습니다. :)ABCD http://abcds.kr https://www.facebook.com/groups/562787713823026/

한성일 https://www.facebook.com/jamie.han.16 [email protected]