Skip to content

Commit

Permalink
Major Refactor (#2)
Browse files Browse the repository at this point in the history
* Major reworks

* More refactoring

* Refactor feature complete!

* Comments

* Add versioning
  • Loading branch information
yeslayla authored Oct 29, 2022
1 parent 49aa4fd commit 696ab72
Show file tree
Hide file tree
Showing 18 changed files with 403 additions and 186 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/publish_release.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ jobs:
make test
- name: Build
run: |
make build
make build VERSION="${{ env.RELEASE_VERSION }}"
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/validate.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@ jobs:
make test
- name: Build
run: |
make build
make build VERSION="test"
4 changes: 3 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
PROJECTNAME="Bird Bot"
PROJECT_BIN="birdbot"
VERSION="DEV"
BUILD_NUMBER:=$(shell date "+%s%N" | cut -b1-13)

# Go related variables.
GOBASE=$(shell pwd)
Expand All @@ -14,7 +16,7 @@ go-full-build: go-clean go-get go-build
go-build:
@echo " > Building binary..."
@mkdir -p $(GOBIN)
@GOOS=linux CGO_ENABLED=0 go build -o $(GOBIN)/$(PROJECT_BIN) $(GOFILES)
@GOOS=linux CGO_ENABLED=0 go build -ldflags "-X github.com/yeslayla/birdbot/app.Version=$(VERSION) -X github.com/yeslayla/birdbot/app.Build=$(BUILD_NUMBER)" -o $(GOBIN)/$(PROJECT_BIN) $(GOFILES)
@chmod 755 $(GOBIN)/$(PROJECT_BIN)

go-generate:
Expand Down
150 changes: 47 additions & 103 deletions app/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,28 @@ import (
"log"
"os"

"github.com/bwmarrin/discordgo"
"github.com/ilyakaznacheev/cleanenv"
"github.com/yeslayla/birdbot/core"
"github.com/yeslayla/birdbot/discord"
)

var Version string
var Build string

type Bot struct {
discord *discordgo.Session
session *discord.Discord

// Discord Objects
guildID string
eventCategoryID string
archiveCategoryID string
notificationChannelID string

// Signal for shutdown
stop chan os.Signal
}

// Initalize creates the discord session and registers handlers
func (app *Bot) Initialize(config_path string) error {
log.Printf("Using config: %s", config_path)
cfg := &Config{}
cfg := &core.Config{}

_, err := os.Stat(config_path)
if errors.Is(err, os.ErrNotExist) {
Expand All @@ -51,171 +52,114 @@ func (app *Bot) Initialize(config_path string) error {
return fmt.Errorf("discord Guild ID is not set")
}

// Create Discord Session
app.discord, err = discordgo.New(fmt.Sprint("Bot ", cfg.Discord.Token))
if err != nil {
return fmt.Errorf("failed to create Discord session: %v", err)
}
app.session = discord.New(app.guildID, cfg.Discord.Token)

// Register Event Handlers
app.discord.AddHandler(app.onReady)
app.discord.AddHandler(app.onEventCreate)
app.discord.AddHandler(app.onEventDelete)
app.discord.AddHandler(app.onEventUpdate)
app.session.OnReady(app.onReady)
app.session.OnEventCreate(app.onEventCreate)
app.session.OnEventDelete(app.onEventDelete)
app.session.OnEventUpdate(app.onEventUpdate)

return nil
}

// Run opens the session with Discord until exit
func (app *Bot) Run() error {

if err := app.discord.Open(); err != nil {
return fmt.Errorf("failed to open Discord session: %v", err)
}
defer app.discord.Close()

// Keep alive
app.stop = make(chan os.Signal, 1)
<-app.stop
return nil
return app.session.Run()
}

// Stop triggers a graceful shutdown of the app
func (app *Bot) Stop() {
log.Print("Shuting down...")
app.stop <- os.Kill
app.session.Stop()
}

// Notify sends a message to the notification channe;
func (app *Bot) Notify(message string) {
if app.notificationChannelID == "" {
log.Println(message)
return
}

_, err := app.discord.ChannelMessageSend(app.notificationChannelID, message)
log.Print("Notification: ", message)

channel := app.session.NewChannelFromID(app.notificationChannelID)
if channel == nil {
log.Printf("Failed notification: channel was not found with ID '%v'", app.notificationChannelID)
}

log.Println("Notification: ", message)
err := app.session.SendMessage(channel, message)
if err != nil {
log.Println("Failed notification: ", err)
log.Print("Failed notification: ", err)
}
}

func (app *Bot) onReady(s *discordgo.Session, r *discordgo.Ready) {
app.Notify("BirdBot is ready!")
log.Print("BirdBot is ready!")
func (app *Bot) onReady(d *discord.Discord) {
app.Notify(fmt.Sprintf("BirdBot %s is ready!", Version))
}

func (app *Bot) onEventCreate(s *discordgo.Session, r *discordgo.GuildScheduledEventCreate) {
if r.GuildID != app.guildID {
return
}
func (app *Bot) onEventCreate(d *discord.Discord, event *core.Event) {

event := &Event{}
event.Name = r.Name
event.OrganizerID = r.CreatorID
event.DateTime = r.ScheduledStartTime
if r.EntityType != discordgo.GuildScheduledEventEntityTypeExternal {
event.Location = REMOTE_LOCATION
} else {
event.Location = r.EntityMetadata.Location
}
log.Print("Event Created: '", event.Name, "':'", event.Location, "'")

channel, err := CreateChannelIfNotExists(s, app.guildID, event.GetChannelName())
channel, err := app.session.NewChannelFromName(event.Channel().Name)
if err != nil {
log.Print("Failed to create channel for event: ", err)
}

if app.eventCategoryID != "" {
if _, err = s.ChannelEdit(channel.ID, &discordgo.ChannelEdit{
ParentID: app.eventCategoryID,
}); err != nil {
err = app.session.MoveChannelToCategory(channel, app.eventCategoryID)
if err != nil {
log.Printf("Failed to move channel to events category '%s': %v", channel.Name, err)
}
}

eventURL := fmt.Sprintf("https://discordapp.com/events/%s/%s", app.guildID, r.ID)
app.Notify(fmt.Sprintf("<@%s> is organizing an event '%s': %s", event.OrganizerID, event.Name, eventURL))
eventURL := fmt.Sprintf("https://discordapp.com/events/%s/%s", app.guildID, event.ID)
app.Notify(fmt.Sprintf("%s is organizing an event '%s': %s", event.Organizer.Mention(), event.Name, eventURL))
}

func (app *Bot) onEventDelete(s *discordgo.Session, r *discordgo.GuildScheduledEventDelete) {
if r.GuildID != app.guildID {
return
}
func (app *Bot) onEventDelete(d *discord.Discord, event *core.Event) {

// Create Event Object
event := &Event{}
event.Name = r.Name
event.OrganizerID = r.CreatorID
event.DateTime = r.ScheduledStartTime
if r.EntityType != discordgo.GuildScheduledEventEntityTypeExternal {
event.Location = REMOTE_LOCATION
} else {
event.Location = r.EntityMetadata.Location
}

_, err := DeleteChannel(app.discord, app.guildID, event.GetChannelName())
_, err := app.session.DeleteChannel(event.Channel())
if err != nil {
log.Print("Failed to create channel for event: ", err)
}

app.Notify(fmt.Sprintf("<@%s> cancelled '%s' on %s, %d!", event.OrganizerID, event.Name, event.DateTime.Month().String(), event.DateTime.Day()))
app.Notify(fmt.Sprintf("%s cancelled '%s' on %s, %d!", event.Organizer.Mention(), event.Name, event.DateTime.Month().String(), event.DateTime.Day()))
}

func (app *Bot) onEventUpdate(s *discordgo.Session, r *discordgo.GuildScheduledEventUpdate) {
if r.GuildID != app.guildID {
return
}

// Create Event Object
event := &Event{}
event.Name = r.Name
event.OrganizerID = r.CreatorID
event.DateTime = r.ScheduledStartTime
if r.EntityType != discordgo.GuildScheduledEventEntityTypeExternal {
event.Location = REMOTE_LOCATION
} else {
event.Location = r.EntityMetadata.Location
}

func (app *Bot) onEventUpdate(d *discord.Discord, event *core.Event) {
// Pass event onwards
switch r.Status {
case discordgo.GuildScheduledEventStatusCompleted:
app.onEventComplete(s, event)
if event.Completed {
app.onEventComplete(d, event)
}
}

func (app *Bot) onEventComplete(s *discordgo.Session, event *Event) {
func (app *Bot) onEventComplete(d *discord.Discord, event *core.Event) {

channel_name := event.GetChannelName()
channel := event.Channel()

if app.archiveCategoryID != "" {

// Get Channel ID
id, err := GetChannelID(s, app.guildID, channel_name)
if err != nil {
log.Printf("Failed to archive channel: %v", err)
return
if err := app.session.MoveChannelToCategory(channel, app.archiveCategoryID); err != nil {
log.Print("Failed to move channel to archive category: ", err)
}

// Move to archive category
if _, err := s.ChannelEdit(id, &discordgo.ChannelEdit{
ParentID: app.archiveCategoryID,
}); err != nil {
log.Printf("Failed to move channel to archive category: %v", err)
return
if err := app.session.ArchiveChannel(channel); err != nil {
log.Print("Failed to archive channel: ", err)
}

log.Printf("Archived channel: '%s'", channel_name)
log.Printf("Archived channel: '%s'", channel.Name)

} else {

// Delete Channel
_, err := DeleteChannel(s, app.guildID, channel_name)
_, err := app.session.DeleteChannel(channel)
if err != nil {
log.Print("Failed to delete channel: ", err)
}

log.Printf("Deleted channel: '%s'", channel_name)
log.Printf("Deleted channel: '%s'", channel.Name)
}
}

Expand Down
68 changes: 0 additions & 68 deletions app/channel.go

This file was deleted.

7 changes: 7 additions & 0 deletions core/channel.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package core

type Channel struct {
Name string
ID string
Verified bool
}
2 changes: 1 addition & 1 deletion app/configuration.go → core/configuration.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package app
package core

type Config struct {
Discord DiscordConfig `yaml:"discord"`
Expand Down
Loading

0 comments on commit 696ab72

Please sign in to comment.