diff --git a/main.go b/main.go index 52555dc..f971a5b 100644 --- a/main.go +++ b/main.go @@ -32,6 +32,11 @@ func main() { Usage: "send telegram message", EnvVar: "PLUGIN_MESSAGE", }, + cli.StringSliceFlag{ + Name: "photo", + Usage: "send photo message", + EnvVar: "PLUGIN_PHOTO", + }, cli.BoolFlag{ Name: "debug", Usage: "enable debug message", @@ -121,6 +126,7 @@ func run(c *cli.Context) error { Debug: c.Bool("debug"), To: c.StringSlice("to"), Message: c.StringSlice("message"), + Photo: c.StringSlice("photo"), Format: c.String("format"), }, } diff --git a/plugin.go b/plugin.go index 5553bf9..9c733bc 100644 --- a/plugin.go +++ b/plugin.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "log" + "os" "strconv" "strings" @@ -35,6 +36,7 @@ type ( Debug bool To []string Message []string + Photo []string Format string } @@ -60,6 +62,19 @@ func trimElement(keys []string) []string { return newKeys } +func fileExist(keys []string) []string { + var newKeys []string + + for _, value := range keys { + if _, err := os.Stat(value); os.IsNotExist(err) { + continue + } + newKeys = append(newKeys, value) + } + + return newKeys +} + func parseID(keys []string) []int64 { var newKeys []int64 @@ -104,11 +119,11 @@ func (p Plugin) Exec() error { // parse ids ids := parseID(p.Config.To) + photos := fileExist(trimElement(p.Config.Photo)) // send message. for _, user := range ids { for _, value := range trimElement(message) { - log.Println(user) msg := tgbotapi.NewMessage(user, value) msg.ParseMode = p.Config.Format @@ -118,6 +133,15 @@ func (p Plugin) Exec() error { log.Println(err.Error()) } } + + for _, value := range photos { + msg := tgbotapi.NewPhotoUpload(user, value) + _, err := bot.Send(msg) + + if err != nil { + log.Println(err.Error()) + } + } } return nil diff --git a/plugin_test.go b/plugin_test.go index f686444..b6b118c 100644 --- a/plugin_test.go +++ b/plugin_test.go @@ -69,6 +69,7 @@ func TestSendMessage(t *testing.T) { Token: os.Getenv("TELEGRAM_TOKEN"), To: []string{os.Getenv("TELEGRAM_TO"), "中文ID", "1234567890"}, Message: []string{"Test Telegram Chat Bot From Travis or Local", " "}, + Photo: []string{"tests/gophercolor.png", "1234", " "}, Debug: false, }, } @@ -137,3 +138,13 @@ func TestParseID(t *testing.T) { assert.Equal(t, result, parseID(input)) } + +func TestCheckFileExist(t *testing.T) { + var input []string + var result []string + + input = []string{"tests/gophercolor.png", "測試", "3"} + result = []string{"tests/gophercolor.png"} + + assert.Equal(t, result, fileExist(input)) +}