Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introductions of Messaging bot 做聊天機器人

Introductions of Messaging bot 做聊天機器人

想做聊天機器人?這裡可以給你一些指引
包含 Slack, Line , FB Messenger, Skype 的串接

Johnny Sung

June 20, 2016
Tweet

More Decks by Johnny Sung

Other Decks in Programming

Transcript

  1. M E S S A G I N G B

    O T I N T R O D U C T I O N S O F JOHNNY SUNG 2016.06.18 @ GDG Kaohsiung
  2. 獺 ఺ 咳 మ 物 ֦ ૶ 磭 ਙ 狶

    Ջ 讕 牫 http://www.jeanchristophebonis.com/wp-content/uploads/2015/01/5949_render_walle4.png
  3. ᮎ 圵 秚 瑊 Ո 牫 • 蝢Ꭳ觊 • Git

    ጱ commit, pull request 蝢Ꭳ • Server deploy 蝢Ꭳ • Ո㹓藶؃蝢Ꭳ牏ᤈԪ磓蝢Ꭳ • 蝱虴蝢Ꭳ • …
  4. ᮎ 圵 秚 瑊 Ո 牫 • ԰㵕觊 (൉׀虻懱౲㵕֢) •

    懪瞆牏懪觵ମ牏懪׎吚 (?) • 搚疑ᛔ㵕ࢧ薟 • 渟楮൉蠣 • …
  5. S L A C K • Incoming Webhooks • Send

    messages into Slack with customization and rich formatting. • Outgoing Webhooks • Send messages from Slack to your service in real-time. • Bot Users • Connect to Slack to read and write as a real-time bot.
  6. I N C O M I N G W E

    B H O O K S https://api.slack.com/incoming-webhooks Your server Slack POST 200 OK
  7. curl -X POST -H 'Content-type: application/json' --data ‘{“text”:"Hello, World!”}’ https://hooks.slack.com/services/T00000000/B00000000/

    XXXXXXXXXXXXXXXXXXXXXXXX I N C O M I N G W E B H O O K S https://api.slack.com/incoming-webhooks 涮鷑鎝䜂
  8. I N C O M I N G W E

    B H O O K S https://api.slack.com/incoming-webhooks
  9. • Trigger keyword(s) • Callbacks • Cons: Public channel only

    O U T G O I N G W E B H O O K S https://api.slack.com/outgoing-webhooks
  10. O U T G O I N G W E

    B H O O K S https://api.slack.com/outgoing-webhooks Slack 1. Detect if have certain keyword ͩΩ΁ͷ΅ Bonjour উ֞ೞࣁਃ สวัสดี ֦অ नमस्ते မဂ#လ%ပ'
  11. O U T G O I N G W E

    B H O O K S https://api.slack.com/outgoing-webhooks Slack Your Server 200 OK 2. POST user message POST
  12. O U T G O I N G W E

    B H O O K S https://api.slack.com/outgoing-webhooks Slack Your Server 200 OK POST 3. Return bot message
  13. B O T U S E R S ( R

    E A L T I M E M E S S A G I N G A P I ) https://api.slack.com/bot-users Your server Slack WebSocket
  14. https://api.slack.com/bot-users Your server Slack WebSocket Hello User Online User Typing

    Messages… B O T U S E R S ( R E A L T I M E M E S S A G I N G A P I )
  15. https://api.slack.com/bot-users Your server Slack WebSocket Hello User Online User Typing

    Messages… B O T U S E R S ( R E A L T I M E M E S S A G I N G A P I )
  16. https://api.slack.com/bot-users Your server Slack WebSocket Post Messages Bots Info Users

    Info… B O T U S E R S ( R E A L T I M E M E S S A G I N G A P I )
  17. #!/usr/bin/python
 # -*- coding: utf-8 -*-
 
 import time
 from

    slackclient import SlackClient
 # Token found at https://api.slack.com/web#authentication
 token = "xoxb-52095439187-CYPqixxxxxzwR9MoriR"
 sc = SlackClient(token)
 if sc.rtm_connect():
 while True:
 results = sc.rtm_read()
 for result in results:
 if 'type' in result:
 if result['type'] == u'message' and not('subtype' in result):
 channel = result['channel']
 text = result['text']
 user = result['user']
 if channel != u'C02HKPG5U' and user != u'U1J2TCX5H': # Filter out:
 # C02HKPG5U ==> General channel
 # U07SJTAMC ==> Bot it's self
 try:
 sc.rtm_send_message(channel, text)
 except Exception, e:
 print e 
 print result
 time.sleep(5)
 else:
 print "Connection Failed, invalid token?" Python
  18. {u'text': u’Hello, world!’, u'ts': u'1466228461.000005', u'user': u'U02HKPG5G', u'team': u'T02HKPG5C', u'type':

    u'message', u'channel': u'G1J4EADCH'} {u'type': u'hello'} {u'type': u'presence_change', u'user': u'U1J4C9FGF', u'presence': u'active'} )FMMP鎝䜂 ♳箁朜䢀隶刿 倞鎝䜂
  19. POST /linebot.php HTTP/1.1 ACCEPT: */* ACCEPT-CHARSET: utf-8 CONTENT-TYPE: application/json;charset=UTF-8 USER-AGENT:

    ChannelEventDispatcher/1.0 X-LINE-CHANNELSIGNATURE: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CONTENT-LENGTH: 542 HOST: your.ip.here:443 CONNECTION: Keep-Alive ACCEPT-ENCODING: gzip,deflate {“result”:[{"content":{"toType":1,"createdTime": 1465701674031,"from":"u2832cfc217c72c6df812248d041b73c8","location":null,"id":"4450389 514583","to":["uc6b4b8ef65ce03b72a672ac34b6e3a60"],"text":"Hello, World!”,”contentMetadata": {"AT_RECV_MODE":"2","EMTVER":"4","SKIP_BADGE_COUNT":"true"},"deliveredTime": 0,"contentType":1,"seq":null},"createdTime": 1465701674063,"eventType":"138311609000106303","from":"u206d25c2ea6bd87c17655609a 1c37cb8","fromChannel":1341301815,"id":"WB1521-3505347188","to": ["uc6b4b8ef65ce03b72a672ac34b6e3a60"],"toChannel":1463624852}]} https://developers.line.me/bot-api/getting-started-with-bot-api-trial 佐ⵌ鎝䜂涸㼓⺫
  20. <?php
 function sendMessage($toIdArr, $message)
 {
 $curl = curl_init();
 $options =

    array(
 CURLOPT_URL => "https://trialbot-api.line.me/v1/events",
 CURLOPT_HEADER => 0,
 CURLOPT_VERBOSE => 0,
 CURLOPT_RETURNTRANSFER => true,
 CURLOPT_POST => true,
 CURLOPT_POSTFIELDS => array(
 "to" => $toIdArr,
 "toChannel" => 1383378250,
 "eventType" => "138331608800106203",
 "content" => array(
 "contentType" => 1,
 "toType" => 1,
 "text" => $message
 ),
 ),
 CURLOPT_HTTPHEADER => array(
 'X-Line-ChannelID: 1463624852',
 'X-Line-ChannelSecret: 4968a9430a32c10d969e395acd04117f',
 'X-Line-Trusted-User-With-ACL: uc6b4b81e65ce03b72a672ac34b6e3a60',
 'Content-type: application/json; charset=UTF-8',
 )
 );
 
 curl_setopt_array($curl, $options);
 $result = curl_exec($curl);
 curl_close($curl);
 return $result;
 } 涮鷑鎝䜂 PHP
  21. FA C E B O O K M E S

    S E N G E R
  22. 皃 㮆 犋 梊 ጱ 塅 ֺ • CNN •

    https://www.facebook.com/cnn/ • Humani: Jessie's Story • https://www.facebook.com/JessieHumani/
  23. Your server Facebook M E S S E N G

    E R B O T Messages https:// https://messengerplatform.fb.com/
  24. Your server Post Messages M E S S E N

    G E R B O T https://messengerplatform.fb.com/ Facebook
  25. C R E AT I N G M E S

    S E N G E R B O T • 1. Create a Facebook App and Page • 2. Setup Webhook • 3. Get a Page Access Token • 4. Subscribe the App to the Page https://messengerplatform.fb.com/
  26. 4 . S U B S C R I B

    E T H E A P P T O T H E PA G E curl -X POST "https://graph.facebook.com/v2.6/me/ subscribed_apps?access_token=<PAGE_ACCESS_TOKEN>" 䁆ᤈ瞲犤
  27. POST /fbbot/main.php HTTP/1.1 HOST: your.ip.here ACCEPT: */* ACCEPT-ENCODING: deflate, gzip

    CONTENT-TYPE: application/json X-HUB-SIGNATURE: sha1=03xxxxxxxxxxxxxxxxxxxxxxxxd58a7 CONTENT-LENGTH: 261 {"object":"page","entry":[{"id":1010700000009448,"time": 1460599788132,"messaging":[{"sender":{"id":1006290000095540},"recipient": {"id":1010710000019448},"timestamp":1460000088101,"message": {"mid":"mid.1460000088087:e7dca9a000001d9e91","seq":15,"text":"hi"}}]}]} 佐ⵌ鎝䜂涸㼓⺫
  28. <?php
 $postdata = file_get_contents("php://input");
 
 $jsobj = json_decode($postdata, true);
 


    $results = $jsobj['entry'];
 
 if (isset($results)) {
 foreach ($results as &$entry) {
 foreach ($entry['messaging'] as &$msgObj) {
 $senderId = $msgObj['sender']['id'];
 $message = $msgObj['message']['text'];
 
 sendMessage($senderId, $message);
 }
 }
 }
 
 PHP 䱺佐鎝䜂
  29. <?php
 function sendMessage($toId, $message)
 {
 $post = json_encode(array(
 "recipient" =>

    array(
 "id" => $toId
 ),
 "message" => array(
 "text" => $message
 )
 )
 );
 
 $pageToken = "YOUR_PAGE_TOKEN";
 
 $ch = curl_init();
 $options = array(
 CURLOPT_URL => "https://graph.facebook.com/v2.6/me/messages?access_token=" . $pageToken,
 CURLOPT_HEADER => 0,
 CURLOPT_VERBOSE => 0,
 CURLOPT_RETURNTRANSFER => true,
 CURLOPT_POST => true,
 CURLOPT_POSTFIELDS => $post,
 CURLOPT_HTTPHEADER => array(
 'Content-type: application/json; charset=UTF-8'
 )
 );
 
 curl_setopt_array($ch, $options);
 $result = curl_exec($ch);
 curl_close($ch);
 return $result;
 } PHP 涮鷑鎝䜂
  30. Your server Skype S K Y P E B O

    T https://developer.microsoft.com/en-us/skype/bots/docs/api/chat Messages https://
  31. Your server Skype Post Messages S K Y P E

    B O T https://developer.microsoft.com/en-us/skype/bots/docs/api/chat
  32. S K Y P E B O T • 1.

    Create Skype bot • 2. Create Microsoft Application • 3. Paste Application ID to Skype bot • 4. Add your bot to contact https://developer.microsoft.com/en-us/skype/bots/docs/api/chat
  33. T H E R E S O U R C

    E M O D E L Conversation ID • 8:<USERNAME> • 28:<BOTID> • 19:<GROUP CONVERSATION> • …. https://developer.microsoft.com/en-us/skype/bots/docs/api/chat
  34. POST /skypebot/main.php HTTP/1.1 CONTENT-TYPE: application/json; charset=utf-8 HOST: your.ip.here CONTENT-LENGTH: 156

    EXPECT: 100-continue CONNECTION: Keep-Alive [{"id":"0","content":"Hi","activity":"message","from":"8:USERNAME","to":"28 :BOTID","time":"2016-06-16T07:08:03.906Z"}] 佐ⵌ鎝䜂涸㼓⺫
  35. <?php
 $postdata = file_get_contents("php://input");
 
 $json = json_decode($postdata, true);
 


    foreach ($json as &$msgObj) {
 if (strcmp($msgObj['activity'], 'message') == 0) {
 $fromId = $msgObj['from'];
 $message = $msgObj['content'];
 sendMessage($fromId, $message);
 }
 }
 
 header("HTTP/1.1 201 Created"); PHP 䱺佐鎝䜂
  36. <?php
 require __DIR__ . '/vendor/autoload.php';
 use Skype\Client;
 
 function sendMessage($id,

    $message)
 {
 $client = new Client([
 'clientId' => 'YOUR_CLIENT_ID',
 'clientSecret' => 'YOUR_CLIENT_SECRET',
 ]);
 $api = $client->authorize()->api('conversation');
 $result = $api->activity($id, $message);
 return $result;
 } PHP 涮鷑鎝䜂