From 5a5749d4a9976249e058449a6de964a7f82656d5 Mon Sep 17 00:00:00 2001 From: kha7iq Date: Tue, 13 Apr 2021 22:06:39 +0800 Subject: [PATCH] feat: Add discord service --- cmd/discord.go | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 cmd/discord.go diff --git a/cmd/discord.go b/cmd/discord.go new file mode 100644 index 0000000..b7951aa --- /dev/null +++ b/cmd/discord.go @@ -0,0 +1,89 @@ +package cmd + +import ( + "context" + "fmt" + "log" + "strings" + + "github.com/nikoksr/notify" + "github.com/nikoksr/notify/service/discord" + "github.com/urfave/cli/v2" +) + +type discordPingMe struct { + Token string + Message string + Channel string + Title string +} + +func SendToDiscord() *cli.Command { + var discordOpts discordPingMe + return &cli.Command{ + Name: "discord", + Usage: "Send message to discord", + Description: `Discord uses bot token to authenticate & send messages to defined channels. +Multiple channel ids can be used separated by comma ','. +All configuration options are also available via environment variables.`, + UsageText: "pingme discord --token '123' --channel '12345,67890' --message 'some message'", + Flags: []cli.Flag{ + &cli.StringFlag{ + Destination: &discordOpts.Token, + Name: "token", + Required: true, + Usage: "Token of discord bot used for sending message.", + EnvVars: []string{"DISCORD_TOKEN"}, + }, + &cli.StringFlag{ + Destination: &discordOpts.Channel, + Name: "channel", + Required: true, + Usage: "Channel ids of discord.", + EnvVars: []string{"DISCORD_CHANNELS"}, + }, + &cli.StringFlag{ + Destination: &discordOpts.Message, + Name: "msg", + Usage: "Message content.", + EnvVars: []string{"DISCORD_MESSAGE"}, + }, + &cli.StringFlag{ + Destination: &discordOpts.Title, + Name: "title", + Value: TimeValue, + Usage: "Title of the message.", + EnvVars: []string{"DISCORD_MSG_TITLE"}, + }, + }, + Action: func(ctx *cli.Context) error { + notifier := notify.New() + discordSvc := discord.New() + + if err := discordSvc.AuthenticateWithBotToken(discordOpts.Token); err != nil { + return fmt.Errorf("unable to authenticate %v\n", err) + } + + chn := strings.Split(discordOpts.Channel, ",") + for _, v := range chn { + if len(v) <= 0 { + return fmt.Errorf(EmptyChannel) + } + + discordSvc.AddReceivers(v) + } + + notifier.UseServices(discordSvc) + + if err := notifier.Send( + context.Background(), + discordOpts.Title, + discordOpts.Message, + ); err != nil { + return err + } + log.Println("Successfully sent!") + return nil + }, + } +}