반응형

[Chatbot] Chatfuel - Build a Facebook bot without coding


https://chatfuel.com/


개인이 직접 페이스북 메신저 챗봇을 만들 수 있는 챗봇 빌더, 


역시 챗봇은 기술이 아니라 컨텐츠가 쟁점. 


10분만에 Chatful을 이용하여 챗봇 만들기


Learn how to create a chatbot with AI navigation just in 10 minutes using Chatfuel.


Visit us here: https://chatfuel.com/


Chatfuel — the intuitive bot builder with AI navigation. Use it to create your own chatbot without any coding skills. 



...

반응형
반응형

[ChatBot] RiveScript - test https://play.rivescript.com/s/F12LdIGLZI


계속 ChatScript 만 해오다가 뭔가 한글에서 진행이 안되서 RiveScript로 진행해보려 한다. 


https://www.rivescript.com/try 에서 테스트 해볼수 있다. 


https://play.rivescript.com/ 에선 직접 입력해서 테스트 한다. 


한글되는지 해보려고 https://play.rivescript.com/s/F12LdIGLZI 해봄. 

아래에 utf-8 체크하니까 오류 안나고 잘 됨. 



한글입력 후 RUN 하니까 Alert 발생


UTF-8 체크 후 RUN 하니까 이상없음.


반응형
반응형

twitter-korean-text - 트위터에서 만든 오픈소스 한국어 처리기


https://github.com/twitter/twitter-korean-text



트위터에서 만든 오픈소스 한국어 처리기

Scala/Java library to process Korean text with a Java wrapper. twitter-korean-text currently provides Korean normalization and tokenization. Please join our community at Google Forum. The intent of this text processor is not limited to short tweet texts.

스칼라로 쓰여진 한국어 처리기입니다. 현재 텍스트 정규화와 형태소 분석, 스테밍을 지원하고 있습니다. 짧은 트윗은 물론이고 긴 글도 처리할 수 있습니다. 개발에 참여하시고 싶은 분은 Google Forum에 가입해 주세요. 사용법을 알고자 하시는 초보부터 코드에 참여하고 싶으신 분들까지 모두 환영합니다.

twitter-korean-text의 목표는 빅데이터 등에서 간단한 한국어 처리를 통해 색인어를 추출하는 데에 있습니다. 완전한 수준의 형태소 분석을 지향하지는 않습니다.

twitter-korean-text는 normalization, tokenization, stemming, phrase extraction 이렇게 네가지 기능을 지원합니다.

정규화 normalization (입니닼ㅋㅋ -> 입니다 ㅋㅋ, 샤릉해 -> 사랑해)

  • 한국어를 처리하는 예시입니닼ㅋㅋㅋㅋㅋ -> 한국어를 처리하는 예시입니다 ㅋㅋ

토큰화 tokenization

  • 한국어를 처리하는 예시입니다 ㅋㅋ -> 한국어Noun, 를Josa, 처리Noun, 하는Verb, 예시Noun, 입Adjective, 니다Eomi ㅋㅋKoreanParticle

어근화 stemming (입니다 -> 이다)

  • 한국어를 처리하는 예시입니다 ㅋㅋ -> 한국어Noun, 를Josa, 처리Noun, 하다Verb, 예시Noun, 이다Adjective, ㅋㅋKoreanParticle

어구 추출 phrase extraction

  • 한국어를 처리하는 예시입니다 ㅋㅋ -> 한국어, 처리, 예시, 처리하는 예시

Introductory Presentation: Google Slides

Try it here

Gunja Agrawal kindly created a test API webpage for this project: http://gunjaagrawal.com/langhack/

Gunja Agrawal님이 만들어주신 테스트 웹 페이지 입니다. http://gunjaagrawal.com/langhack/

Opensourced here: twitter-korean-tokenizer-api

API

scaladoc

mavendoc

Maven

To include this in your Maven-based JVM project, add the following lines to your pom.xml:

Maven을 이용할 경우 pom.xml에 다음의 내용을 추가하시면 됩니다:

  <dependency>
    <groupId>com.twitter.penguin</groupId>
    <artifactId>korean-text</artifactId>
    <version>4.4</version>
  </dependency>

The maven site is available here http://twitter.github.io/twitter-korean-text/ and scaladocs are here http://twitter.github.io/twitter-korean-text/scaladocs/

Support for other languages.

.net

modamoda kindly offered a .net wrapper: https://github.com/modamoda/TwitterKoreanProcessorCS

node.js

Ch0p kindly offered a node.js wrapper: twtkrjs

Youngrok Kim kindly offered a node.js wrapper: node-twitter-korean-text

Python

Baeg-il Kim kindly offered a Python version: https://github.com/cedar101/twitter-korean-py

Jaepil Jeong kindly offered a Python wrapper: https://github.com/jaepil/twkorean

  • Python Korean NLP project KoNLPy now includes twitter-korean-text. 파이썬에서 쉬운 활용이 가능한 KoNLPy 패키지에 twkorean이 포함되었습니다.

Ruby

jun85664396 kindly offered a Ruby wrapper: twitter-korean-text-ruby

  • This provides access to com.twitter.penguin.korean.TwitterKoreanProcessorJava (Java wrapper).

Jaehyun Shin kindly offered a Ruby wrapper: twitter-korean-text-ruby

  • This provides access to com.twitter.penguin.korean.TwitterKoreanProcessor (Original Scala Class).

Elastic Search

socurites's Korean analyzer for elasticsearch based on twitter-korean-text: tkt-elasticsearch

Get the source 소스를 원하시는 경우

Clone the git repo and build using maven.

Git 전체를 클론하고 Maven을 이용하여 빌드합니다.

git clone https://github.com/twitter/twitter-korean-text.git
cd twitter-korean-text
mvn compile

Open 'pom.xml' from your favorite IDE.

Usage 사용 방법

You can find these examples in examples folder.

examples 폴더에 사용 방법 예제 파일이 있습니다.

from Scala

import com.twitter.penguin.korean.TwitterKoreanProcessor
import com.twitter.penguin.korean.phrase_extractor.KoreanPhraseExtractor.KoreanPhrase
import com.twitter.penguin.korean.tokenizer.KoreanTokenizer.KoreanToken

object ScalaTwitterKoreanTextExample {
  def main(args: Array[String]) {
    val text = "한국어를 처리하는 예시입니닼ㅋㅋㅋㅋㅋ #한국어"

    // Normalize
    val normalized: CharSequence = TwitterKoreanProcessor.normalize(text)
    println(normalized)
    // 한국어를 처리하는 예시입니다ㅋㅋ #한국어

    // Tokenize
    val tokens: Seq[KoreanToken] = TwitterKoreanProcessor.tokenize(normalized)
    println(tokens)
    // List(한국어(Noun: 0, 3), 를(Josa: 3, 1),  (Space: 4, 1), 처리(Noun: 5, 2), 하는(Verb: 7, 2),  (Space: 9, 1), 예시(Noun: 10, 2), 입니(Adjective: 12, 2), 다(Eomi: 14, 1), ㅋㅋ(KoreanParticle: 15, 2),  (Space: 17, 1), #한국어(Hashtag: 18, 4))

    // Stemming
    val stemmed: Seq[KoreanToken] = TwitterKoreanProcessor.stem(tokens)

    println(stemmed)
    // List(한국어(Noun: 0, 3), 를(Josa: 3, 1),  (Space: 4, 1), 처리(Noun: 5, 2), 하다(Verb: 7, 2),  (Space: 9, 1), 예시(Noun: 10, 2), 이다(Adjective: 12, 3), ㅋㅋ(KoreanParticle: 15, 2),  (Space: 17, 1), #한국어(Hashtag: 18, 4))

    // Phrase extraction
    val phrases: Seq[KoreanPhrase] = TwitterKoreanProcessor.extractPhrases(tokens, filterSpam = true, enableHashtags = true)
    println(phrases)
    // List(한국어(Noun: 0, 3), 처리(Noun: 5, 2), 처리하는 예시(Noun: 5, 7), 예시(Noun: 10, 2), #한국어(Hashtag: 18, 4))
  }
}

from Java

import java.util.List;

import scala.collection.Seq;

import com.twitter.penguin.korean.TwitterKoreanProcessor;
import com.twitter.penguin.korean.TwitterKoreanProcessorJava;
import com.twitter.penguin.korean.phrase_extractor.KoreanPhraseExtractor;
import com.twitter.penguin.korean.tokenizer.KoreanTokenizer;

public class JavaTwitterKoreanTextExample {
  public static void main(String[] args) {
    String text = "한국어를 처리하는 예시입니닼ㅋㅋㅋㅋㅋ #한국어";

    // Normalize
    CharSequence normalized = TwitterKoreanProcessorJava.normalize(text);
    System.out.println(normalized);
    // 한국어를 처리하는 예시입니다ㅋㅋ #한국어


    // Tokenize
    Seq<KoreanTokenizer.KoreanToken> tokens = TwitterKoreanProcessorJava.tokenize(normalized);
    System.out.println(TwitterKoreanProcessorJava.tokensToJavaStringList(tokens));
    // [한국어, 를, 처리, 하는, 예시, 입니, 다, ㅋㅋ, #한국어]
    System.out.println(TwitterKoreanProcessorJava.tokensToJavaKoreanTokenList(tokens));
    // [한국어(Noun: 0, 3), 를(Josa: 3, 1),  (Space: 4, 1), 처리(Noun: 5, 2), 하는(Verb: 7, 2),  (Space: 9, 1), 예시(Noun: 10, 2), 입니(Adjective: 12, 2), 다(Eomi: 14, 1), ㅋㅋ(KoreanParticle: 15, 2),  (Space: 17, 1), #한국어(Hashtag: 18, 4)]


    // Stemming
    Seq<KoreanTokenizer.KoreanToken> stemmed = TwitterKoreanProcessorJava.stem(tokens);
    System.out.println(TwitterKoreanProcessorJava.tokensToJavaStringList(stemmed));
    // [한국어, 를, 처리, 하다, 예시, 이다, ㅋㅋ, #한국어]
    System.out.println(TwitterKoreanProcessorJava.tokensToJavaKoreanTokenList(stemmed));
    // [한국어(Noun: 0, 3), 를(Josa: 3, 1),  (Space: 4, 1), 처리(Noun: 5, 2), 하다(Verb: 7, 2),  (Space: 9, 1), 예시(Noun: 10, 2), 이다(Adjective: 12, 3), ㅋㅋ(KoreanParticle: 15, 2),  (Space: 17, 1), #한국어(Hashtag: 18, 4)]


    // Phrase extraction
    List<KoreanPhraseExtractor.KoreanPhrase> phrases = TwitterKoreanProcessorJava.extractPhrases(tokens, true, true);
    System.out.println(phrases);
    // [한국어(Noun: 0, 3), 처리(Noun: 5, 2), 처리하는 예시(Noun: 5, 7), 예시(Noun: 10, 2), #한국어(Hashtag: 18, 4)]

  }
}

Basics

TwitterKoreanProcessor.scala is the central object that provides the interface for all the features.

TwitterKoreanProcessor.scala에 지원하는 모든 기능을 모아 두었습니다.

Running Tests

mvn test will run our unit tests

모든 유닛 테스트를 실행하려면 mvn test를 이용해 주세요.

Tools

We provide tools for quality assurance and test resources. They can be found under src/main/scala/com/twitter/penguin/korean/qa and src/main/scala/com/twitter/penguin/korean/tools.

Contribution

Refer to the general contribution guide. We will add this project-specific contribution guide later.

설치 및 수정하는 방법 상세 안내

Performance 처리 속도

Tested on Intel i7 2.3 Ghz

Initial loading time (초기 로딩 시간): 2~4 sec

Average time per parsing a chunk (평균 어절 처리 시간): 0.12 ms

Tweets (Avg length ~50 chars)

Tweets100K200K300K400K500K600K700K800K900K1M
Time in Seconds57.59112.09165.05218.11270.54328.52381.09439.71492.94542.12
Average per tweet: 0.54212 ms

Benchmark test by KoNLPy

Benchmark test

From http://konlpy.org/ko/v0.4.2/morph/

Author(s)


반응형
반응형

[Chatbot] http://mindmap.ai/ - 마인드맵으로 만드는 인공지능 챗봇플랫폼



챗봇서비스를 지원한다고 해서 가입!!!






...



반응형
반응형

대화형 챗봇 설계의 과제


챗봇이 실패하는 이유

페이스북이 2016년 4월에 봇 플랫폼을 출시 한 후, 많은 사람들이 주요 "출시 파트너"를 시험해 보았고 매우 부족한 것을 알게 되었습니다. 챗봇은 응용 프로그램 도메인 내에 있는 기본적인 질문 (예: 날씨 또는 꽃 배달 확인)조차 이해할 수 없었습니다. 사용자가 챗봇이 원하는 기계적인 질문에서 벗어나 "자연스럽게" 말하려고 할 때 챗봇이 혼란스러워하는 것을 보는 것은 특히 더 고통스러웠습니다.

페이스북 메신저 제품 관리자인 Mikhail Larionnov는 페이스북 플랫폼에서 많은 챗봇을 검토한 결과, 일부 챗봇의 견인력 부족에 대한 세 가지 이유를 확인했습니다:

  • 이용을 시작할 때 챗봇의 기능에 대한 설명이 거의 없다
  • 단일 챗봇에서 너무 많은 작업을 시도해 목표가 불명확
  • 자연어 처리에 지나치게 의존

성공적인 챗봇을 만드는 방법

그러나 Larionnov는 이러한 문제를 해결하기 위한 구체적인 조언을 제공했습니다.

첫째, 챗봇은 매우 제한된 범위를 가져야합니다. 챗봇은 좁은 주제에 대한 가치를 제공하고, 그것을 잘 해내야 합니다. 더 중요한 것은 챗봇이 무엇을 하는지 한두 문장으로 설명할 수 있어야 합니다.

둘째, 각 메시징 플랫폼의 내장 기능을 사용하여 사용자가 이용을 시작할 때 챗봇의 기능을 잘 전달해야 합니다. 페이스북 메신저의 경우 잘 만들어진 인사말 창과 동작 유도 문을 활용할 수 있습니다. 슬랙(Slack)의 경우 봇 저장소의 설명을 이용할 수 있습니다.

셋째, 가능한 구조화된 버튼을 사용해야합니다. 자유로운 사용자 입력이 정말 필요한 경우 AI가 입력을 이해할 수 없는 경우를 처리하고, 구문을 올바르게 사용하는 방법에 대한 도움말을 제공해야 합니다. 챗봇의 구문은 작업을 트리거(trigger, 시작)하는 명령과 키워드입니다.

네 번째 항목을 추가하면, 스팸처럼 불필요한 정보를 제공하면 안됩니다. 챗봇은 중지, 탈퇴 및 취소와 같은 명령을 이해하고 응답해야합니다. 그리고 즉시 메시지 전송을 중단해야 합니다. 봇이 과도하게 원치 않는 메시지를 사용자에게 보내면 사용자는 챗봇을 차단할 수밖에 없습니다. 4%의 사용자가 챗봇을 차단하면 페이스북은 사용자의 챗봇을 오프라인으로 전환시키는 것으로 알려져 있습니다.

반응형
반응형

 Vectorflow - https://github.com/Netflix/vectorflow


Netflix Technology Blog

Learn more about how Netflix designs, builds, and operates our systems and engineering organizations

https://medium.com/@NetflixTechBlog




희소 한 데이터를위한 경량 신경 네트워크 라이브러리

Vectorflow is a minimalist neural network library optimized for sparse data and single machine environments.

Original blog post here.

Installation

dub package

The library is distributed as a dub package. Add vectorflow to the dependencies section of your dub.json:

"vectorflow": "~>1.0.0"

The library itself doesn't have any dependency. All you need is a recent D compiler.

LDC is the recommended compiler for the fastest runtime speed.

Tested on:

  • Linux, OSX
  • LDC version: >= 1.1.1
  • DMD version: >= 2.073.1

Setting up a D environment

If you're new to D, keep reading. You will need dub (the D package manager) and LDC (the LLVM-based D compiler).

macOs
brew install dub
brew install ldc
Ubuntu

dub can be downloaded here (or follow instructions on this page). LDC can be installed by running:

snap install --classic --edge ldc2

Examples

To run the RCV1 example (sparse logistic regression):

cd examples && ./compile_run.sh rcv1.d

Tests

To run the tests:

dub test

Documentation

vectorflow is using ddoc. One way of building and serving locally the documentation (you will need libevent for serving) is:

dub build -b ddox && dub run -b ddox

Or use your favorite DDOC compiler.

Please also refer to the repo wiki.



...

반응형
반응형

[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 파이썬으로 챗봇_만들기





...

반응형

+ Recent posts