Created
April 14, 2016 09:25
-
-
Save tomyhero/bd984cae2f1bba5603345a824b2acac1 to your computer and use it in GitHub Desktop.
facebook messenger platform sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"encoding/json" | |
"fmt" | |
log "github.com/Sirupsen/logrus" | |
"io/ioutil" | |
"net/http" | |
) | |
const token string = "XXXXXX" | |
func main() { | |
http.HandleFunc("/", handler) | |
http.ListenAndServe(":5555", nil) | |
} | |
type ( | |
FBRes struct { | |
Object string `json:"object"` | |
Entries []FBEntry `json:"entry"` | |
//Entries []map[string]interface{} `json:"entry"` | |
} | |
FBEntry struct { | |
ID int `json:"id"` | |
Time int `json:"time"` | |
Messagings []FBMessaging `json:"messaging"` | |
} | |
FBMessaging struct { | |
Sender FBSender `json:"sender"` | |
Recipient FBRecipient `json:"recipient"` | |
Timestamp int `json:"timestamp"` | |
Message FBMessage `json:"message"` | |
} | |
FBMessage struct { | |
Mid string `json:"mid"` | |
Seq int `json:"seq"` | |
Text string `json:"text"` | |
} | |
FBSender struct { | |
Id int `json:"id"` | |
} | |
FBRecipient struct { | |
Id int `json:"id"` | |
} | |
) | |
func handler(w http.ResponseWriter, r *http.Request) { | |
res := FBRes{} | |
json.NewDecoder(r.Body).Decode(&res) | |
log.Info(res) | |
for _, entry := range res.Entries { | |
for _, messaging := range entry.Messagings { | |
Send(messaging.Sender.Id, messaging.Message.Text) | |
} | |
} | |
} | |
func Send(id int, message string) { | |
url := "https://graph.facebook.com/v2.6/me/messages?access_token=" + token | |
data := map[string]interface{}{ | |
"recipient": map[string]int{"id": id}, | |
"message": map[string]string{"text": message}, | |
} | |
b, err := json.Marshal(data) | |
log.Info(string(b), err) | |
req, err := http.NewRequest("POST", url, bytes.NewBuffer(b)) | |
req.Header.Set("Content-Type", "application/json") | |
client := &http.Client{} | |
resp, err := client.Do(req) | |
if err != nil { | |
panic(err) | |
} | |
defer resp.Body.Close() | |
r, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Info(string(r)) | |
} | |
func _verify_handler(w http.ResponseWriter, r *http.Request) { | |
challenge := r.URL.Query()["hub.challenge"][0] | |
fmt.Fprintf(w, challenge) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment