Skip to content
Draft
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
5 changes: 3 additions & 2 deletions src/discord/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,11 @@ func init() {
}

guildMember, err := discord.GetGuildMember(ctx, config.Config.Discord.GuildID, message.Author.ID) // NOTE(asaf): We assume we're only working with one guild, because the discord API sucks and doesn't provide the guild in the message payload.
if err != nil {
if err == nil {
message.Member = &guildMember
} else {
logging.Error().Err(err).Msg("failed to get guild member for message while scraping")
}
message.Member = guildMember

err = discord.HandleIncomingMessage(ctx, conn, message, true)
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions src/discord/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func (bot *botInstance) doInteraction(ctx context.Context, i *Interaction) {

if join {
logging.ExtractLogger(ctx).Debug().Interface("interaction", i).Msg("Got hmh replay")
err := AddGuildMemberRole(ctx, i.Member.User.ID, config.Config.Discord.HMHReplayRoleID)
err := AddGuildMemberRole(ctx, i.Member.User.ID, config.Config.Discord.HMHReplayRoleID, "HMH Replay slash command")
if err != nil {
err = sendEphemeralMessageForInteraction(ctx, i, "We failed to set the role. Please inform an admin.")
if err != nil {
Expand All @@ -139,7 +139,7 @@ func (bot *botInstance) doInteraction(ctx context.Context, i *Interaction) {
}
}
} else {
err := RemoveGuildMemberRole(ctx, i.Member.User.ID, config.Config.Discord.HMHReplayRoleID)
err := RemoveGuildMemberRole(ctx, i.Member.User.ID, config.Config.Discord.HMHReplayRoleID, "HMH Replay slash command")
if err != nil {
err = sendEphemeralMessageForInteraction(ctx, i, "We failed to remove the role. Please inform an admin.")
if err != nil {
Expand Down Expand Up @@ -188,7 +188,7 @@ func (bot *botInstance) doInteraction(ctx context.Context, i *Interaction) {
// Give user the Discord role
roleID := hmndata.LatestJam.DiscordRoleIDs[config.Config.Env]
utils.Assert(roleID)
err = AddGuildMemberRole(ctx, i.Member.User.ID, roleID)
err = AddGuildMemberRole(ctx, i.Member.User.ID, roleID, "/joinjam slash command")
if err != nil {
log.Error().Err(err).Msg("failed to give user the jam role")
errOccurred = true
Expand Down
42 changes: 22 additions & 20 deletions src/discord/gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@ type BotEvent struct {

var botEvents = make([]BotEvent, 0, 1000)
var botEventsMutex = sync.Mutex{}
var RecordAllGatewayMessages bool

func RecordBotEvent(name, extra string) {
func recordBotEvent(name, extra string) {
botEventsMutex.Lock()
defer botEventsMutex.Unlock()
if len(botEvents) > 1000 {
Expand Down Expand Up @@ -87,7 +88,7 @@ func RunDiscordBot(dbConn *pgxpool.Pool) *jobs.Job {
if err != nil {
disconnectMessage = err.Error()
}
RecordBotEvent("Disconnected", disconnectMessage)
recordBotEvent("Disconnected", disconnectMessage)
if err != nil {
dur := boff.Duration()
log.Error().
Expand Down Expand Up @@ -192,16 +193,14 @@ func (bot *botInstance) Run(ctx context.Context) (err error) {

for {
msg, err := bot.receiveGatewayMessage(ctx)
if err != nil {
if errors.Is(err, net.ErrClosed) {
// If the connection is closed, that's our cue to shut down the bot. Any errors
// related to the closure will have been logged elsewhere anyway.
return nil
} else {
// NOTE(ben): I don't know what events we might get in the future that we might
// want to handle gracefully (like above). Keep an eye out.
return oops.New(err, "failed to receive message from the gateway")
}
if errors.Is(err, net.ErrClosed) {
// If the connection is closed, that's our cue to shut down the bot. Any errors
// related to the closure will have been logged elsewhere anyway.
return nil
} else if err != nil {
// NOTE(ben): I don't know what events we might get in the future that we might
// want to handle gracefully (like above). Keep an eye out.
return oops.New(err, "failed to receive message from the gateway")
}

// Update the sequence number in the db
Expand All @@ -227,7 +226,7 @@ func (bot *botInstance) Run(ctx context.Context) (err error) {
logging.ExtractLogger(ctx).Info().Msg("Discord asked us to reconnect to the gateway")
return nil
case OpcodeInvalidSession:
RecordBotEvent("Failed to resume - invalid session", "")
recordBotEvent("Failed to resume - invalid session", "")
// We tried to resume but the session was invalid.
// Delete the session and reconnect from scratch again.
_, err := bot.dbConn.Exec(ctx, `DELETE FROM discord_session`)
Expand Down Expand Up @@ -299,9 +298,9 @@ func (bot *botInstance) connect(ctx context.Context) error {
}
}

RecordBotEvent("Connected", "")
recordBotEvent("Connected", "")
if shouldResume {
RecordBotEvent("Resuming with session ID", session.ID)
recordBotEvent("Resuming with session ID", session.ID)
// Reconnect to the previous session
bot.resuming = true
err := bot.sendGatewayMessage(ctx, GatewayMessage{
Expand Down Expand Up @@ -551,6 +550,9 @@ func (bot *botInstance) receiveGatewayMessage(ctx context.Context) (*GatewayMess
if err != nil {
return nil, err
}
if RecordAllGatewayMessages {
recordBotEvent("Gateway message", string(msgBytes))
}

var msg GatewayMessage
err = json.Unmarshal(msgBytes, &msg)
Expand Down Expand Up @@ -583,27 +585,27 @@ func (bot *botInstance) processEventMsg(ctx context.Context, msg *GatewayMessage
if msg.EventName != nil {
name = *msg.EventName
}
RecordBotEvent("Got event while resuming", name)
recordBotEvent("Got event while resuming", name)
}
switch *msg.EventName {
case "RESUMED":
// Nothing to do, but at least we can log something
logging.ExtractLogger(ctx).Info().Msg("Finished resuming gateway session")

bot.resuming = false
RecordBotEvent("Done resuming", "")
recordBotEvent("Done resuming", "")
bot.createApplicationCommands(ctx)
case "MESSAGE_CREATE":
newMessage := *MessageFromMap(msg.Data, "")

err := bot.messageCreateOrUpdate(ctx, &newMessage)
err := bot.messageCreateOrUpdate(ctx, newMessage)
if err != nil {
return oops.New(err, "error on new message")
}
case "MESSAGE_UPDATE":
newMessage := *MessageFromMap(msg.Data, "")

err := bot.messageCreateOrUpdate(ctx, &newMessage)
err := bot.messageCreateOrUpdate(ctx, newMessage)
if err != nil {
return oops.New(err, "error on updated message")
}
Expand Down Expand Up @@ -633,7 +635,7 @@ func (bot *botInstance) processEventMsg(ctx context.Context, msg *GatewayMessage
}

// Only return an error if we want to restart the bot.
func (bot *botInstance) messageCreateOrUpdate(ctx context.Context, msg *Message) error {
func (bot *botInstance) messageCreateOrUpdate(ctx context.Context, msg Message) error {
if msg.OriginalHasFields("author") && msg.Author.ID == config.Config.Discord.BotUserID {
// Don't process your own messages
return nil
Expand Down
8 changes: 4 additions & 4 deletions src/discord/history.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,10 +171,10 @@ func ScrapeRecents(ctx context.Context, dbConn *pgxpool.Pool, channelID string,
logging.Error().Err(err).Msg("failed to get guild member for message while scraping")
return false
}
msg.Member = guildMember
msg.Member = &guildMember

msg.Backfilled = true
err = HandleIncomingMessage(ctx, dbConn, &msg, false)
err = HandleIncomingMessage(ctx, dbConn, msg, false)

if err != nil {
errLog := logging.ExtractLogger(ctx).Error()
Expand Down Expand Up @@ -226,9 +226,9 @@ func ScrapeAll(ctx context.Context, dbConn *pgxpool.Pool, channelID string, earl
}

msg.Backfilled = true
err := TrackMessage(ctx, dbConn, &msg)
err := TrackMessage(ctx, dbConn, msg)
if err == nil {
err = UpdateInternedMessage(ctx, dbConn, &msg, false, false, false)
err = UpdateInternedMessage(ctx, dbConn, msg, false, false, false)
}

if err != nil {
Expand Down
16 changes: 8 additions & 8 deletions src/discord/message_handling.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func shouldAutomaticallyCreateSnippet(interned *InternedMessage) bool {
}
}

func HandleIncomingMessage(ctx context.Context, dbConn db.ConnOrTx, msg *Message, notifyUser bool) error {
func HandleIncomingMessage(ctx context.Context, dbConn db.ConnOrTx, msg Message, notifyUser bool) error {
var deleted bool
var err error

Expand Down Expand Up @@ -96,7 +96,7 @@ var githubRegex = regexp.MustCompile(`^(https:\/\/)?(www\.|gist\.)?github.com`)
var steampoweredRegex = regexp.MustCompile(`steampowered\.com`)
var steamCutoffDate = time.Date(2026, 5, 10, 0, 0, 0, 0, time.UTC)

func cleanUpShowcase(ctx context.Context, dbConn db.ConnOrTx, msg *Message) (bool, error) {
func cleanUpShowcase(ctx context.Context, dbConn db.ConnOrTx, msg Message) (bool, error) {
if msg.ChannelID != config.Config.Discord.ShowcaseChannelID {
return false, nil
}
Expand Down Expand Up @@ -155,7 +155,7 @@ func cleanUpShowcase(ctx context.Context, dbConn db.ConnOrTx, msg *Message) (boo
return false, nil
}

func cleanUpLibrary(ctx context.Context, dbConn db.ConnOrTx, msg *Message) (bool, error) {
func cleanUpLibrary(ctx context.Context, dbConn db.ConnOrTx, msg Message) (bool, error) {
if msg.ChannelID != config.Config.Discord.LibraryChannelID {
return false, nil
}
Expand Down Expand Up @@ -191,7 +191,7 @@ record of the message itself.
func TrackMessage(
ctx context.Context,
dbConn db.ConnOrTx,
msg *Message,
msg Message,
) error {
if !msg.OriginalHasFields("author", "timestamp") {
return errNotEnoughInfo
Expand Down Expand Up @@ -257,7 +257,7 @@ func FetchInternedMessage(ctx context.Context, dbConn db.ConnOrTx, msgId string)
func UpdateInternedMessage(
ctx context.Context,
dbConn db.ConnOrTx,
msg *Message,
msg Message,
messageDeleted bool, // whether the message was deleted before this update, e.g. as part of showcase cleanup
canCreateSnippet bool, // if false, no snippet will be created for this message regardless of contents
notifyUser bool, // whether to notify the user of any problems with their message
Expand Down Expand Up @@ -363,7 +363,7 @@ func SaveMessageContents(
ctx context.Context,
dbConn db.ConnOrTx,
interned *InternedMessage,
msg *Message,
msg Message,
notifyUser bool,
) (contentChanged bool, err error) {
if interned.DiscordUser == nil {
Expand Down Expand Up @@ -1013,7 +1013,7 @@ func messageHasLinks(content string) bool {
return false
}

func messageIsSnippetable(msg *Message) bool {
func messageIsSnippetable(msg Message) bool {
hasGoodContent := true
if msg.OriginalHasFields("content") && !messageHasLinks(msg.Content) {
hasGoodContent = false
Expand Down Expand Up @@ -1062,7 +1062,7 @@ func SendDM(ctx context.Context, dbConn db.ConnOrTx, authorID string, text strin
return nil
}

func RebukeMessage(ctx context.Context, dbConn db.ConnOrTx, msg *Message, noteToUser string) (deleted bool, err error) {
func RebukeMessage(ctx context.Context, dbConn db.ConnOrTx, msg Message, noteToUser string) (deleted bool, err error) {
err = DeleteMessage(ctx, msg.ChannelID, msg.ID)
if err != nil {
return false, oops.New(err, "failed to delete message")
Expand Down
Loading
Loading