반응형

[ChatBot] 챗봇 시작해보기

챗봇 시작해보기

  1. 1. 챗봇 시작해보기 파이썬과 노드로 만들어 보는 챗봇 (Slack, facebook..) ABCD, 한성일
  2. 2. 0. 챗봇이란?
  3. 3. 챗봇이란? 고객의 요청을 대신 응답해주는 채팅로봇 인공지능 빅데이터 자연어처리 프로그래밍 나이가 어떻게 되 시나요? 텍스트 음성 … 묻지 마세요.. 응답요청 Chatbot 머신러닝
  4. 4. 챗봇 예 심심이 페이스북 챗봇
  5. 5. 어디에 쓸까요? 가장 쉽게 떠오르는 곳은 콜 센터입니다.
  6. 6. 또 어디가 있을까요? 물건주문, 호텔예약, 비서…
  7. 7. 생각보다 간단할지 모릅니다.
  8. 8. 1. 챗봇 플로우
  9. 9. 챗봇 프레임웍 http://kitt.ai/ https://dev.botframework.com/
  10. 10. 챗봇 플랫폼 라인 슬렉 텔레그램 페이스북
  11. 11. 일반적인 챗봇 플로우 http://www.lds.com/coepost/enabling-a-smart-user-experience-using-chatbots/
  12. 12. 슬랙과 페이스북 API 를 이용해서 챗봇을 만들어보겠습니다. 간단한..
  13. 13. 2. 파이썬으로 슬렉챗봇 만들기
  14. 14. 선작업 1. 파이썬 설치 https://realpython.com/blog/python/getting-started-with-the-slack-api-using-python-and-flask/ 참고 2. 슬랙 커뮤니티 생성
  15. 15. VIRTUAL ENV 설정 $ mkdir abcd-python-slack-bot $ virtualenv venv $ source venv/bin/activate (venv)$ pip install slackclient==1.0.0
  16. 16. 토큰생성 https://api.slack.com/web
  17. 17. 토큰생성 https://api.slack.com/docs/oauth-test-tokens
  18. 18. 토큰을 환경 변수로 지정 (venv)$ export SLACK_TOKEN=‘생성된 토큰'
  19. 19. ngrok 을 이용 외부 오픈 SSL 주소 생성 https://ngrok.com/download (venv)$ ./ngrok http 5000 로컬 서버를 SSL 로 외부 오픈..
  20. 20. WEBHOOK https://api.slack.com/outgoing-webhooks
  21. 21. WEBHOOK https://abcds.slack.com/apps/new/A0F7VRG6Q-outgoing-webhooks
  22. 22. INTEGRATION SETTINGS https://abcds.slack.com/services/B37GEBQBZ?added=1 ngrok 으로 생성된 주소 + /webhook 사용될 채널 웹훅 토큰
  23. 23. WEBHOOK (venv)$ export SLACK_WEBHOOK_SECRET=‘생성된 웹훅 토큰'
  24. 24. FLASK 설치 (venv)$ pip install flask
  25. 25. RECEIVE.PY # -*- 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:' ) @app.route('/webhook', methods=['POST']) def inbound(): print("get " + request.form.get('token')) print("username " + request.form.get('user_name')) 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) print(inbound_message) return Response(), 200 @app.route('/', methods=['GET']) def test(): return Response('It works!') if __name__ == "__main__": app.run(debug=True) receive.py
  26. 26. RECEIVE.PY (venv)$ python receive.py
  27. 27. 구동화면
  28. 28. 실제 서버를 설정해서 포팅해봅시다.
  29. 29. 3. 노드로 페이스북 챗봇 만들기 (HEROKU)
  30. 30. 선작업 http://x-team.com/2016/04/how-to-get-started-with-facebook-messenger-bots/ nodejs 설치 참고 https://nodejs.org/ko/download/
  31. 31. 선작업 heroku 가입이 되어있어야 함 https://heroku.com/ https://devcenter.heroku.com/articles/getting-started-with-nodejs#set-up heroku CLI 가 설치되어있어야 함
  32. 32. 프로젝트 생성 $ mkdir abcd-node-bot $ cd abcd-node-bot/ $ npm init $ npm install express body-parser request --save { "name": "testbot", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo "Error: no test specified" && exit 1", "start": "node index.js" }, "author": "", "license": "ISC", "dependencies": { "body-parser": "^1.15.2", "express": "^4.14.0", "request": "^2.79.0" } }
  33. 33. express 설치 $ npm install express body-parser request --save
  34. 34. INDEX.JS 생성 index.js 생성 var express = require('express'); var bodyParser = require('body-parser'); var request = require('request'); var app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.listen((process.env.PORT || 3000)); // Server frontpage app.get('/', function (req, res) {     res.send('잘돈다.'); }); // Facebook Webhook app.get('/webhook', function (req, res) { console.log(req.query['hub.verify_token']); if (req.query['hub.verify_token'] === 'abcd_verify_token') { // webhook 설정에 입력된 토큰 res.send(req.query['hub.challenge']); } else { res.send('Invalid verify token'); } }); node index.js
  35. 35. HEROKU 생성 $ heroku login
  36. 36. 로컬 GIT 설정 $ git init $ heroku create $ git add . $ git commit -m ‘ABCD 노드 봇 첫번째 커밋' $ git push heroku master .gitignore node_modules
  37. 37. 작동확인 https://warm-spire-76279.herokuapp.com/
  38. 38. 페이스북 페이지 만들기 https://www.facebook.com/pages/create/
  39. 39. 페이지 생성 완료
  40. 40. 앱생성 https://developers.facebook.com/quickstarts/ 기본설정으로 앱생성
  41. 41. 제품추가
  42. 42. 토큰생성
  43. 43. 토큰생성
  44. 44. WEB HOOK 설정 https://developers.facebook.com/ heroku 경로
  45. 45. WEB HOOK 설정 페이지를 선택해주세요!
  46. 46. WEBHOOK 설정
  47. 47. PAGE_ACCESS_TOKEN 설정 PAGE_ACCESS_TOKEN
  48. 48. 토큰 유효성 확인 https://warm-spire-76279.herokuapp.com/webhook? hub.verify_token=abcd_verify_token
  49. 49. 따라하기 봇 테스트
  50. 50. KITTEN https://placekitten.com/ kitten 300 200
  51. 51. 따라하기 & 키튼 봇 소스 1 var express = require('express'); var bodyParser = require('body-parser'); var request = require('request'); var app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.listen((process.env.PORT || 3000)); // Server frontpage app.get('/', function (req, res) { res.send('This is TestBot Server'); }); // Facebook Webhook app.get('/webhook', function (req, res) { console.log(req.query['hub.verify_token']); if (req.query['hub.verify_token'] === 'abcd_verify_token') { // webhook 설정에 입력된 토큰 res.send(req.query['hub.challenge']); } else { res.send('Invalid verify token'); } });
  52. 52. 따라하기 & 키튼 봇 소스 2 // handler receiving messages app.post('/webhook', function (req, res) { var events = req.body.entry[0].messaging; for (i = 0; i < events.length; i++) { var event = events[i]; if (event.message && event.message.text) { if (!kittenMessage(event.sender.id, event.message.text)) { sendMessage(event.sender.id, {text: event.message.text}); } } else if (event.postback) { console.log("Postback received: " + JSON.stringify(event.postback)); } } res.sendStatus(200); }); // generic function sending messages function sendMessage(recipientId, message) { request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token: process.env.PAGE_ACCESS_TOKEN}, method: 'POST', json: { recipient: {id: recipientId}, message: message, } }, function(error, response, body) { if (error) { console.log('Error sending message: ', error); } else if (response.body.error) { console.log('Error: ', response.body.error); } }); };
  53. 53. 따라하기 & 키튼 봇 소스 3 // send rich message with kitten function kittenMessage(recipientId, text) { text = text || ""; var values = text.split(' '); if (values.length === 3 && values[0] === 'kitten') { if (Number(values[1]) > 0 && Number(values[2]) > 0) { var imageUrl = "https://placekitten.com/" + Number(values[1]) + "/" + Number(values[2]); message = { "attachment": { "type": "template", "payload": { "template_type": "generic", "elements": [{ "title": "Kitten", "subtitle": "Cute kitten picture", "image_url": imageUrl , "buttons": [{ "type": "web_url", "url": imageUrl, "title": "Show kitten" }, { "type": "postback", "title": "I like this", "payload": "User " + recipientId + " likes kitten " + imageUrl, }] }] } } }; sendMessage(recipientId, message); return true; } } return false; };
  54. 54. 4. 조금 더해보기
  55. 55. 더하기봇
  56. 56. 더하기 봇 소스 #1 var express = require('express'); var bodyParser = require('body-parser'); var request = require('request'); var app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.listen((process.env.PORT || 3000)); // Server frontpage app.get('/', function (req, res) { res.send('This is TestBot Server'); }); app.get('/forecast', function (req, res) { forecast.get([35.9335, 139.6181], function(err, weather) { if(err) return console.dir(err); console.dir(weather); console.dir(weather.latitude); console.log("weather.latitude " + weather.latitude); console.log("오늘 " + weather.timezone + "의 날씨는 " + weather.currently.summary + "입니다. "); }); res.send('forecast'); });
  57. 57. 더하기 봇 소스 #2 // Facebook Webhook app.get('/webhook', function (req, res) { if (req.query['hub.verify_token'] === 'abcd_verify_token') { res.send(req.query['hub.challenge']); } else { res.send('Invalid verify token'); } }); // handler receiving messages app.post('/webhook', function (req, res) { var events = req.body.entry[0].messaging; for (i = 0; i < events.length; i++) { var event = events[i]; if (event.message && event.message.text) { addMessage(event.sender.id, event.message.text); } } res.sendStatus(200); });
  58. 58. 더하기 봇 소스 #3 // generic function sending messages function sendMessage(recipientId, message) { request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token: process.env.PAGE_ACCESS_TOKEN}, method: 'POST', json: { recipient: {id: recipientId}, message: message, } }, function(error, response, body) { if (error) { console.log('Error sending message: ', error); } else if (response.body.error) { console.log('Error: ', response.body.error); } }); }; function addMessage(recipientId, text) { text = text || ""; var values = text.split(' '); if (values.length === 3 && values[0] === 'add') { if (Number(values[1]) > 0 && Number(values[2]) > 0) { addText = values[1] + " + " + values[2] + " = " + (Number(values[1]) + Number(values[2])); message = {text: addText}; sendMessage(recipientId, message); } } };
  59. 59. FORECAST 설치 $ npm install --save forecast
  60. 60. 날씨봇 https://darksky.net/dev/
  61. 61. FORECAST KEY
  62. 62. 날씨앱 테스트
  63. 63. 날씨 봇 소스 #1 var express = require('express'); var bodyParser = require('body-parser'); var request = require('request'); var app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.listen((process.env.PORT || 3000)); var Forecast = require('forecast'); // Initialize var forecast = new Forecast({ service: 'darksky', key: ‘your-api-key‘, units: 'celcius', cache: true, // Cache API requests ttl: { minutes: 27, seconds: 45 } });
  64. 64. 날씨 봇 소스 #2 // Server frontpage app.get('/', function (req, res) { res.send('This is TestBot Server'); }); app.get('/forecast', function (req, res) { forecast.get([35.9335, 139.6181], function(err, weather) { if(err) return console.dir(err); console.dir(weather); }); res.send('forecast'); }); // Facebook Webhook app.get('/webhook', function (req, res) { if (req.query['hub.verify_token'] === 'abcd_verify_token') { res.send(req.query['hub.challenge']); } else { res.send('Invalid verify token'); } });
  65. 65. 날씨 봇 소스 #3 // handler receiving messages app.post('/webhook', function (req, res) { var events = req.body.entry[0].messaging; for (i = 0; i < events.length; i++) { var event = events[i]; if (event.message && event.message.text) { weatherMessage(event.sender.id, event.message.text); } } res.sendStatus(200); }); // generic function sending messages function sendMessage(recipientId, message) { request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token: process.env.PAGE_ACCESS_TOKEN}, method: 'POST', json: { recipient: {id: recipientId}, message: message, } }, function(error, response, body) { if (error) { console.log('Error sending message: ', error); } else if (response.body.error) { console.log('Error: ', response.body.error); } }); };
  66. 66. 날씨 봇 소스 #4 function weatherMessage(recipientId, text){ text = text || ""; var values = text.split(' '); if (values[0] === '날씨') { forecast.get([35.9335, 139.6181], function(err, weather) { console.log(weather); weatherText = "오늘 " + weather.timezone + "의 날씨는 " + weather.currently.summary + "입니다. "; message = {text: weatherText}; sendMessage(recipientId, message); }); } }
  67. 67. 더하기와 날씨봇을 확장해 보세요.
  68. 68. 또 어떤걸 해보고 싶으신가요? 머신러닝, 자연어처리, 음성인식…
  69. 69. 파이썬 https://github.com/snowkiwi/slack-python-bot-tutorial 소스는 이곳을 참고하세요. 노드 https://github.com/snowkiwi/facebook-node-bot
  70. 70. Q & A
  71. 71. 수고하셨습니다. :) ABCD http://abcds.kr 


...

반응형
반응형

[Chatbot] 20170227 파이썬으로 챗봇_만들기





...

반응형
반응형

[Chatbot] 챗봇 개발을 위한 네이버 랩스 api





...

반응형
반응형

[ChatBot] 마이크로소프트 봇 프레임워크로 만드는 인공지능 봇






...

반응형
반응형

30분 안에 챗봇 만들기 

- #1 https://brunch.co.kr/@chris-song/28



lang : python

Bot Platform : Bot Framework(https://dev.botframework.com/) or api.ai(https://api.ai/) or (https://chatfuel.com/)

Messenger : Facebook Messenger, Telegram, Slack, 아무거나 


- #2 https://brunch.co.kr/@chris-song/29  - https://youtu.be/OPIE74jg7S8


사용해볼 프레임워크 

- Bot Framework

- Cognitive Service API


개발 언어 

- Python


Python 라이브러리

- microsoftbotframework


API 서버

- Heroku App


선행 조건(Prerequisites)

- Heroku 계정

- github 계정

- Azure 계정

- Facebook 계정

 

...    

반응형
반응형

스레드(thread)는 어떠한 프로그램 내에서, 특히 프로세스 내에서 실행되는 흐름의 단위를 말한다. 일반적으로 한 프로그램은 하나의 스레드를 가지고 있지만, 프로그램 환경에 따라 둘 이상의 스레드를 동시에 실행할 수 있다. 이러한 실행 방식을 멀티스레드(multithread)라고 한다.


멀티스레딩(multithreading) 컴퓨터는 여러 개의 스레드를 효과적으로 실행할 수 있는 하드웨어 지원을 갖추고 있다. 이는 스레드가 모두 같은 주소 공간에서 동작하여 하나의 CPU 캐시 공유 집합과 하나의 변환 색인 버퍼 (TLB)만 있는 멀티프로세서 시스템 (멀티 코어 시스템)과는 구별한다. 그러므로 멀티스레딩은 프로그램 안에서 병렬 처리의 이점을 맛볼 수 있지만 멀티프로세싱 시스템은 여러 개의 프로그램들을 병렬로 처리할 수 있다. 멀티프로세싱 시스템이 여러 개의 완전한 처리 장치들을 포함하는 반면 멀티스레딩은 스레드 수준뿐 아니라 명령어 수준의 병렬 처리에까지 신경을 쓰면서 하나의 코어에 대한 이용성을 증가하는 것에 초점을 두고 있다.


챗봇에서 웹으로 접속 했을때, 

node.js 로 챗팅 만들었을때와 다르게 바로 멀티쓰레드 진행됨. 

실행한 웹 페이지마다 다른 응답을 보여주었다. 


어떻게 멀티쓰레드가 되는건지원... 


https://github.com/bwilcox-1234/ChatScript/blob/master/SRC/evserver/ev.pod



...

반응형
반응형

챗봇 설계시 고려 사항  http://story.pxd.co.kr/m/1250

챗봇의 기능을 명확히 인지할 수 있어야 한다.

챗봇을 통한 정보 탐색은 대화 흐름에 따라 이루어지기 때문에 시작 과정이 매우 중요합니다. 챗봇을 통한 정보 탐색이 편리하더라도 챗봇이 제공하는 기능을 사용자가 인지하지 못하면 챗봇의 정보 탐색 자체가 이루어지지 않을 수 있습니다. 이번에 설계한 챗봇은 챗봇 정보 탐색 흐름을 체험할 수 있도록 첫 진입 시 챗봇 안내에 따라 기능을 직접 사용하는 체험 튜토리얼을 제공했습니다.

정보 탐색 과정에서 챗봇과의 대화 흐름이 끊기지 않도록 언제든 탐색 과정 중 새로운 정보를 탐색할 수 있는 구조로 설계했습니다. 재진입 시 튜토리얼 없이 챗봇 대화가 어렵지 않도록 키워드를 추천하여 챗봇이 전달할 정보에 대한 가이드라인을 제공합니다.


사용자가 예측한 답변을 제공해야 한다.

동문서답하는 사람과 대화를 지속하기 어렵듯 챗봇과의 대화를 지속시키려면  챗봇은 사용자의 질문에 맞는 적절한 대답을 해야 합니다. 사용자가 채팅창에 키워드를 입력하고 나서 기대한 대답을 계속 얻지 못하면 그 챗봇과는 대화를 지속하기 어려울 것입니다. 응답 가능 범위가 좁은 우리 챗봇이 바보처럼 느껴지지 않게 챗봇이 응답 가능한 영역에서 키워드를 입력하도록 설계했습니다. 그리고 챗봇 대화 시 특정 정보 탐색을 위한 입력 영역을 제공하여 특정 범위 내의 키워드 입력을 유도했습니다.


기존의 정보 탐색 과정보다 편리해야 한다.

요약 정보 > 상세 정보 확인 과정에서 상세 정보 확인 시 사용자가 반복적으로 입력해야 하는 키워드가 있었습니다. 화면 진입보다 정보 탐색 과정이 편리하려면 반복적으로 수행해야 하는 키워드 입력을 줄여야 했습니다. 처음 요약 정보를 확인할 키워드는 사용자가 직접 입력하되, 상세 정보를 보고 싶은 항목들은 선택지를 통해 확인하도록 설계했습니다. 또, 한 화면에서 사용자가 원하는 정보를 한눈에 확인할 수 있도록 제공되는 선택지의 영역을 최소화했습니다.

반응형
반응형

리더들은 아침마다 다음과 같은 질문들을 스스로에게 해야 한다.

‘나는 어떤 세계에 살고 있는가.’

‘가장 큰 트렌드는 어떤 게 있나.’

‘우리 회사 사람들이 트렌드로부터 최상의 이익을 얻어 번창하고

최악의 결과를 피하려면 무엇을 해야 하는가.’

- 토머스 프리드만 


변화가 느린 세상에서는 자칫 길을 잘못 들어도

궤도를 수정해 가면됩니다.

오늘처럼 급속한 변화의 시대엔 세상의 변화 방향을

놓치면 조직의 미래는 보장할 수 없습니다.

리더의 마지막 책임은 조직의 생존을 지켜내는 일입니다.

리더가 한순간도 방심할 수 없는 이유가 여기 있습니다.



...

반응형

+ Recent posts