Skip to content

Commit

Permalink
discord
Browse files Browse the repository at this point in the history
  • Loading branch information
coma-toast committed Jul 3, 2024
1 parent 8fdf43c commit 2e82550
Show file tree
Hide file tree
Showing 4 changed files with 143 additions and 10 deletions.
14 changes: 8 additions & 6 deletions internal/utils/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@ import (

// config is the configuration struct
type Config struct {
LogFilePath string
DBFilePath string
InstanceID string
SecretKey string
Port string
DevMode bool
LogFilePath string
DBFilePath string
InstanceID string
SecretKey string
Port string
DiscordWebhookURL string
DevMode bool
}

func GetConf(path string) *Config {
Expand All @@ -27,6 +28,7 @@ func GetConf(path string) *Config {
viper.SetDefault("InstanceID", "")
viper.SetDefault("SecretKey", "")
viper.SetDefault("Port", "")
viper.SetDefault("DiscordWebhookURL", "")
viper.SetDefault("DevMode", false)

if err := viper.ReadInConfig(); err != nil {
Expand Down
36 changes: 35 additions & 1 deletion internal/utils/logger.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,42 @@
package utils

import (
"fmt"
"io"
"os"

"github.com/sirupsen/logrus"
)

type Logger struct {
logger *logrus.Logger
file *os.File
}

func (l *Logger) Init(json bool) {
// Write logs to multiple writers
type multiLogWriter struct {
writers []io.Writer
}

func (m multiLogWriter) Write(p []byte) (int, error) {
n := len(p)
for _, w := range m.writers {
nw, err := w.Write(p[:n])
if err != nil {
return nw, err
}
n -= nw
}
return n, nil
}

// Add a method to set the writers
func (m *multiLogWriter) SetWriters(writers []io.Writer) {
m.writers = writers
}

func (l *Logger) Init(json bool, logFile string) {
var err error
l.logger = logrus.New()
l.logger.SetReportCaller(true)
l.logger.Out = os.Stdout
Expand All @@ -28,6 +54,14 @@ func (l *Logger) Init(json bool) {
} else {
l.logger.Formatter = &logrus.TextFormatter{}
}
// Create a custom formatter that writes to both stdout and a file
l.file, err = os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Println("Error opening log file:", err)
}
multiLogWriter := multiLogWriter{}
multiLogWriter.SetWriters([]io.Writer{os.Stdout, l.file})
l.logger.Out = multiLogWriter
l.logger.Info("Initializing Logger")
}

Expand Down
7 changes: 4 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/coma-toast/notifapi/internal/utils"
"github.com/coma-toast/notifapi/pkg/api"
"github.com/coma-toast/notifapi/pkg/app"
"github.com/coma-toast/notifapi/pkg/pusher"
"github.com/coma-toast/notifapi/pkg/discord_notifier" // Add this import statement
)

func main() {
Expand All @@ -17,14 +17,15 @@ func main() {
flag.Parse()

app.Config = *utils.GetConf(*configPath)
app.Logger.Init(false)
app.Logger.Init(false, app.Config.LogFilePath+"notifapi.log")
app.Logger.Info("App initialized")
app.Data.Init(app.Config.DBFilePath)
hostname, err := os.Hostname()
if err != nil {
app.Logger.Error(err)
}
app.Notifier = pusher.Pusher{InstanceID: app.Config.InstanceID, SecretKey: app.Config.SecretKey, Data: &app.Data}
// app.Notifier = pusher.Pusher{InstanceID: app.Config.InstanceID, SecretKey: app.Config.SecretKey, Data: &app.Data}
app.Notifier = discord_notifier.NewDiscordNotifier(app.Config.DiscordWebhookURL)
// * re-enable when back online
id, err := app.Notifier.SendMessage([]string{"hello"}, "NotifAPI", "NotifAPI is starting up on "+hostname, "main.go")
if err != nil {
Expand Down
96 changes: 96 additions & 0 deletions pkg/discord_notifier/discord.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package discord_notifier

import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)

// DiscordWebhook represents the Discord webhook configuration.
type DiscordWebhook struct {
URL string `json:"url"`
}

// NewDiscordNotifier creates a new instance of Discord notifier.
func NewDiscordNotifier(webhookURL string) *DiscordNotifier {
return &DiscordNotifier{
webhookURL: webhookURL,
}
}

// DiscordNotifier implements the Notifier interface for sending messages to Discord.
type DiscordNotifier struct {
webhookURL string
}

// SendMessage sends a message without a link to Discord.
func (n *DiscordNotifier) SendMessage(interests []string, title, body, source string) (string, error) {
message, err := createMessage(interests, title, body, "", source, nil)
if err != nil {
return "", err
}
resp, err := n.send(message)
if err != nil {
return "", err
}
return string(resp), nil
}

// SendMessageWithLink sends a message with a link to Discord.
func (n *DiscordNotifier) SendMessageWithLink(interests []string, title, body, link, source string) (string, error) {
message, err := createMessage(interests, title, body, link, source, nil)
if err != nil {
return "", err
}
resp, err := n.send(message)
if err != nil {
return "", err
}
return string(resp), nil
}

// SendMessageFull sends a full message including metadata to Discord.
func (n *DiscordNotifier) SendMessageFull(interests []string, title, body, link, source string, metadata map[string]interface{}) (string, error) {
message, err := createMessage(interests, title, body, link, source, metadata)
if err != nil {
return "", err
}
resp, err := n.send(message)
if err != nil {
return "", err
}
return string(resp), nil
}

func createMessage(interests []string, title, body, link, source string, metadata map[string]interface{}) ([]byte, error) {
data := map[string]interface{}{
"content": fmt.Sprintf("**%s**\n%s\n*Source:* %s\n*Interests:* %v", title, body, source, interests),
}
if link != "" {
data["components"] = []map[string]interface{}{
map[string]interface{}{
"type": "actions",
"elements": []map[string]interface{}{{"type": "button", "label": "View Details", "style": "primary", "url": link}},
},
}
}
if len(metadata) > 0 {
data["footer"] = map[string]string{"text": "Metadata"}
for k, v := range metadata {
data[k] = v
}
}
return json.Marshal(data)
}

func (n *DiscordNotifier) send(message []byte) ([]byte, error) {
resp, err := http.Post(n.webhookURL, "application/json", bytes.NewBuffer(message))
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
return body, nil
}

0 comments on commit 2e82550

Please sign in to comment.