plugins

package
v3.25.0 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2024 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Overview

Package plugins defines interfaces and helpers for plugin (internal and external ones) development and integration

Index

Constants

View Source
const DefaultConfigName = "default"

DefaultConfigName is the name the default configuration must have when defined

Variables

View Source
var (
	// ErrValueNotSet is used to notify the value is not available in the FieldCollection
	ErrValueNotSet = errors.New("specified value not found")
	// ErrValueMismatch is used to notify the value does not match the requested type
	ErrValueMismatch = errors.New("specified value has different format")
)
View Source
var ErrSkipSendingMessage = errors.New("skip sending message")

ErrSkipSendingMessage should be returned by a MsgModificationFunc to prevent the message to be sent to the Twitch servers

View Source
var ErrStopRuleExecution = errors.New("stop rule execution now")

ErrStopRuleExecution is a way for actions to terminate execution of the current rule gracefully. No actions after this has been returned will be executed and no error state will be set

Functions

func DeriveChannel

func DeriveChannel(m *irc.Message, evtData *FieldCollection) string

DeriveChannel takes an irc.Message and a FieldCollection and tries to extract from them the channel the event / message has taken place

func DeriveUser

func DeriveUser(m *irc.Message, evtData *FieldCollection) string

DeriveUser takes an irc.Message and a FieldCollection and tries to extract from them the user causing the event / message

Types

type ActionDocumentation

type ActionDocumentation struct {
	Description string `json:"description"`
	Name        string `json:"name"`
	Type        string `json:"type"`

	Fields []ActionDocumentationField `json:"fields"`
}

ActionDocumentation contains the documentation for a single actor to be rendered into the documentation site

type ActionDocumentationField

type ActionDocumentationField struct {
	Default         string                       `json:"default"`
	DefaultComment  string                       `json:"default_comment"`
	Description     string                       `json:"description"`
	Key             string                       `json:"key"`
	Long            bool                         `json:"long"`
	Name            string                       `json:"name"`
	Optional        bool                         `json:"optional"`
	SupportTemplate bool                         `json:"support_template"`
	Type            ActionDocumentationFieldType `json:"type"`
}

ActionDocumentationField documents fields available in the actor

type ActionDocumentationFieldType

type ActionDocumentationFieldType string

ActionDocumentationFieldType defines known field types

const (
	ActionDocumentationFieldTypeBool        ActionDocumentationFieldType = "bool"
	ActionDocumentationFieldTypeDuration    ActionDocumentationFieldType = "duration"
	ActionDocumentationFieldTypeInt64       ActionDocumentationFieldType = "int64"
	ActionDocumentationFieldTypeString      ActionDocumentationFieldType = "string"
	ActionDocumentationFieldTypeStringSlice ActionDocumentationFieldType = "stringslice"
)

Enum of available field types

type Actor

type Actor interface {
	// Execute will be called after the config was read into the Actor
	Execute(c *irc.Client, m *irc.Message, r *Rule, evtData *FieldCollection, attrs *FieldCollection) (preventCooldown bool, err error)
	// IsAsync may return true if the Execute function is to be executed
	// in a Go routine as of long runtime. Normally it should return false
	// except in very specific cases
	IsAsync() bool
	// Name must return an unique name for the actor in order to identify
	// it in the logs for debugging purposes
	Name() string
	// Validate will be called to validate the loaded configuration. It should
	// return an error if required keys are missing from the AttributeStore
	// or if keys contain broken configs
	Validate(TemplateValidatorFunc, *FieldCollection) error
}

Actor defines an interface to implement in the plugin for actors

type ActorCreationFunc

type ActorCreationFunc func() Actor

ActorCreationFunc is a function to return a new instance of the plugins actor

type ActorDocumentationRegistrationFunc

type ActorDocumentationRegistrationFunc func(ActionDocumentation)

ActorDocumentationRegistrationFunc is passed from the bot to the plugins RegisterFunc to register a new actor documentation

type ActorKit added in v3.16.0

type ActorKit struct{}

ActorKit contains some common validation functions to be used when implementing actors

func (ActorKit) ValidateRequireNonEmpty added in v3.16.0

func (ActorKit) ValidateRequireNonEmpty(attrs *FieldCollection, fields ...string) error

ValidateRequireNonEmpty checks whether the fields are gettable (not returning ErrValueNotSet) and does not contain zero value recognized by reflect (to just check whether the field is set but allow zero values use HasAll on the FieldCollection)

func (ActorKit) ValidateRequireValidTemplate added in v3.16.0

func (ActorKit) ValidateRequireValidTemplate(tplValidator TemplateValidatorFunc, attrs *FieldCollection, fields ...string) error

ValidateRequireValidTemplate checks whether fields are gettable as strings and do have a template which validates (this does not check for empty strings as an empty template is indeed valid)

func (ActorKit) ValidateRequireValidTemplateIfSet added in v3.16.0

func (ActorKit) ValidateRequireValidTemplateIfSet(tplValidator TemplateValidatorFunc, attrs *FieldCollection, fields ...string) error

ValidateRequireValidTemplateIfSet checks whether the field is either not set or a valid template (this does not check for empty strings as an empty template is indeed valid)

type ActorRegistrationFunc

type ActorRegistrationFunc func(name string, acf ActorCreationFunc)

ActorRegistrationFunc is passed from the bot to the plugins RegisterFunc to register a new actor in the bot

type ChannelAnyPermissionCheckFunc added in v3.2.0

type ChannelAnyPermissionCheckFunc func(channel string, scopes ...string) (bool, error)

ChannelAnyPermissionCheckFunc is available to check whether the bot has stored scopes / permissions for the given channel. Any of the given scopes need to be available to return true.

type ChannelPermissionCheckFunc added in v3.2.0

type ChannelPermissionCheckFunc func(channel string, scopes ...string) (bool, error)

ChannelPermissionCheckFunc is available to check whether the bot has stored scopes / permissions for the given channel. All given scopes need to be available to return true.

type CronRegistrationFunc

type CronRegistrationFunc func(spec string, cmd func()) (cron.EntryID, error)

CronRegistrationFunc is passed from the bot to the plugins RegisterFunc to register a new cron function in the internal cron scheduler

type DatabaseCopyFunc added in v3.20.0

type DatabaseCopyFunc func(src, target *gorm.DB) error

DatabaseCopyFunc defines the function type the plugin must implement and register to enable the bot to replicate its database stored content into a new database

type EventHandlerFunc

type EventHandlerFunc func(evt string, eventData *FieldCollection) error

EventHandlerFunc defines the type of function required to listen for events

type EventHandlerRegisterFunc

type EventHandlerRegisterFunc func(EventHandlerFunc) error

EventHandlerRegisterFunc is passed from the bot to the plugins RegisterFunc to register a new event handler function which is then fed with all events occurring in the bot

type FieldCollection

type FieldCollection struct {
	// contains filtered or unexported fields
}

FieldCollection holds an map[string]any with conversion functions attached

func FieldCollectionFromData

func FieldCollectionFromData(data map[string]any) *FieldCollection

FieldCollectionFromData is a wrapper around NewFieldCollection and SetFromData

func NewFieldCollection

func NewFieldCollection() *FieldCollection

NewFieldCollection creates a new FieldCollection with empty data store

func (*FieldCollection) Any added in v3.8.0

func (f *FieldCollection) Any(name string) (any, error)

Any tries to read key name as any-type (interface)

func (*FieldCollection) Bool

func (f *FieldCollection) Bool(name string) (bool, error)

Bool tries to read key name as bool

func (*FieldCollection) CanBool

func (f *FieldCollection) CanBool(name string) bool

CanBool tries to read key name as bool and checks whether error is nil

func (*FieldCollection) CanDuration

func (f *FieldCollection) CanDuration(name string) bool

CanDuration tries to read key name as time.Duration and checks whether error is nil

func (*FieldCollection) CanInt64

func (f *FieldCollection) CanInt64(name string) bool

CanInt64 tries to read key name as int64 and checks whether error is nil

func (*FieldCollection) CanString

func (f *FieldCollection) CanString(name string) bool

CanString tries to read key name as string and checks whether error is nil

func (*FieldCollection) Clone

func (f *FieldCollection) Clone() *FieldCollection

Clone is a wrapper around n.SetFromData(o.Data())

func (*FieldCollection) Data

func (f *FieldCollection) Data() map[string]any

Data creates a map-copy of the data stored inside the FieldCollection

func (*FieldCollection) Duration

func (f *FieldCollection) Duration(name string) (time.Duration, error)

Duration tries to read key name as time.Duration

func (*FieldCollection) Expect

func (f *FieldCollection) Expect(keys ...string) error

Expect takes a list of keys and returns an error with all non-found names

func (*FieldCollection) HasAll

func (f *FieldCollection) HasAll(keys ...string) bool

HasAll takes a list of keys and returns whether all of them exist inside the FieldCollection

func (*FieldCollection) Int64

func (f *FieldCollection) Int64(name string) (int64, error)

Int64 tries to read key name as int64

func (*FieldCollection) MarshalJSON

func (f *FieldCollection) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaller interface

func (*FieldCollection) MarshalYAML

func (f *FieldCollection) MarshalYAML() (any, error)

MarshalYAML implements the yaml.Marshaller interface

func (*FieldCollection) MustBool

func (f *FieldCollection) MustBool(name string, defVal *bool) bool

MustBool is a wrapper around Bool and panics if an error was returned

func (*FieldCollection) MustDuration

func (f *FieldCollection) MustDuration(name string, defVal *time.Duration) time.Duration

MustDuration is a wrapper around Duration and panics if an error was returned

func (*FieldCollection) MustInt64

func (f *FieldCollection) MustInt64(name string, defVal *int64) int64

MustInt64 is a wrapper around Int64 and panics if an error was returned

func (*FieldCollection) MustString

func (f *FieldCollection) MustString(name string, defVal *string) string

MustString is a wrapper around String and panics if an error was returned

func (*FieldCollection) MustStringSlice added in v3.8.0

func (f *FieldCollection) MustStringSlice(name string) []string

MustStringSlice is a wrapper around StringSlice and returns nil in case name is not set

func (*FieldCollection) Set

func (f *FieldCollection) Set(key string, value any)

Set sets a single key to specified value

func (*FieldCollection) SetFromData

func (f *FieldCollection) SetFromData(data map[string]any)

SetFromData takes a map of data and copies all data into the FieldCollection

func (*FieldCollection) String

func (f *FieldCollection) String(name string) (string, error)

String tries to read key name as string

func (*FieldCollection) StringSlice

func (f *FieldCollection) StringSlice(name string) ([]string, error)

StringSlice tries to read key name as []string

func (*FieldCollection) UnmarshalJSON

func (f *FieldCollection) UnmarshalJSON(raw []byte) error

UnmarshalJSON implements the json.Unmarshaller interface

func (*FieldCollection) UnmarshalYAML

func (f *FieldCollection) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML implements the yaml.Unmarshaller interface

type HTTPRouteParamDocumentation

type HTTPRouteParamDocumentation struct {
	Description string
	Name        string
	Required    bool
	Type        string
}

HTTPRouteParamDocumentation documents parameters expected by a HTTP route and to be documented in the API documentation

type HTTPRouteRegistrationArgs

type HTTPRouteRegistrationArgs struct {
	Accept              []string
	Description         string
	HandlerFunc         http.HandlerFunc
	IsPrefix            bool
	Method              string
	Module              string
	Name                string
	Path                string
	QueryParams         []HTTPRouteParamDocumentation
	RequiresEditorsAuth bool
	RequiresWriteAuth   bool
	ResponseType        HTTPRouteResponseType
	RouteParams         []HTTPRouteParamDocumentation
	SkipDocumentation   bool
}

HTTPRouteRegistrationArgs defines the HTTP route to be added in using the HTTPRouteRegistrationFunc

type HTTPRouteRegistrationFunc

type HTTPRouteRegistrationFunc func(HTTPRouteRegistrationArgs) error

HTTPRouteRegistrationFunc is passed from the bot to the plugins RegisterFunc to register a new route in the API router

type HTTPRouteResponseType

type HTTPRouteResponseType uint64

HTTPRouteResponseType pre-defines response types known to the API documentation

const (
	HTTPRouteResponseTypeNo200 HTTPRouteResponseType = iota
	HTTPRouteResponseTypeTextPlain
	HTTPRouteResponseTypeJSON
	HTTPRouteResponseTypeMultiple
)

Enum of known HTTPRouteResponseType

type LoggerCreationFunc

type LoggerCreationFunc func(moduleName string) *logrus.Entry

LoggerCreationFunc is passed from the bot to the plugins RegisterFunc to retrieve a pre-configured logrus.Entry scoped for the given module name

type ModuleConfig added in v3.18.0

type ModuleConfig map[string]map[string]*FieldCollection

ModuleConfig represents a mapping of configurations per channel and module

func (ModuleConfig) GetChannelConfig added in v3.18.0

func (m ModuleConfig) GetChannelConfig(module, channel string) *FieldCollection

GetChannelConfig reads the channel specific configuration for the given module. This is created by taking an empty FieldCollection, merging in the default configuration and finally overwriting all existing channel configurations.

type ModuleConfigGetterFunc added in v3.18.0

type ModuleConfigGetterFunc func(module, channel string) *FieldCollection

ModuleConfigGetterFunc is passed from the bot to the plugins RegisterFunc to fetch module generic or channel specific configuration from the module configuration

type MsgFormatter

type MsgFormatter func(tplString string, m *irc.Message, r *Rule, fields *FieldCollection) (string, error)

MsgFormatter is passed from the bot to the plugins RegisterFunc to format messages using all registered and available template functions

type MsgModificationFunc

type MsgModificationFunc func(*irc.Message) error

MsgModificationFunc can be used to modify messages between the plugins generating them and the bot sending them to the Twitch servers

type MsgModificationRegistrationFunc

type MsgModificationRegistrationFunc func(linePrefix string, modFn MsgModificationFunc)

MsgModificationRegistrationFunc is passed from the bot to the plugins RegisterFunc to register a new MsgModificationFunc for the given prefix

type RawMessageHandlerFunc

type RawMessageHandlerFunc func(m *irc.Message) error

RawMessageHandlerFunc is the type of function to implement in your plugin in order to process raw-messages from the IRC connection

type RawMessageHandlerRegisterFunc

type RawMessageHandlerRegisterFunc func(RawMessageHandlerFunc) error

RawMessageHandlerRegisterFunc is passed from the bot to the plugins RegisterFunc to register a new RawMessageHandlerFunc

type RegisterFunc

type RegisterFunc func(RegistrationArguments) error

RegisterFunc is the type of function your plugin must expose with the name Register

type RegistrationArguments

type RegistrationArguments struct {
	// CreateEvent allows to create an event handed out to all modules to handle
	CreateEvent EventHandlerFunc
	// FormatMessage is a method to convert templates into strings using internally known variables / configs
	FormatMessage MsgFormatter
	// FrontendNotify is a way to send a notification to the frontend
	FrontendNotify func(string)
	// GetDatabaseConnector returns an active database.Connector to access the backend storage database
	GetDatabaseConnector func() database.Connector
	// GetLogger returns a sirupsen log.Entry pre-configured with the module name
	GetLogger LoggerCreationFunc
	// GetModuleConfigForChannel returns the module configuration for the given channel if available
	GetModuleConfigForChannel ModuleConfigGetterFunc
	// GetTwitchClient retrieves a fully configured Twitch client with initialized cache
	GetTwitchClient func() *twitch.Client
	// GetTwitchClientForChannel retrieves a fully configured Twitch client with initialized cache for extended permission channels
	GetTwitchClientForChannel func(string) (*twitch.Client, error)
	// HasAnyPermissionForChannel checks whether ANY of the given permissions were granted for the given channel
	HasAnyPermissionForChannel ChannelAnyPermissionCheckFunc
	// HasPermissionForChannel checks whether ALL of the given permissions were granted for the given channel
	HasPermissionForChannel ChannelPermissionCheckFunc
	// RegisterActor is used to register a new IRC rule-actor implementing the Actor interface
	RegisterActor ActorRegistrationFunc
	// RegisterActorDocumentation is used to register an ActorDocumentation for the config editor
	RegisterActorDocumentation ActorDocumentationRegistrationFunc
	// RegisterAPIRoute registers a new HTTP handler function including documentation
	RegisterAPIRoute HTTPRouteRegistrationFunc
	// RegisterCopyDatabaseFunc registers a DatabaseCopyFunc for the
	// database migration tool. Modules not registering such a func
	// will not be copied over when migrating to another database.
	RegisterCopyDatabaseFunc func(name string, fn DatabaseCopyFunc)
	// RegisterCron is a method to register cron functions in the global cron instance
	RegisterCron CronRegistrationFunc
	// RegisterEventHandler is a method to register a handler function receiving ALL events
	RegisterEventHandler EventHandlerRegisterFunc
	// RegisterMessageModFunc is a method to register a handler to modify / react on messages
	RegisterMessageModFunc MsgModificationRegistrationFunc
	// RegisterRawMessageHandler is a method to register an handler to receive ALL messages received
	RegisterRawMessageHandler RawMessageHandlerRegisterFunc
	// RegisterTemplateFunction can be used to register a new template functions
	RegisterTemplateFunction TemplateFuncRegister
	// SendMessage can be used to send a message not triggered by an event
	SendMessage SendMessageFunc
	// ValidateToken offers a way to validate a token and determine whether it has permissions on a given module
	ValidateToken ValidateTokenFunc
}

RegistrationArguments is the object your RegisterFunc will receive and can use to interact with the bot instance

type Rule

type Rule struct {
	UUID          string  `hash:"-" json:"uuid,omitempty" yaml:"uuid,omitempty"`
	Description   string  `json:"description,omitempty" yaml:"description,omitempty"`
	SubscribeFrom *string `json:"subscribe_from,omitempty" yaml:"subscribe_from,omitempty"`

	Actions []*RuleAction `json:"actions,omitempty" yaml:"actions,omitempty"`

	Cooldown        *time.Duration `json:"cooldown,omitempty" yaml:"cooldown,omitempty"`
	ChannelCooldown *time.Duration `json:"channel_cooldown,omitempty" yaml:"channel_cooldown,omitempty"`
	UserCooldown    *time.Duration `json:"user_cooldown,omitempty" yaml:"user_cooldown,omitempty"`
	SkipCooldownFor []string       `json:"skip_cooldown_for,omitempty" yaml:"skip_cooldown_for,omitempty"`

	MatchChannels []string `json:"match_channels,omitempty" yaml:"match_channels,omitempty"`
	MatchEvent    *string  `json:"match_event,omitempty" yaml:"match_event,omitempty"`
	MatchMessage  *string  `json:"match_message,omitempty" yaml:"match_message,omitempty"`
	MatchUsers    []string `json:"match_users,omitempty" yaml:"match_users,omitempty" `

	DisableOnMatchMessages []string `json:"disable_on_match_messages,omitempty" yaml:"disable_on_match_messages,omitempty"`

	Disable           *bool    `json:"disable,omitempty" yaml:"disable,omitempty"`
	DisableOnOffline  *bool    `json:"disable_on_offline,omitempty" yaml:"disable_on_offline,omitempty"`
	DisableOnPermit   *bool    `json:"disable_on_permit,omitempty" yaml:"disable_on_permit,omitempty"`
	DisableOnTemplate *string  `json:"disable_on_template,omitempty" yaml:"disable_on_template,omitempty"`
	DisableOn         []string `json:"disable_on,omitempty" yaml:"disable_on,omitempty"`
	EnableOn          []string `json:"enable_on,omitempty" yaml:"enable_on,omitempty"`
	// contains filtered or unexported fields
}

Rule represents a rule in the bot configuration

func (*Rule) GetMatchMessage

func (r *Rule) GetMatchMessage() *regexp.Regexp

GetMatchMessage returns the cached Regexp if available or compiles the given match string into a Regexp

func (Rule) MatcherID

func (r Rule) MatcherID() string

MatcherID returns the rule UUID or a hash for the rule if no UUID is available

func (*Rule) Matches

func (r *Rule) Matches(m *irc.Message, event *string, timerStore TimerStore, msgFormatter MsgFormatter, twitchClient *twitch.Client, eventData *FieldCollection) bool

Matches checks whether the Rule should be executed for the given parameters

func (*Rule) SetCooldown

func (r *Rule) SetCooldown(timerStore TimerStore, m *irc.Message, evtData *FieldCollection)

SetCooldown uses the given TimerStore to set the cooldowns for the Rule after execution

func (*Rule) UpdateFromSubscription

func (r *Rule) UpdateFromSubscription(ctx context.Context) (bool, error)

UpdateFromSubscription fetches the remote Rule source if one is defined and updates the rule with its content

func (Rule) Validate

func (r Rule) Validate(tplValidate TemplateValidatorFunc) error

Validate executes some basic checks on the validity of the Rule

type RuleAction

type RuleAction struct {
	Type       string           `json:"type" yaml:"type,omitempty"`
	Attributes *FieldCollection `json:"attributes" yaml:"attributes,omitempty"`
}

RuleAction represents an action to be executed when running a Rule

type SendMessageFunc

type SendMessageFunc func(*irc.Message) error

SendMessageFunc is available through the RegistrationArguments and MUST be used to send messages to the Twitch servers

type TemplateFuncDocumentation added in v3.17.0

type TemplateFuncDocumentation struct {
	Name        string
	Description string
	Syntax      string
	Example     *TemplateFuncDocumentationExample
	Remarks     string
}

TemplateFuncDocumentation contains a documentation for a template function to be rendered into the documentation site

type TemplateFuncDocumentationExample added in v3.17.0

type TemplateFuncDocumentationExample struct {
	MatchMessage   string
	MessageContent string
	Template       string
	ExpectedOutput string
	FakedOutput    string
}

TemplateFuncDocumentationExample contains an example of the function execution to be rendered as an example how to use the template function

type TemplateFuncGetter

type TemplateFuncGetter func(*irc.Message, *Rule, *FieldCollection) any

TemplateFuncGetter is the type of function to implement in the plugin to create a new template function on request of the bot

func GenericTemplateFunctionGetter

func GenericTemplateFunctionGetter(f any) TemplateFuncGetter

GenericTemplateFunctionGetter wraps a generic template function not requiring access to the irc.Message, Rule or FieldCollection to satisfy the TemplateFuncGetter interface

type TemplateFuncRegister

type TemplateFuncRegister func(name string, fg TemplateFuncGetter, doc ...TemplateFuncDocumentation)

TemplateFuncRegister is passed from the bot to the plugins RegisterFunc to register a new TemplateFuncGetter

type TemplateValidatorFunc

type TemplateValidatorFunc func(raw string) error

TemplateValidatorFunc is passed from the bot to the plugins RegisterFunc to validate templates considering all registered template functions

type TimerEntry

type TimerEntry struct {
	Kind TimerType `json:"kind"`
	Time time.Time `json:"time"`
}

TimerEntry represents a time for the given type in the TimerStore

type TimerStore

type TimerStore interface {
	AddCooldown(tt TimerType, limiter, ruleID string, expiry time.Time) error
	InCooldown(tt TimerType, limiter, ruleID string) (bool, error)
	AddPermit(channel, username string) error
	HasPermit(channel, username string) (bool, error)
}

TimerStore defines what to expect when interacting with a store

type TimerType

type TimerType uint8

TimerType defines an enum of available timer types

const (
	TimerTypePermit TimerType = iota
	TimerTypeCooldown
)

Definitions of supported TimerType values

type ValidateTokenFunc

type ValidateTokenFunc func(token string, modules ...string) error

ValidateTokenFunc is passed from the bot to the plugins RegisterFunc to validate tokens and their access permissions

Jump to

Keyboard shortcuts

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