gokord

package module
v0.13.1 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2025 License: MPL-2.0 Imports: 25 Imported by: 4

README

Common

Common code shared between my bots.

Features

  • Creation of the bot (commands, status, handlers)
  • Basic config
  • Redis connection
  • Postgres connection
  • Various useful things (logger, timers)

Technologies

  • Go
  • go-redis
  • pelletier/go-toml
  • gorm

Documentation

Index

Constants

View Source
const (
	GameStatus      StatusType = 0
	WatchStatus     StatusType = 1
	StreamingStatus StatusType = 2
	ListeningStatus StatusType = 3

	AdminPermission int64 = discord.PermissionManageGuild // AdminPermission of the command
)
View Source
const (
	ConfigFolder = "config"
)

Variables

View Source
var (
	Debug = true

	ErrBadStatusType     = errors.New("bad status type, please use the constant")
	ErrStatusUrlNotFound = errors.New("status url not found")
)
View Source
var (
	ErrSubsAreNil         = errors.New("subs are nil in general handler")
	ErrSubCommandNotFound = errors.New("sub command not found")
)
View Source
var (
	// BaseCfg is the main BaseConfig used by the bot
	BaseCfg BaseConfig

	// UseRedis is true if the bot will use redis
	UseRedis = true

	ErrImpossibleToConnectDB         = errors.New("impossible to connect to the database")
	ErrImpossibleToConnectRedis      = errors.New("impossible to connect to redis")
	ErrMigratingGokordInternalModels = errors.New("error while migrating internal models")
)
View Source
var DB *gorm.DB

DB used

View Source
var (
	ErrNilClient = errors.New("redis.NewClient is nil")
)
View Source
var NilVersion = Version{Major: 0, Minor: 0, Patch: 0}

Functions

func ComesFromDM added in v0.11.0

func ComesFromDM(s bot.Session, id string) (bool, error)

ComesFromDM returns true if a message comes from a DM channel

func FetchGuildUser added in v0.11.0

func FetchGuildUser(s bot.Session, guildID string) []*user.Member

FetchGuildUser returns the list of member in a guild

func GetTimestampFromId added in v0.11.0

func GetTimestampFromId(id string) (time.Time, error)

func LoadConfig added in v0.6.0

func LoadConfig(cfg interface{}, name string, defaultValues func(), marshal func(interface{}) ([]byte, error), unmarshal func([]byte, interface{}) error) error

LoadConfig a config (already called on start)

func NewTimer added in v0.11.0

func NewTimer(d time.Duration, fn func(chan<- interface{})) chan<- interface{}

NewTimer produce a new async ticker.

d is for the duration between two ticks, and fn is the functions called at each tick: it takes a chan in parameter, and you can put anything here to disable the ticker

It returns a chan to disable the timer

func SetupConfigs

func SetupConfigs(customBaseConfig BaseConfig, cfgInfo []*ConfigInfo) error

SetupConfigs with the given configs (+ base config which is available at BaseCfg)

customBaseConfig is the new type of BaseCfg

Types

type BaseConfig

type BaseConfig interface {
	// IsDebug returns true if the bot is in debug mode
	IsDebug() bool
	// GetAuthor returns the author (or the owner) of the bot
	GetAuthor() string
	// GetRedisCredentials returns the RedisCredentials used by the bot.
	//
	// Must return nil if gokord.UseRedis is false
	GetRedisCredentials() *RedisCredentials
	// GetSQLCredentials returns the SQLCredentials used by the bot
	GetSQLCredentials() SQLCredentials
	// SetDefaultValues set all values of this config to their default ones. THIS IS A DESTRUCTIVE OPERATION!
	SetDefaultValues()
	// Marshal the config, must use toml.Marshal
	Marshal() ([]byte, error)
	// Unmarshal the config, must use toml.Unmarshal
	Unmarshal([]byte) error
}

type Bot

type Bot struct {
	Logger   *slog.Logger
	Token    string               // Token of the Bot
	Status   []*Status            // Status of the Bot
	Commands []cmd.CommandBuilder // Commands of the Bot, use New to create easily a new command

	AfterInit   func(s *discordgo.Session) // AfterInit is called after the initialization process of the Bot
	Version     *Version
	Innovations []*Innovation
	Name        string
	Intents     discord.Intent

	Verbose bool
	// contains filtered or unexported fields
}

Bot is the representation of a discord bot

func (*Bot) AddHandler added in v0.11.0

func (b *Bot) AddHandler(handler any)

func (*Bot) HandleMessageComponent added in v0.11.0

func (b *Bot) HandleMessageComponent(handler func(bot.Session, *event.InteractionCreate, *interaction.MessageComponentData, *cmd.ResponseBuilder),
	id string)

func (*Bot) HandleModal added in v0.11.0

func (b *Bot) HandleModal(handler func(bot.Session, *event.InteractionCreate, *interaction.ModalSubmitData, *cmd.ResponseBuilder),
	id string)

func (*Bot) Start

func (b *Bot) Start()

Start the Bot (blocking instruction)

type BotData added in v0.5.0

type BotData struct {
	gorm.Model
	Version string `gorm:"version"`
	Name    string `gorm:"name"`
}

func (*BotData) Load added in v0.5.0

func (b *BotData) Load() error

func (*BotData) Save added in v0.5.0

func (b *BotData) Save() error

type ConfigInfo

type ConfigInfo struct {
	Cfg           interface{} // Cfg is a pointer to the struct
	Name          string      // Name of the config
	DefaultValues func()      // DefaultValues is called to set up the default values of the config
}

ConfigInfo has all required information to get a config

type DataBase added in v0.3.0

type DataBase interface {
	Load() error // Load data from the database
	Save() error // Save data into the database
}

DataBase is an interface with basic methods to load and save data

type Innovation added in v0.5.0

type Innovation struct {
	Version   *Version
	Commands  *InnovationCommands
	Changelog string
}

func LoadInnovationFromJson added in v0.5.0

func LoadInnovationFromJson(b []byte) ([]*Innovation, error)

LoadInnovationFromJson provided (could be embedded with go/embed)

type InnovationCommands added in v0.5.0

type InnovationCommands struct {
	Added   []string `json:"added"`
	Removed []string `json:"removed"`
	Updated []string `json:"updated"`
}

type InnovationJson added in v0.5.1

type InnovationJson struct {
	Version   string              `json:"version"`
	Commands  *InnovationCommands `json:"commands"`
	Changelog string              `json:"changelog,omitempty"`
}

type RedisBase added in v0.3.0

type RedisBase interface {
	GenKey(key string) string // GenKey generates the key to use
}

RedisBase is an interface helping use of redis to store/cache data

type RedisCredentials

type RedisCredentials struct {
	Address  string `toml:"address"`
	Password string `toml:"password"`
	DB       int    `toml:"db"`
}
var (
	// Credentials of redis
	Credentials RedisCredentials
	// Ctx background
	Ctx = context.Background()
)

func (*RedisCredentials) Connect added in v0.6.0

func (rc *RedisCredentials) Connect() (*redis.Client, error)

Connect to Redis with the given RedisCredentials

func (*RedisCredentials) SetDefaultValues added in v0.6.0

func (rc *RedisCredentials) SetDefaultValues()

SetDefaultValues set all values of these credentials to their default ones. THIS IS A DESTRUCTIVE OPERATION!

type RedisUser added in v0.3.0

type RedisUser struct {
	RedisBase
	DiscordID string
	GuildID   string
}

RedisUser is the default implementation of RedisBase for a Discord User

func (*RedisUser) GenKey added in v0.3.0

func (p *RedisUser) GenKey(key string) string

type SQLCredentials added in v0.6.0

type SQLCredentials interface {
	// SetDefaultValues set all values of these credentials to their default ones.
	// THIS IS A DESTRUCTIVE OPERATION!
	SetDefaultValues()
	// Connect to the database, must use gorm.Open
	// (see https://gorm.io/docs/connecting_to_the_database.html)
	Connect() (*gorm.DB, error)
}

type Status

type Status struct {
	Type    StatusType // Type of the Status (use GameStatus or WatchStatus or StreamingStatus or ListeningStatus)
	Content string     // Content of the Status
	Url     string     // Url of the StreamingStatus
}

Status contains all required information for updating the status

type StatusType added in v0.8.0

type StatusType int

type Version added in v0.5.0

type Version struct {
	Major      uint
	Minor      uint
	Patch      uint
	PreRelease string
}

func ParseVersion added in v0.5.0

func ParseVersion(s string) (Version, error)

func (*Version) ForSort added in v0.5.0

func (v *Version) ForSort(o *Version) int

ForSort returns:

  • 0 if o and v are the same version
  • 1 if v is newer than o
  • -1 if o is newer than v

func (*Version) Is added in v0.5.0

func (v *Version) Is(o *Version) bool

Is check if this is the same version

func (*Version) NewerThan added in v0.5.0

func (v *Version) NewerThan(o *Version) bool

NewerThan check if the version is newer than the version o

Does not support pre-release checks

func (*Version) SetMajor added in v0.5.0

func (v *Version) SetMajor(m uint) *Version

func (*Version) SetMinor added in v0.5.0

func (v *Version) SetMinor(m uint) *Version

func (*Version) SetPatch added in v0.5.0

func (v *Version) SetPatch(p uint) *Version

func (*Version) SetPreRelease added in v0.5.0

func (v *Version) SetPreRelease(p string) *Version

func (*Version) String added in v0.5.0

func (v *Version) String() string

func (*Version) UpdateBotVersion added in v0.5.0

func (v *Version) UpdateBotVersion(bot *Bot)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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