Skip to content

Commit

Permalink
Add Line notify API. (#77)
Browse files Browse the repository at this point in the history
  • Loading branch information
appleboy authored Dec 18, 2017
1 parent 9a799b4 commit fc54ebe
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 2 deletions.
11 changes: 9 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"log"
"os"

"github.com/joho/godotenv"
Expand Down Expand Up @@ -233,7 +234,10 @@ VERSION:
REPOSITORY:
Github: https://github.com/appleboy/drone-line
`
app.Run(os.Args)
err := app.Run(os.Args)
if err != nil {
log.Println(err)
}
}

func run(c *cli.Context) error {
Expand Down Expand Up @@ -285,8 +289,11 @@ func run(c *cli.Context) error {

command := c.Args().Get(0)

if command == "webhook" {
switch command {
case "webhook":
return plugin.Webhook()
case "notify":
return plugin.Notify()
}

return plugin.Exec()
Expand Down
64 changes: 64 additions & 0 deletions plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -359,6 +360,69 @@ func (p Plugin) Webhook() error {
return nil
}

// Notify for Line notify service
// https://notify-bot.line.me
func (p Plugin) Notify() error {
if p.Config.ChannelToken == "" || len(p.Config.Message) == 0 {
return errors.New("missing token or message")
}

for _, m := range p.Config.Message {
if err := p.notify(m, p.Config.ChannelToken); err != nil {
return err
}
}

return nil
}

func (p Plugin) notify(message, token string) error {
data := url.Values{}
data.Add("message", message)

u, _ := url.ParseRequestURI("https://notify-api.line.me/api/notify")
urlStr := u.String()

req, err := http.NewRequest(
"POST",
urlStr,
strings.NewReader(data.Encode()),
)

if err != nil {
return errors.New("failed to create request:" + err.Error())
}

req.Header.Add("Authorization", "Bearer "+token)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

client := &http.Client{}
res, err := client.Do(req)

if err != nil {
return errors.New("failed to process request:" + err.Error())
}

defer res.Body.Close()

if p.Config.Debug {
log.Println("=================================")
log.Printf("%#v\n", res)
log.Println("=================================")
}

if res.Status == "200 OK" {
log.Println("successfully send notfiy")
}

if err != nil {
return errors.New("failed to create request:" + err.Error())
}

return nil
}

// Exec executes the plugin.
func (p Plugin) Exec() error {

Expand Down

0 comments on commit fc54ebe

Please sign in to comment.