As the title suggests, I created a system for uploading photos from LINE Bot to Dropbox. Currently, there are a lot of issues, but I will post it because I have implemented the main functions.
When you send an image to LINE Bot,
Upload to Dropbox.
main.go
package main
import (
"io"
"log"
"net/http"
"os"
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox"
"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/files"
"github.com/line/line-bot-sdk-go/linebot"
"gopkg.in/ini.v1"
)
type Config struct {
channelSecrt string
channelToken string
dropboxToken string
}
var conf Config
func init() {
c, _ := ini.Load("config.ini")
conf = Config{
channelSecrt: c.Section("lineBotApi").Key("secret").String(),
channelToken: c.Section("lineBotApi").Key("token").String(),
dropboxToken: c.Section("DropboxApi").Key("token").String(),
}
}
func main() {
http.HandleFunc("/callback", lineHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func lineHandler(w http.ResponseWriter, r *http.Request) {
bot, err := linebot.New(
conf.channelSecrt,
conf.channelToken,
)
if err != nil {
log.Fatal(err)
}
events, err := bot.ParseRequest(r)
if err != nil {
if err == linebot.ErrInvalidSignature {
w.WriteHeader(400)
} else {
w.WriteHeader(500)
}
return
}
for _, event := range events {
if event.Type == linebot.EventTypeMessage {
switch message := event.Message.(type) {
case *linebot.ImageMessage:
content, err := bot.GetMessageContent(message.ID).Do()
if err != nil {
log.Println(err)
}
filename := message.ID + ".png "
file, err := os.Create(filename)
if err != nil {
log.Println(err)
}
if _, err = io.Copy(file, content.Content); err != nil {
log.Println(err)
}
config := dropbox.Config{
Token: conf.dropboxToken,
}
cli := files.New(config)
req := files.NewCommitInfo("/" + filename)
f, _ := os.Open(filename)
_, err = cli.Upload(req, f)
if err != nil {
log.Print(err)
return
}
if _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage("Upload completed")).Do(); err != nil {
log.Print(err)
}
default:
if _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage("Please send the image")).Do(); err != nil {
log.Print(err)
}
}
}
}
if err := http.ListenAndServe(":"+os.Getenv("PORT"), nil); err != nil {
log.Fatal(err)
}
}
content, err := bot.GetMessageContent(message.ID).Do()
if err != nil {
log.Println(err)
}
filename := message.ID + ".png "
file, err := os.Create(filename)
if err != nil {
log.Println(err)
}
if _, err = io.Copy(file, content.Content); err != nil {
log.Println(err)
}
config := dropbox.Config{
Token: conf.dropboxToken,
}
cli := files.New(config)
req := files.NewCommitInfo("/" + filename)
f, _ := os.Open(filename)
_, err = cli.Upload(req, f)
if err != nil {
log.Print(err)
return
}
Recommended Posts