Skip to content

Instantly share code, notes, and snippets.

@browny
Created October 28, 2018 11:25
Show Gist options
  • Save browny/3b9b91a2cd202f0710e5a7e8c42242e8 to your computer and use it in GitHub Desktop.
Save browny/3b9b91a2cd202f0710e5a7e8c42242e8 to your computer and use it in GitHub Desktop.
Dialogflow webhook sample code
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
owm "github.com/briandowns/openweathermap"
"github.com/julienschmidt/httprouter"
dfw "github.com/leboncoin/dialogflow-go-webhook"
)
const (
apiKey = "your_OpenWeatherMap_key"
)
func main() {
router := httprouter.New()
router.POST("/webhook", webhook)
log.Fatal(http.ListenAndServe(":8080", router))
}
func webhook(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
// 接收 fulfllment request
dfr := dfw.Request{}
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&dfr)
if err != nil {
panic(err)
}
// 打印出 fulfillment request 的 body (debug 使用)
b, err := json.MarshalIndent(dfr, "", " ")
if err != nil {
panic(err)
}
log.Println(string(b))
m, err := jsonStringToMap(string(dfr.QueryResult.Parameters))
if err != nil {
log.Fatalln(err)
}
// 取出參數
city := m["geo-city"].(string)
log.Printf("Action: %s, City: %s", dfr.QueryResult.Action, city)
// 呼叫 OpenWeatherMap API 查詢氣溫
temp := getTemperature(city)
// 構造 fulfillment response 返回
dff := &dfw.Fulfillment{
FulfillmentText: fmt.Sprintf(
"Current temperature of %s is %s", city, temp,
),
}
resp, err := json.Marshal(dff)
if err != nil {
log.Fatalln(err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(resp)
}
func getTemperature(locationName string) string {
owmCurrent, err := owm.NewCurrent("C", "ZH_TW", apiKey)
if err != nil {
log.Fatalln(err)
}
owmCurrent.CurrentByName(locationName)
return strconv.FormatFloat(owmCurrent.Main.Temp, 'f', -1, 64)
}
func jsonStringToMap(jsonString string) (map[string]interface{}, error) {
var dat map[string]interface{}
err := json.Unmarshal([]byte(jsonString), &dat)
if err != nil {
return nil, err
}
return dat, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment