|
| 1 | +原文:[Facebook chat bot aka joke bot with django tutorial](https://codeexperiments.quora.com/Facebook-chat-bot-aka-joke-bot-with-django-tutorial) |
| 2 | + |
| 3 | +--- |
| 4 | + |
| 5 | + |
| 6 | + |
| 7 | + |
| 8 | +The age of bots has begun. Chat bots are a sensation now a days and are being |
| 9 | +hailed as the next generation replacement to websites and apps. Many platforms |
| 10 | +are getting opened up with chat bots as interaction tools such as in Facebook, |
| 11 | +Telegram etc. Chat bots are already quite famous in China’s messaging giant We |
| 12 | +Chat where people book cabs and make financial transactions via chat. |
| 13 | + |
| 14 | +I have decided to try to develop a chat bot which does only one thing. Send a |
| 15 | +random joke like the below one without an image irrespective of what the user |
| 16 | +types |
| 17 | + |
| 18 | + |
| 19 | + |
| 20 | +Getting started we are going to develop it in django. Why django? , I am good |
| 21 | +in python so I felt to go forward in Django, you can choose whatever you like. |
| 22 | +The official docs are for node.js . |
| 23 | + |
| 24 | +1. Create a facebook page from here [Create a Page | |
| 25 | +Facebook](https://www.facebook.com/pages/create/) . Choose some page type and |
| 26 | +go forward with the settings. |
| 27 | + |
| 28 | +2.Create a facebook app from here [Log into Facebook | |
| 29 | +Facebook](https://developers.facebook.com/quickstarts/) and fill in the |
| 30 | +required details to create an app. |
| 31 | + |
| 32 | +3.Once both the page and app are created go to the app settings and under |
| 33 | +Product Settings click Add Product and then Select **Messenger **. |
| 34 | + |
| 35 | +4.Now you need to setup webhooks. We need to deploy the django project online |
| 36 | +and make it available for facebook to make requests and facebook allows only |
| 37 | +https urls. [Your development environment, in the cloud](http://c9.io) is the |
| 38 | +best option I found online and it’s free for a basic app. Create a workspace |
| 39 | +in c9 and choose **Django **as platform. Now you will be directed to your |
| 40 | +online workspace. |
| 41 | + |
| 42 | +5. From the workspace use the below command to create a django app. |
| 43 | + |
| 44 | +```python |
| 45 | + |
| 46 | + django-admin.py startapp jokebot |
| 47 | + |
| 48 | +``` |
| 49 | + |
| 50 | +This should create an app jokebot. |
| 51 | + |
| 52 | +Go to [settings.py](http://settings.py) file in the workspace, find |
| 53 | +INSTALLED_APPS and add jokebot. |
| 54 | + |
| 55 | +```python |
| 56 | + |
| 57 | + INSTALLED_APPS = [ |
| 58 | + 'django.contrib.admin', |
| 59 | + 'django.contrib.auth', |
| 60 | + 'django.contrib.contenttypes', |
| 61 | + 'django.contrib.sessions', |
| 62 | + 'django.contrib.messages', |
| 63 | + 'django.contrib.staticfiles', |
| 64 | + 'jokebot', |
| 65 | + ] |
| 66 | + |
| 67 | +``` |
| 68 | + |
| 69 | +Modify [urls.py](http://urls.py) to include an endpoint for webhook. The |
| 70 | +webhook will hit the endpoint url/james and we have to respind with a token |
| 71 | +for facebook to validate. |
| 72 | + |
| 73 | +```python |
| 74 | + |
| 75 | + from django.conf.urls import url, include |
| 76 | + from django.contrib import admin |
| 77 | + from jokebot.views import jokebot |
| 78 | + |
| 79 | + urlpatterns = [ |
| 80 | + url(r'^admin/', admin.site.urls), |
| 81 | + url(r'^james/?$', jokebot.as_view()) |
| 82 | + ] |
| 83 | + |
| 84 | +``` |
| 85 | + |
| 86 | +Now go to [views.py](http://views.py) in the app jokebot and modify it to the |
| 87 | +following. |
| 88 | + |
| 89 | +```python |
| 90 | + |
| 91 | + import json, requests, random, re |
| 92 | + from pprint import pprint |
| 93 | + |
| 94 | + from django.views import generic |
| 95 | + from django.http.response import HttpResponse |
| 96 | + |
| 97 | + from django.views.decorators.csrf import csrf_exempt |
| 98 | + from django.utils.decorators import method_decorator |
| 99 | + |
| 100 | + |
| 101 | + def get_joke(fbid, recevied_message): |
| 102 | + joke_text = requests.get("http://api.icndb.com/jokes/random/").json()['value']['joke'] |
| 103 | + post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=%s'%'Place your access token here' |
| 104 | + response_msg = json.dumps({"recipient":{"id":fbid}, "message":{"text":joke_text}}) |
| 105 | + status = requests.post(post_message_url, headers={"Content-Type": "application/json"},data=response_msg) |
| 106 | + pprint(status.json()) |
| 107 | + |
| 108 | + class jokebot(generic.View): |
| 109 | + def get(self, request, *args, **kwargs): |
| 110 | + if self.request.GET['hub.verify_token'] == verify_token: |
| 111 | + return HttpResponse(self.request.GET['hub.challenge']) |
| 112 | + else: |
| 113 | + return HttpResponse('Error, invalid token') |
| 114 | + |
| 115 | + @method_decorator(csrf_exempt) |
| 116 | + def dispatch(self, request, *args, **kwargs): |
| 117 | + return generic.View.dispatch(self, request, *args, **kwargs) |
| 118 | + |
| 119 | + |
| 120 | + def post(self, request, *args, **kwargs): |
| 121 | + incoming_message = json.loads(self.request.body.decode('utf-8')) |
| 122 | + for entry in incoming_message['entry']: |
| 123 | + for message in entry['messaging']: |
| 124 | + if 'message' in message: |
| 125 | + get_joke(message['sender']['id'], message['message']['text']) |
| 126 | + return HttpResponse() |
| 127 | + |
| 128 | +``` |
| 129 | + |
| 130 | +We create a class jokebot which responds with |
| 131 | + |
| 132 | +```python |
| 133 | + |
| 134 | + self.request.GET['hub.challenge'] |
| 135 | + |
| 136 | +``` |
| 137 | + |
| 138 | +on a webhook request. |
| 139 | + |
| 140 | +Under the "PRODUCT SETTINGS" section, click on the "Messenger" product you |
| 141 | +just added, find the Webhooks section and click Setup Webhooks. Enter a URL |
| 142 | +for a webhook, enter a Verify Token and select message_deliveries, messages, |
| 143 | +messaging_optins, and messaging_postbacks under Subscription Fields. |
| 144 | + |
| 145 | + |
| 146 | + |
| 147 | +Choose any verify_token and place it in facebook and in the code. To get the |
| 148 | +url click on **Run** in c9 and place the url/james in callback url option. Now |
| 149 | +click on Verify and Save and you should get the webhook verified. |
| 150 | + |
| 151 | +Now we handle the message and send a joke using this code |
| 152 | + |
| 153 | +```python |
| 154 | + |
| 155 | + def post(self, request, *args, **kwargs): |
| 156 | + incoming_message = json.loads(self.request.body.decode('utf-8')) |
| 157 | + for entry in incoming_message['entry']: |
| 158 | + for message in entry['messaging']: |
| 159 | + if 'message' in message: |
| 160 | + get_joke(message['sender']['id'], message['message']['text']) |
| 161 | + return HttpResponse() |
| 162 | + |
| 163 | +``` |
| 164 | + |
| 165 | +This basically reads the post request of a message and responds with a joke. |
| 166 | + |
| 167 | +```python |
| 168 | + |
| 169 | + def get_joke(fbid, recevied_message): |
| 170 | + joke_text = requests.get("http://api.icndb.com/jokes/random/").json()['value']['joke'] |
| 171 | + post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=%s'%'Place your access token here' |
| 172 | + response_msg = json.dumps({"recipient":{"id":fbid}, "message":{"text":joke_text}}) |
| 173 | + status = requests.post(post_message_url, headers={"Content-Type": "application/json"},data=response_msg) |
| 174 | + pprint(status.json()) |
| 175 | + |
| 176 | +``` |
| 177 | + |
| 178 | +This function gets a random joke using an online api [The Internet ChuckNorris Database](http://www.icndb.com/) and sends it back to the user. |
| 179 | + |
| 180 | +To get page access token in the Token Generation section, select your Page. A |
| 181 | +Page Access Token will be generated for you. Copy this Page Access Token. |
| 182 | +Note: The generated token will NOT be saved in this UI. Each time you select |
| 183 | +that Page a new token will be generated. However, any previous tokens created |
| 184 | +will continue to function. |
| 185 | + |
| 186 | + |
| 187 | + |
| 188 | +So now run the server again and send a message and you should get a Chuck |
| 189 | +Norris joke. Remember that the app now works only for you. To make it publicly |
| 190 | +available you have to request fb to approve your app and publish it. |
| 191 | + |
| 192 | +You can find the entire source code here [Anil1331/Facebook-chat-bot](https://github.com/Anil1331/Facebook-chat-bot) . |
| 193 | + |
| 194 | +Sources:- |
| 195 | + |
| 196 | + 1. [How To Build Bots for Messenger - Facebook for Developers](https://developers.facebook.com/blog/post/2016/04/12/bots-for-messenger/) |
| 197 | + |
| 198 | + |
0 commit comments