bot

package
v0.0.0-...-c37b5aa Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 14, 2024 License: GPL-3.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Chat commands
	GetUserInfoFromChatCommandContext = "query"
	AddCustomSlashCommand             = "addcommand"
	RemoveCustomSlashCommand          = "deletecommand"

	// Modals
	SaveCustomSlashCommand   = "Save custom slash command"
	DeleteCustomSlashCommand = "Remove custom slash command"

	// Modal options
	CustomSlashName               = "Name for this custom slash command"
	CustomSlashCommandDescription = "Description for this custom slash command"
	CustomSlashCommandContent     = "Message to paste if this command is used"
	CustomCommandIdentifier       = "Custom command: "

	// Constants
	MaxCommandContentLength     = 32   // https://discord.com/developers/docs/interactions/application-commands#create-global-application-command
	MaxMessageContentLength     = 2000 // https://discord.com/developers/docs/resources/channel#create-message
	MaxDescriptionContentLength = 100  // https://discord.com/developers/docs/interactions/application-commands#application-command-object
)
View Source
const (
	// User commands
	GetUserInfoFromUserContext      = "Check info"
	DocumentBehaviorFromUserContext = "Save evidence"

	// Message commands
	GetUserInfoFromMessageContext      = "Get user info"
	DocumentBehaviorFromMessageContext = "Save as evidence"

	// Settings (the names affect the column names in the DB)
	EvidenceChannelSettingID = "Evidence channel"
	ModeratorRoleSettingID   = "Moderator role"

	// Moderation buttons
	IncreaseUserReputation      = "⬆️ Reputation"
	DecreaseUserReputation      = "⬇️ Reputation"
	ShowEvidenceCollectionModal = "Add notes"
	SubmitReport                = "Submit report"

	// Modals
	SaveEvidenceNotes = "Save evidence notes"

	// Modal options
	EvidenceNotes = "Evidence notes"

	// Text fragments
	CurrentReputation      = "Current reputation"
	PreviousReputation     = "Previous reputation"
	ModerationSuccessful   = "Moderation action saved"
	ModerationUnSuccessful = "There was a problem saving moderation action"
	OriginalMessageContent = "Content of original message"
	Attachments            = "Attachments"
	Notes                  = "Notes"
)
View Source
const (

	// Premade Option IDs (semi-reusable)
	// TODO: actions that delete messages, ban users etc
	UserOption    = "user"
	ChannelOption = "channel"
	MessageOption = "message"
	ReasonOption  = "reason"

	// Colors
	FrenchGray = 13424349
	Purple     = 7283691
	DarkRed    = 9109504
	Green      = 4306266

	// If images have this in front of their name, they're spoilered
	Spoiler = "SPOILER_"

	// Errors
	UnexpectedRowsAffected = "unexpected number of rows affected getting user reputation: %v"

	// URLs
	MessageURLTemplate = "https://discord.com/channels/%s/%s/%s"
)
View Source
const (
	// Slash command
	Help = "help"

	BotHelpText = `**Usage**
		In the Discord app, right click (Desktop) or long press (mobile) a message or user to see the available options.
	
	Configure the bot (Highly recommended to do so only people in a specific role can use the moderation commands):
	
	` + "`/settings`" + `
	
	Look up a user (more coming soon):
	
	` + "`/query`" + `
	
	Add a custom command (simply posts your desired block of text, Markdown formatting enabled)
	
	` + "`/addcommand`" + `
	
	Remove a custom command
	
	` + "`/deletecommand`" + `
	
	Get this help message:
	
	` + "`/help`"
)
View Source
const (
	// Slash command
	Settings                     = "settings"
	SettingFailedResponseMessage = "Error changing setting"
)

Variables

View Source
var (
	ChatCommands = []*discordgo.ApplicationCommand{
		{
			Name:        Help,
			Description: "How to use this bot",
		},
		{
			Name:        GetUserInfoFromChatCommandContext,
			Description: "Check a user's reputation information",
			Type:        discordgo.ChatApplicationCommand,
			Options: []*discordgo.ApplicationCommandOption{
				{
					Name:        UserOption,
					Description: "User to look up",
					Type:        discordgo.ApplicationCommandOptionString,
					Required:    true,
				},
			},
		},
		{
			Name:        Settings,
			Description: "Change settings",
		},
		{
			Name:        AddCustomSlashCommand,
			Description: "Create custom slash command",
		},
		{
			Name:        RemoveCustomSlashCommand,
			Description: "Remove custom slash command",
		},
	}
	UserCommands = []*discordgo.ApplicationCommand{
		{
			Name: GetUserInfoFromUserContext,
			Type: discordgo.UserApplicationCommand,
		},
		{
			Name: DocumentBehaviorFromUserContext,
			Type: discordgo.UserApplicationCommand,
		},
	}
	MessageCommands = []*discordgo.ApplicationCommand{
		{
			Name: GetUserInfoFromMessageContext,
			Type: discordgo.MessageApplicationCommand,
		},
		{
			Name: DocumentBehaviorFromMessageContext,
			Type: discordgo.MessageApplicationCommand,
		},
	}

	RegisteredCommands = []*discordgo.ApplicationCommand{}

	// This object is used to register chat commands, so if it's
	// not in here, it won't get registered properly. This is updated
	// during runtime.
	ConfiguredCommands = append(append(ChatCommands, UserCommands...), MessageCommands...)
)
View Source
var (
	// Enabled takes a boolean and returns "enabled" or "disabled" as a string
	Enabled = map[bool]string{
			// contains filtered or unexported fields
	}
	// Takes a boolean and returns a colorized button if true
	ActiveButton = map[bool]discordgo.ButtonStyle{
					// contains filtered or unexported fields
	}
)

Functions

This section is empty.

Types

type CustomCommand

type CustomCommand struct {
	ID            string
	GuildConfigID string `gorm:"type:varchar(191)"`
	Name          string
	Description   string
	Content       string
}

Custom commands registered with a specific server ID is registered with the Discord API GuildConfigID is the server ID where the command is registered

type GuildConfig

type GuildConfig struct {
	ID                       string          `pretty:"Server ID" gorm:"type:varchar(191)"`
	Name                     string          `pretty:"Server Name" gorm:"default:default"`
	Active                   *bool           `pretty:"Bot is active in the server" gorm:"default:true"`
	EvidenceChannelSettingID string          `pretty:"Channel to document evidence in"`
	ModeratorRoleSettingID   string          `pretty:"Role for moderators"`
	CustomCommands           []CustomCommand `pretty:"Custom commands"`
}

Servers are called Guilds in the Discord API

type ModeratedUser

type ModeratedUser struct {
	ID               string
	GuildId          string
	GuildName        string
	UserID           string
	UserName         string
	ModerationEvents []ModerationEvent
	Reputation       *int64 `gorm:"default:1"`
}

A ModeratedUser represents a specific user/server combination that serves to record events and a "Reputation" which is only visible to people who are in the moderator's configurable role.

type ModerationEvent

type ModerationEvent struct {
	ID                 uint `gorm:"primaryKey"`
	ModeratedUserID    string
	GuildId            string
	GuildName          string
	UserID             string
	UserName           string
	Notes              string
	PreviousReputation *int64
	CurrentReputation  *int64
	ModeratorID        string
	ModeratorName      string
	ReportURL          string
}

This is the representation of a moderation action

type ModeratorBot

type ModeratorBot struct {
	DB     *gorm.DB
	DG     *discordgo.Session
	Config ModeratorBotConfig
}

Handlers ModeratorBot is the main type passed around throughout the code It has many functions for overall bot management

func (*ModeratorBot) BotReadyHandler

func (bot *ModeratorBot) BotReadyHandler(s *discordgo.Session, r *discordgo.Ready)

BotReadyHandler is called when the bot is considered ready to use the Discord session

func (*ModeratorBot) ChangeUserReputation

func (bot *ModeratorBot) ChangeUserReputation(i *discordgo.InteractionCreate, difference int) (err error)

Updates a user reputation, given the source interaction and value to add

func (*ModeratorBot) CreateCustomSlashCommandFromChatCommandContext

func (bot *ModeratorBot) CreateCustomSlashCommandFromChatCommandContext(i *discordgo.InteractionCreate)

Creates a new slash command

func (*ModeratorBot) DeleteCustomSlashCommandFromButtonContext

func (bot *ModeratorBot) DeleteCustomSlashCommandFromButtonContext(i *discordgo.InteractionCreate, commandID string)

Deletes a custom command

func (*ModeratorBot) DeleteCustomSlashCommandFromChatCommandContext

func (bot *ModeratorBot) DeleteCustomSlashCommandFromChatCommandContext(i *discordgo.InteractionCreate)

func (*ModeratorBot) DocumentBehaviorFromButtonContext

func (bot *ModeratorBot) DocumentBehaviorFromButtonContext(i *discordgo.InteractionCreate)

Called from the App menu, this displays an embed for the moderator to choose to change the reputation of the posting user and (PLANNED) produces output in the evidence channel with information about the message, user and moderation actions taken

func (*ModeratorBot) DocumentBehaviorFromMessageContext

func (bot *ModeratorBot) DocumentBehaviorFromMessageContext(i *discordgo.InteractionCreate)

Called from the App menu, this displays an embed for the moderator to choose to change the reputation of the posting user and (PLANNED) produces output in the evidence channel with information about the message, user and moderation actions taken

func (*ModeratorBot) DocumentBehaviorFromUserContext

func (bot *ModeratorBot) DocumentBehaviorFromUserContext(i *discordgo.InteractionCreate)

Very similar to GenerateEvidenceReportFromMessageContext, but this is called when the target is a user and not a message, therefore this will be implicitly without any message reference

func (*ModeratorBot) GenerateEvidenceReportFromMessage

func (bot *ModeratorBot) GenerateEvidenceReportFromMessage(i *discordgo.InteractionCreate, message *discordgo.Message) (resp *discordgo.InteractionResponse)

Returns a discordgo.InteractionResponse with an evidence report based on a message provided

func (*ModeratorBot) GetCustomCommandHandlers

func (bot *ModeratorBot) GetCustomCommandHandlers() (cmds map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate))

GetCustomCommandHandlers returns a map[string]func of command handlers for every ServerConfig

func (*ModeratorBot) GetHelpFromChatCommandContext

func (bot *ModeratorBot) GetHelpFromChatCommandContext(i *discordgo.InteractionCreate)

This produces the help text seen from the chat commant `/help`

func (*ModeratorBot) GetModeratedUser

func (bot *ModeratorBot) GetModeratedUser(GuildId string, userID string) (moderatedUser ModeratedUser)

Returns a ModeratedUser record from the DB using server and user ID (a user can be in multiple servers)

func (*ModeratorBot) GetUserInfoFromChatCommandContext

func (bot *ModeratorBot) GetUserInfoFromChatCommandContext(i *discordgo.InteractionCreate)

Gets user info from the `/query` command

func (*ModeratorBot) GetUserInfoFromMessageContext

func (bot *ModeratorBot) GetUserInfoFromMessageContext(i *discordgo.InteractionCreate)

Produces user info such as reputation and (PLANNED) stats

func (*ModeratorBot) GetUserInfoFromUserContext

func (bot *ModeratorBot) GetUserInfoFromUserContext(i *discordgo.InteractionCreate)

Produces user info such as reputation and (PLANNED) stats

func (*ModeratorBot) GuildCreateHandler

func (bot *ModeratorBot) GuildCreateHandler(s *discordgo.Session, gc *discordgo.GuildCreate)

GuildCreateHandler is called whenever the bot joins a new guild.

func (*ModeratorBot) GuildDeleteHandler

func (bot *ModeratorBot) GuildDeleteHandler(s *discordgo.Session, gd *discordgo.GuildDelete)

GuildDeleteHandler is called whenever the bot leaves a guild.

func (*ModeratorBot) InteractionHandler

func (bot *ModeratorBot) InteractionHandler(s *discordgo.Session, i *discordgo.InteractionCreate)

InteractionInit configures all interactive commands

func (*ModeratorBot) RegisterCustomCommandHandler

func (bot *ModeratorBot) RegisterCustomCommandHandler(cmds []CustomCommand)

RegisterCustomCommandHandler registers the provided commands

func (*ModeratorBot) RespondToSettingsChoice

func (bot *ModeratorBot) RespondToSettingsChoice(i *discordgo.InteractionCreate,
	setting string, value string)

Updates a server setting according to the column name (setting) and the value

func (*ModeratorBot) SaveCustomSlashCommand

func (bot *ModeratorBot) SaveCustomSlashCommand(i *discordgo.InteractionCreate)

Takes user-submitted command and adds it to the server config and registers it in the guild

func (*ModeratorBot) SaveEvidenceNotes

func (bot *ModeratorBot) SaveEvidenceNotes(i *discordgo.InteractionCreate)

Takes user-submitted notes and adds it to an in-progress report

func (*ModeratorBot) SetSettingsFromChatCommandContext

func (bot *ModeratorBot) SetSettingsFromChatCommandContext(i *discordgo.InteractionCreate)

Sets setting choices from the `/settings` command

func (*ModeratorBot) SettingsIntegrationResponse

func (bot *ModeratorBot) SettingsIntegrationResponse(cfg GuildConfig) *discordgo.InteractionResponseData

SettingsIntegrationResponse returns server settings in a *discordgo.InteractionResponseData

func (*ModeratorBot) ShowEvidenceCollectionModal

func (bot *ModeratorBot) ShowEvidenceCollectionModal(i *discordgo.InteractionCreate)

ShowEvidenceCollectionModal shows the user a modal to fill in information about selected evidence

func (*ModeratorBot) StartHealthAPI

func (b *ModeratorBot) StartHealthAPI()

Starts a simple health API that pings the DB

func (*ModeratorBot) SubmitReport

func (bot *ModeratorBot) SubmitReport(i *discordgo.InteractionCreate)

Submits evidence to the configured channel (including notes)

func (*ModeratorBot) UpdateCommands

func (bot *ModeratorBot) UpdateCommands() (err error)

UpdateCommands iterates through all configured commands and ensures they are registered, updated or removed

func (*ModeratorBot) UpdateInactiveRegistrations

func (bot *ModeratorBot) UpdateInactiveRegistrations(activeGuilds []*discordgo.Guild)

UpdateInactiveRegistrations goes through every server registration and updates the DB as to whether or not it's active

func (*ModeratorBot) UseCustomSlashCommandFromChatCommandContext

func (bot *ModeratorBot) UseCustomSlashCommandFromChatCommandContext(i *discordgo.InteractionCreate, content string)

Creates a new slash command

type ModeratorBotConfig

type ModeratorBotConfig struct {
	DBType     string `env:"DB_TYPE"`
	DBHost     string `env:"DB_HOST"`
	DBPort     string `env:"DB_PORT"`
	DBName     string `env:"DB_NAME"`
	DBPassword string `env:"DB_PASSWORD"`
	DBUser     string `env:"DB_USER"`
	LogLevel   string `env:"LOG_LEVEL"`
	Token      string `env:"TOKEN"`
}

ModeratorBotConfig is attached to ModeratorBot so config settings can be accessed easily

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL