Skip to content

Commit

Permalink
latest: Spring 24 Final Exam Routine Added
Browse files Browse the repository at this point in the history
Schedule message added
bug fix. Remove total message use command
  • Loading branch information
monzim committed Apr 30, 2024
1 parent 8882653 commit 7ebac80
Show file tree
Hide file tree
Showing 19 changed files with 10,503 additions and 136 deletions.
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"cSpell.words": ["syronously"]
}
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# Stage 1: Build the Go application
FROM golang:1.22.0-alpine3.18 AS builder

WORKDIR /go/src/app

COPY . .
COPY public public

RUN go get -d -v
RUN go mod download
Expand All @@ -12,7 +12,7 @@ RUN CGO_ENABLED=0 GOOS=linux go build -o main .

FROM alpine:3.19.1

LABEL name="UIU Discord Bot" version="1.0.0"
LABEL name="UIU Discord Bot" version="2.0.2"
LABEL author="Azraf Al Monzim"
LABEL maintainer="Azraf Al Monzim"

Expand Down
61 changes: 61 additions & 0 deletions bot/cron.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package bot

import (
"os"
"time"

"github.com/monzim/uiuBot/models"
"github.com/rs/zerolog/log"
)

func (b *Bot) CronSchedule() {
interval, err := time.ParseDuration(os.Getenv("CRON_INTERVAL_DURATION"))
if err != nil {
log.Error().Err(err).Msg("Error parsing the interval")
interval = time.Minute * 5
}

ticker := time.NewTicker(interval)
defer ticker.Stop()

for range ticker.C {
go func() {
defer func() {
if r := recover(); r != nil {
log.Error().Msgf("Recovered from panic: %v", r)
}
}()

b.sendScheduledMessages(interval)
}()
}
}

func (b *Bot) sendScheduledMessages(interval time.Duration) {
var messages []models.CronMessage
err := b.DB.Where("done = ? AND send_time < ?", false, time.Now().Add(interval)).Find(&messages).Error

log.Info().Msgf("CRON Found %d messages to send", len(messages))

if err != nil {
log.Error().Err(err).Msg("Error fetching scheduled messages")
}

for _, message := range messages {
if message.SendTime.Before(time.Now()) {
discordMessage, err := b.Session.ChannelMessageSend(message.ChannelID, message.Message)
if err != nil {
log.Error().Err(err).Msg("Error sending scheduled message")
}

message.Done = true
err = b.DB.Save(&message).Error

if err != nil {
log.Error().Err(err).Msg("Error updating scheduled message")
}

log.Info().Msgf("Message sent to channel %s with message id %s", message.ChannelID, discordMessage.ID)
}
}
}
2 changes: 2 additions & 0 deletions commands/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ func GetCommands(db *gorm.DB) []*discordgo.ApplicationCommand {
helpHandler.Command,
handlerUserConfigure.Command,
handlerRamadanCalender.Command,
handleSendMessage.Command,
}
}

Expand Down Expand Up @@ -129,6 +130,7 @@ var (
helpHandler.Trigger: helpHandler.Handler,
handlerUserConfigure.Trigger: handlerUserConfigure.Handler,
handlerRamadanCalender.Trigger: handlerRamadanCalender.Handler,
handleSendMessage.Trigger: handleSendMessage.Handler,
}
)

Expand Down
32 changes: 18 additions & 14 deletions commands/exam_time.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ var (
SUPPORT_STRING = utils.SUPPORT_MESSAGE
)

const currentSemester = models.SPRING_24_FIN

var examTime = Commnad{
Trigger: "exam-time",
Command: &discordgo.ApplicationCommand{
Expand Down Expand Up @@ -77,6 +79,7 @@ var examTime = Commnad{
res := op.db.Where(models.Exam{
Department: strings.ToLower(department),
Section: strings.ToLower(section),
TrimsterID: currentSemester,
}).Where("course_code LIKE ?", "%"+strings.ToLower(strings.TrimSpace(courseCode))+"%").Find(&exams)

if res.Error != nil {
Expand All @@ -102,14 +105,15 @@ var examTime = Commnad{
". You may have entered course code incorrectly. Here is an example: `2213` or `cse 2213`. " +
"\n" + SUPPORT_STRING,

Embeds: []*discordgo.MessageEmbed{
// TODO: remove this embed when the final exam schedule is available
&discordgo.MessageEmbed{
Title: "This time is for Midterm",
Description: "Midterm is over. Please check your final exam schedule. If you have any question, feel free to ask.",
Color: utils.GenColorCode("Midterm"),
},
}},
// Embeds: []*discordgo.MessageEmbed{
// // TODO: remove this embed when the final exam schedule is available
// &discordgo.MessageEmbed{
// Title: "This time is for Midterm",
// Description: "Midterm is over. Please check your final exam schedule. If you have any question, feel free to ask.",
// Color: utils.GenColorCode("Midterm"),
// },
// },
},
})
return
}
Expand All @@ -129,12 +133,12 @@ var examTime = Commnad{
})
}

// TODO: remove this embed when the final exam schedule is available
embeds = append(embeds, &discordgo.MessageEmbed{
Title: "This time is for Midterm",
Description: "Midterm is over. Please check your final exam schedule. If you have any question, feel free to ask.",
Color: utils.GenColorCode("Midterm"),
})
// // TODO: remove this embed when the final exam schedule is available
// embeds = append(embeds, &discordgo.MessageEmbed{
// Title: "This time is for Midterm",
// Description: "Midterm is over. Please check your final exam schedule. If you have any question, feel free to ask.",
// Color: utils.GenColorCode("Midterm"),
// })

embeds[len(embeds)-1].Footer = &discordgo.MessageEmbedFooter{
Text: "Help Us Make a Difference",
Expand Down
2 changes: 1 addition & 1 deletion commands/help.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ var allCommands = []lol{
{Name: academyCalenderHandler.Trigger, Description: academyCalenderHandler.Command.Description},
{Name: handlerNoticeSearch.Trigger, Description: handlerNoticeSearch.Command.Description},
{Name: handlerUserConfigure.Trigger, Description: handlerUserConfigure.Command.Description},
{Name: handlerRamadanCalender.Trigger, Description: handlerRamadanCalender.Command.Description},
// {Name: handlerRamadanCalender.Trigger, Description: handlerRamadanCalender.Command.Description},
}

var helpHandler = Commnad{
Expand Down
1 change: 1 addition & 0 deletions commands/list-message.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package commands
141 changes: 141 additions & 0 deletions commands/send-message.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package commands

import (
"fmt"
"os"
"strconv"
"time"

"github.com/bwmarrin/discordgo"
"github.com/monzim/uiuBot/models"
)

var handleSendMessage = Commnad{
Trigger: "send-message",
Command: &discordgo.ApplicationCommand{
Name: "send-message",
Description: "This will send a message to you",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "message",
Description: "Input your message",
Required: true,
},

{
Type: discordgo.ApplicationCommandOptionString,
Name: "time",
Description: "Choose time unit",
Required: true,
Choices: []*discordgo.ApplicationCommandOptionChoice{
{
Name: "minutes",
Value: "minutes",
},
{
Name: "hours",
Value: "hours",
},
{
Name: "days",
Value: "days",
},
},
},

{
Type: discordgo.ApplicationCommandOptionString,
Name: "value",
Description: "Input the value",
Required: true,
},

{
Type: discordgo.ApplicationCommandOptionChannel,
Name: "channel",
Description: "Select the channel",
Required: true,
},
},
},

Handler: func(op *options) {
if !hasRole(op.in.Member.Roles, os.Getenv("ADMIN_ROLE_ID")) {
op.ses.InteractionRespond(op.in.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "You don't have permission to run this command",
},
})

return
}

input := op.in.ApplicationCommandData().Options

optionMap := make(map[string]*discordgo.ApplicationCommandInteractionDataOption, len(input))
for _, opt := range input {
optionMap[opt.Name] = opt
}

message := optionMap["message"].StringValue()
timeUnit := optionMap["time"].StringValue()
value := optionMap["value"].StringValue()
channel := optionMap["channel"].ChannelValue(op.ses)

sendTime := timeToDuration(timeUnit, value)
res := op.db.Create(&models.CronMessage{
Message: message,
ChannelID: channel.ID,
UserID: op.in.Member.User.ID,
SendTime: sendTime,
})

if res.Error != nil {
op.ses.InteractionRespond(op.in.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Failed to save schedule message. Please try again later.",
},
})
}

op.ses.InteractionRespond(op.in.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: fmt.Sprintf("Message scheduled for %s in %s", sendTime.Format(time.RFC1123), channel.Mention()),
},
})

},
}

func timeToDuration(timeUnit string, value string) time.Time {
var duration time.Duration
after, err := strconv.Atoi(value)
if err != nil {
duration = time.Minute * 10
}

switch timeUnit {
case "minutes":
duration = time.Minute * time.Duration(after).Abs()
case "hours":
duration = time.Hour * time.Duration(after).Abs()
case "days":
duration = time.Hour * 24 * time.Duration(after).Abs()
}

return time.Now().Add(duration)
}

func hasRole(roles []string, role string) bool {
for _, r := range roles {
if r == role {
return true
}
}

return false
}
4 changes: 2 additions & 2 deletions commands/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import (
"github.com/bwmarrin/discordgo"
)

var VERSION = "2.0.1"
var BUILD = time.Date(2024, time.March, 28, 20, 26, 01, 0, time.UTC)
var VERSION = "2.0.2"
var BUILD = time.Date(2024, time.May, 01, 00, 35, 01, 0, time.UTC)

var handlerVersion = Commnad{
Trigger: "version",
Expand Down
Loading

0 comments on commit 7ebac80

Please sign in to comment.