Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions action/discord.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package action

import (
"context"
"log"
"fmt"

"github.com/ValianceTekProject/AreaBack/db"
"github.com/ValianceTekProject/AreaBack/initializers"
)

func GetDiscordToken(ctx context.Context, config map[string]any) (string, string, error) {
actionID, ok := config["action_id"].(string)

if !ok {
return "", "", fmt.Errorf("Unable to retrieve actionId")
}

action, err := initializers.DB.Actions.FindUnique(
db.Actions.ID.Equals(actionID),
).With(
db.Actions.Area.Fetch().With(
db.Areas.User.Fetch().With(
db.Users.ServiceTokens.Fetch(),
),
),
db.Actions.Service.Fetch(),
).Exec(ctx)

if err != nil {
log.Printf("Failed to get Actions: %v", err)
}

area := action.Area()
user := area.User()
service := action.Service()
var discordToken string
for _, ust := range user.ServiceTokens() {
if ust.ServiceID == service.ID {
discordToken = ust.AccessToken
break
}
}
return actionID, discordToken, nil
}
101 changes: 101 additions & 0 deletions action/discordNewMsg.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package action

import (
"context"
"encoding/json"
"fmt"
"github.com/ValianceTekProject/AreaBack/db"
"github.com/ValianceTekProject/AreaBack/initializers"
"io"
"net/http"
"os"
"time"
)

type DiscordMessage struct {
ID string `json:"id"`
ChannelID string `json:"channel_id"`
Content string `json:"content"`
Timestamp time.Time `json:"timestamp"`
Author struct {
ID string `json:"id"`
Username string `json:"username"`
} `json:"author"`
}

func ExecDiscordNewMsg(config map[string]any) error {
ctx := context.Background()

actionID, ok := config["action_id"].(string)
if !ok {
return fmt.Errorf("unable to retrieve action_id")
}

botToken := os.Getenv("DISCORD_BOT_TOKEN")
if botToken == "" {
return fmt.Errorf("DISCORD_BOT_TOKEN environment variable is not set")
}

channelID := "1442506377674096690"

execDiscordNewMsgAction(botToken, channelID, actionID, ctx)

return nil
}

func execDiscordNewMsgAction(botToken string, channelID string, actionID string, ctx context.Context) {
url := fmt.Sprintf("https://discord.com/api/v10/channels/%s/messages?limit=10", channelID)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}

req.Header.Set("Authorization", fmt.Sprintf("Bot %s", botToken))
req.Header.Set("Content-Type", "application/json")

client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error calling Discord API:", err)
return
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Discord API error (status %d): %s\n", resp.StatusCode, string(body))
return
}

var messages []DiscordMessage
if err := json.NewDecoder(resp.Body).Decode(&messages); err != nil {
fmt.Println("Error decoding Discord response:", err)
return
}

now := time.Now()
hasNewMessage := false

for _, msg := range messages {
timeSinceMessage := now.Sub(msg.Timestamp)
if timeSinceMessage <= 1*time.Minute {
hasNewMessage = true
fmt.Printf("New message detected in channel %s: %s (by %s)\n",
channelID, msg.Content, msg.Author.Username)
break
}
}

if hasNewMessage {
_, err := initializers.DB.Actions.FindUnique(
db.Actions.ID.Equals(actionID),
).Update(
db.Actions.Triggered.Set(true),
).Exec(ctx)

if err != nil {
fmt.Println("Error updating action trigger:", err)
}
}
}
2 changes: 2 additions & 0 deletions authentification/discordAuth.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ func getDiscordOAuthConfig() *oauth2.Config {
Scopes: []string{
"identify",
"email",
"guilds",
"messages.read",
},
Endpoint: oauth2.Endpoint{
AuthURL: "https://discord.com/api/oauth2/authorize",
Expand Down
1 change: 1 addition & 0 deletions templates/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ var Services = map[string]*Service{
Required: true,
},
},
Handler: action.ExecDiscordNewMsg,
},
},
Reactions: map[string]*ReactionDefinition{
Expand Down