Förderjahr 2016 / Projekt Call #11 / ProjektID: 1983 / Projekt: Prometheus
This is a guide on how to set up Chatfuel to process messages via the Chatfuel API on your server side application. And further on how to send a message to the user via Chatfuel's Broadcasting API from your application.
You can easily integrate this into the Prometheus AI Facebook Messenger Bot Sample.
Setup the JSON API Plugin
1. Click the +
tab in the block where you'd like to trigger the JSON API call:
2. Select the JSON API Plugin:
3. Add the corresponding URL to your server, in this case we use a ngrok URL for local development:
Handle the route in your Clojure app
In the prometheus-ai/prometheus-sample you would add this to handler.clj.
(defroutes app-routes
(GET "/chatfuel" request (println request) (api/handle-chatfuel-message request))
Process message & return a message to the user via the Broadcasting API
A few use cases for processing an incoming request could be to save input data into a database, process data further in a different API, process images or media attachments, …
Chatfuel Token for Broadcasting
Copy the broadcasting token from Chatfuel in the Configure
tab:
In the prometheus-ai/prometheus-sample you would add this to bot.clj.
Either define a variable for the chatfuel-token and assign the broadcasting token as string
(def chatfuel-token "your_chatfuel_broadcasting_token")
or add the token as an environment variable e.g. to the profiles.clj
in the root directory of the app (remember to not push this file to a public repository)
{:dev {:env {:chatfuel-token "your_chatfuel_broadcasting_token"}}}
and then define a variable that accesses the token from profiles.clj:
(def chatfuel-token (env :chatfuel-token))
Process incoming request & Broadcasting API
We do a POST
request to the Chatfuel Broadcasting API with required parameters and custom attributes in JSON
.
In the prometheus-ai/prometheus-sample you would add this to bot.clj.
(defn handle-chatfuel-message [request]
(let [data (get-in request [:params])
messenger-user-id (get data "messenger user id")]
;Process message here (save to DB, send to another API, process image, …)
;Broadcast a message to user(s)
(clj-http/post (str "https://api.chatfuel.com/bots/5937eda8e4b0ef6701357a40/users/" messenger-user-id "/send?chatfuel_token=" chatfuel-token "&chatfuel_block_name=API")
{:form-params {:booking_user "Rich Hickey"} :content-type :json})))
Create the block to send to the user in Chatfuel
In this guide we named the block "API" (as seen in the URL above: &chatfuel_block_name=API
).
Chatfuel's Broadcasting API enables you to send any block from the bot's structure or set user attributes via an API call. Find more details on how to use it here.