discordbot

package
Version: v0.0.0-...-07d25bb Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2021 License: Apache-2.0 Imports: 36 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EmbedLimitTitle       = 256
	EmbedLimitDescription = 2048
	EmbedLimitFieldValue  = 1024
	EmbedLimitFieldName   = 256
	EmbedLimitField       = 25
	EmbedLimitFooter      = 2048
	EmbedLimit            = 4000
)

Constants for message embed character limits

Variables

View Source
var Consts = map[string]reflect.Value{
	"EmbedLimit":            reflect.ValueOf(EmbedLimit),
	"EmbedLimitDescription": reflect.ValueOf(EmbedLimitDescription),
	"EmbedLimitField":       reflect.ValueOf(EmbedLimitField),
	"EmbedLimitFieldName":   reflect.ValueOf(EmbedLimitFieldName),
	"EmbedLimitFieldValue":  reflect.ValueOf(EmbedLimitFieldValue),
	"EmbedLimitFooter":      reflect.ValueOf(EmbedLimitFooter),
	"EmbedLimitTitle":       reflect.ValueOf(EmbedLimitTitle),
	"PrivilegeAdmin":        reflect.ValueOf(PrivilegeAdmin),
	"PrivilegeEveryone":     reflect.ValueOf(PrivilegeEveryone),
	"PrivilegeNobody":       reflect.ValueOf(PrivilegeNobody),
	"PrivilegeRoot":         reflect.ValueOf(PrivilegeRoot),
}
View Source
var Functions = map[string]reflect.Value{
	"AnkoPackageConfigurator": reflect.ValueOf(AnkoPackageConfigurator),
	"BotStats":                reflect.ValueOf(BotStats),
	"BuildAnkoOutFunction":    reflect.ValueOf(BuildAnkoOutFunction),
	"ComesFromDM":             reflect.ValueOf(ComesFromDM),
	"CreateInvite":            reflect.ValueOf(CreateInvite),
	"GetMessageHandlers":      reflect.ValueOf(GetMessageHandlers),
	"GetMuteManager":          reflect.ValueOf(GetMuteManager),
	"GetReactionHandlers":     reflect.ValueOf(GetReactionHandlers),
	"NewCommand":              reflect.ValueOf(NewCommand),
	"NewCommandLibrary":       reflect.ValueOf(NewCommandLibrary),
	"NewEmbed":                reflect.ValueOf(NewEmbed),
	"NewInfoHandler":          reflect.ValueOf(NewInfoHandler),
	"NewMuteManager":          reflect.ValueOf(NewMuteManager),
	"ProjectGuildMember":      reflect.ValueOf(ProjectGuildMember),
	"SendDMtoUser":            reflect.ValueOf(SendDMtoUser),
	"SetMessageHandlers":      reflect.ValueOf(SetMessageHandlers),
	"SetMuteManager":          reflect.ValueOf(SetMuteManager),
	"SetReactionHandlers":     reflect.ValueOf(SetReactionHandlers),
	"Start":                   reflect.ValueOf(Start),
	"Stop":                    reflect.ValueOf(Stop),
	"User":                    reflect.ValueOf(User),
}
View Source
var ThePosPlayBridge = new(PosPlayBridge)

ThePosPlayBridge is the PosPlayBridge of the bot (exported so the posplay package can reach it)

View Source
var Types = map[string]reflect.Type{
	"Command":         reflect.TypeOf((*Command)(nil)).Elem(),
	"CommandHandler":  reflect.TypeOf((*CommandHandler)(nil)).Elem(),
	"CommandLibrary":  reflect.TypeOf((*CommandLibrary)(nil)).Elem(),
	"CommandReceiver": reflect.TypeOf((*CommandReceiver)(nil)).Elem(),
	"Embed":           reflect.TypeOf((*Embed)(nil)).Elem(),
	"InfoHandler":     reflect.TypeOf((*InfoHandler)(nil)).Elem(),
	"MessageHandler":  reflect.TypeOf((*MessageHandler)(nil)).Elem(),
	"MuteManager":     reflect.TypeOf((*MuteManager)(nil)).Elem(),
	"PosPlayBridge":   reflect.TypeOf((*PosPlayBridge)(nil)).Elem(),
	"PosPlayXPInfo":   reflect.TypeOf((*PosPlayXPInfo)(nil)).Elem(),
	"Privilege":       reflect.TypeOf((*Privilege)(nil)).Elem(),
	"ReactionHandler": reflect.TypeOf((*ReactionHandler)(nil)).Elem(),
	"SQLSystem":       reflect.TypeOf((*SQLSystem)(nil)).Elem(),
	"ScriptSystem":    reflect.TypeOf((*ScriptSystem)(nil)).Elem(),
	"Stats":           reflect.TypeOf((*Stats)(nil)).Elem(),
}
View Source
var Variables = map[string]reflect.Value{
	"ThePosPlayBridge": reflect.ValueOf(&ThePosPlayBridge),
}

Functions

func AnkoPackageConfigurator

func AnkoPackageConfigurator(packages map[string]map[string]reflect.Value, packageTypes map[string]map[string]reflect.Type)

AnkoPackageConfigurator exports functions for use with the anko scripting system

func BuildAnkoOutFunction

func BuildAnkoOutFunction(channelID string) func(env *ankiddie.Environment, msg string) error

BuildAnkoOutFunction returns a function suitable for passing to Ankiddie as the output function of anko environments, that sends messages to a discord channel

func ComesFromDM

func ComesFromDM(s *discordgo.Session, m *discordgo.MessageCreate) (bool, error)

ComesFromDM returns true if a message comes from a DM channel

func CreateInvite

func CreateInvite(channelID, requesterIPaddr, utmSource string) (*discordgo.Invite, error)

CreateInvite creates a single-use invite for the specified channel

func ProjectGuildMember

func ProjectGuildMember(userID string) (*discordgo.Member, error)

ProjectGuildMember returns a user from the project guild by ID

func SendDMtoUser

func SendDMtoUser(userID string, data *discordgo.MessageSend) (*discordgo.Message, error)

SendDMtoUser sends a direct message to the specified user with the specified content

func SetMessageHandlers

func SetMessageHandlers(m []MessageHandler)

SetMessageHandlers sets the MessageHandlers the bot is using

func SetMuteManager

func SetMuteManager(m *MuteManager)

SetMuteManager sets the MuteManager the bot is using

func SetReactionHandlers

func SetReactionHandlers(m []ReactionHandler)

SetReactionHandlers sets the ReactionHandlers the bot is using

func Start

func Start(snode sqalx.Node, swebsiteURL string, keybox *keybox.Keybox,
	log *log.Logger,
	cmdRecv CommandReceiver) error

Start starts the Discord bot

func Stop

func Stop()

Stop stops the Discord bot

func User

func User(userID string) (*discordgo.User, error)

User returns the user details of the given userID

Types

type Command

type Command struct {
	Name             string
	RequirePrivilege Privilege
	IgnoreMute       bool
	Handler          CommandHandler
	SkipArgParsing   bool
}

Command represents a bot command

func NewCommand

func NewCommand(name string, handler CommandHandler) Command

NewCommand returns a new Command with the specified name and handler

func (Command) Handle

func (c Command) Handle(s *discordgo.Session, m *discordgo.MessageCreate, args []string)

Handle executes this command

func (Command) WithIgnoreMute

func (c Command) WithIgnoreMute(ignoreMute bool) Command

WithIgnoreMute sets whether the command works regardless of the bot being muted

func (Command) WithRequirePrivilege

func (c Command) WithRequirePrivilege(privilege Privilege) Command

WithRequirePrivilege sets the minimum privilege to use a command and returns the modified copy

func (Command) WithSkipArgParsing

func (c Command) WithSkipArgParsing(skipArgParsing bool) Command

WithSkipArgParsing sets whether arguments for this command are to be parsed by go-shellquote (true), or if the remainder of the message should be passed as the first item in the args array (false)

type CommandHandler

type CommandHandler func(s *discordgo.Session, m *discordgo.MessageCreate, args []string)

CommandHandler is a function capable of handling a bot commmand

type CommandLibrary

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

CommandLibrary handles a set of commands

func NewCommandLibrary

func NewCommandLibrary(prefix, botOwnerUserID string) *CommandLibrary

NewCommandLibrary returns a new CommandLibrary with the specified prefix

func (*CommandLibrary) Get

func (l *CommandLibrary) Get(name string) (command *Command, present bool)

Get retrieves a command from the library by name

func (*CommandLibrary) HandleMessage

func (l *CommandLibrary) HandleMessage(s *discordgo.Session, m *discordgo.MessageCreate, muted bool) bool

HandleMessage attempts to handle the provided message; if it fails, it returns false

func (*CommandLibrary) MessagesActedUpon

func (l *CommandLibrary) MessagesActedUpon() int

MessagesActedUpon returns the number of messages acted upon by this CommandLibrary

func (*CommandLibrary) MessagesHandled

func (l *CommandLibrary) MessagesHandled() int

MessagesHandled returns the number of messages handled by this CommandLibrary

func (*CommandLibrary) Name

func (l *CommandLibrary) Name() string

Name returns the name of this message handler

func (*CommandLibrary) Register

func (l *CommandLibrary) Register(command Command)

Register registers a command in the library, replacing an existing command with the same name, if one exists

func (*CommandLibrary) SetPrefix

func (l *CommandLibrary) SetPrefix(prefix string)

SetPrefix sets the prefix for the CommandLibrary

func (*CommandLibrary) WithAdminChannel

func (l *CommandLibrary) WithAdminChannel(channelID string) *CommandLibrary

WithAdminChannel sets the admin channel for this command library (used with PrivilegeAdmin)

type CommandReceiver

type CommandReceiver interface {
	// NewLineStatus is called when the bot wants to add a new line status
	NewLineStatus(status *types.Status)

	// ControlScraper is called when the bot wants to start/stop/change a scraper
	ControlScraper(scraper string, enable bool, messageCallback func(message string))

	// ControlNotifs is caled when the bot wants to block/unblock sending of push notifications
	ControlNotifs(notifType string, enable bool)

	// CastDisturbanceVote is called when the bot wants to cast a disturbance vote
	CastDisturbanceVote(line *types.Line, weight int)

	// ClearDisturbanceVotes is called when the bot wants to clear disturbance votes
	ClearDisturbanceVotes(line *types.Line)

	// GetDisturbanceVotes is called when the bot wants to show current disturbance report status
	GetDisturbanceVotes(messageCallback func(message string))

	// GetThresholdMultiplier is called when the bot wants to know the current vote threshold multiplier
	GetThresholdMultiplier() float32

	// SetThresholdMultiplier is called when the bot wants to set the current vote threshold multiplier
	SetThresholdMultiplier(multiplier float32)

	// GetThresholdOffset is called when the bot wants to know the current vote threshold offset
	GetThresholdOffset() int

	// SetThresholdOffset is called when the bot wants to set the current vote threshold offset
	SetThresholdOffset(offset int)

	// GetVersion is called when the bot wants to get the current server version
	GetVersion() (gitCommit string, buildDate string)

	// GetStats is called when the bot wants to get the current server stats
	GetStats() (dbOpenConnections, apiTotalRequests int)

	// SendNotificationMetaBroadcast sends a FCM message containing a notification to show on some/all clients
	SendNotificationMetaBroadcast(shardID, shardMax int, versionFilter, localeFilter, title, body, url string)

	// SendCommandMetaBroadcast sends a FCM message containing a command to run on some/all clients
	SendCommandMetaBroadcast(shardID, shardMax int, versionFilter, localeFilter, command string, args ...string)

	// GetAnkiddie returns a reference to the global Ankiddie system
	GetAnkiddie() *ankiddie.Ankiddie

	// SetMQTTGatewayEnabled enables or disables the MQTT gateway
	SetMQTTGatewayEnabled(enabled bool) string

	// SendMQTTGatewayCommand sends a command to the MQTT subsystem
	SendMQTTGatewayCommand(command string, args ...string) string

	// SetAPIMOTDforLocale sets the "message of the day" of the API for the specified locale
	SetAPIMOTDforLocale(locale, html string)

	// SetAPIMOTDpriority sets the "message of the day" priority
	SetAPIMOTDpriority(priority int)

	// SetAPIMOTDmainLocale sets the "message of the day" main locale
	SetAPIMOTDmainLocale(mainLocale string)

	// ClearAPIMOTD clears the API MOTD
	ClearAPIMOTD()
}

CommandReceiver is used to send commands and exchange information with the code that set up a bot

type Embed

type Embed struct {
	*discordgo.MessageEmbed
}

Embed ...

func NewEmbed

func NewEmbed() *Embed

NewEmbed returns a new embed object

func (*Embed) AddField

func (e *Embed) AddField(name, value string) *Embed

AddField [name] [value]

func (*Embed) AddInlineField

func (e *Embed) AddInlineField(name, value string) *Embed

AddInlineField [name] [value]

func (*Embed) InlineAllFields

func (e *Embed) InlineAllFields() *Embed

InlineAllFields sets all fields in the embed to be inline

func (*Embed) SetAuthor

func (e *Embed) SetAuthor(args ...string) *Embed

SetAuthor ...

func (*Embed) SetColor

func (e *Embed) SetColor(clr int) *Embed

SetColor ...

func (*Embed) SetDescription

func (e *Embed) SetDescription(description string) *Embed

SetDescription [desc]

func (*Embed) SetFooter

func (e *Embed) SetFooter(args ...string) *Embed

SetFooter [Text] [iconURL]

func (*Embed) SetImage

func (e *Embed) SetImage(args ...string) *Embed

SetImage ...

func (*Embed) SetThumbnail

func (e *Embed) SetThumbnail(args ...string) *Embed

SetThumbnail ...

func (*Embed) SetTitle

func (e *Embed) SetTitle(name string) *Embed

SetTitle ...

func (*Embed) SetURL

func (e *Embed) SetURL(URL string) *Embed

SetURL ...

func (*Embed) Truncate

func (e *Embed) Truncate() *Embed

Truncate truncates any embed value over the character limit.

func (*Embed) TruncateDescription

func (e *Embed) TruncateDescription() *Embed

TruncateDescription ...

func (*Embed) TruncateFields

func (e *Embed) TruncateFields() *Embed

TruncateFields truncates fields that are too long

func (*Embed) TruncateFooter

func (e *Embed) TruncateFooter() *Embed

TruncateFooter ...

func (*Embed) TruncateTitle

func (e *Embed) TruncateTitle() *Embed

TruncateTitle ...

type InfoHandler

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

A InfoHandler parses Discord messages for references to database entities (both natural language based and ID-based) and replies with information messages

func NewInfoHandler

func NewInfoHandler(snode sqalx.Node) (*InfoHandler, error)

NewInfoHandler returns a new InfoHandler

func (*InfoHandler) HandleMessage

func (i *InfoHandler) HandleMessage(s *discordgo.Session, m *discordgo.MessageCreate, muted bool) bool

HandleMessage attempts to handle the provided message; always returns false as this is a non-authoritative handler

func (*InfoHandler) HandleReaction

func (i *InfoHandler) HandleReaction(s *discordgo.Session, m *discordgo.MessageReactionAdd) bool

HandleReaction attempts to handle the provided reaction always returns false as this is a non-authoritative handler

func (*InfoHandler) MessagesActedUpon

func (i *InfoHandler) MessagesActedUpon() int

MessagesActedUpon returns the number of messages acted upon by this InfoHandler

func (*InfoHandler) MessagesHandled

func (i *InfoHandler) MessagesHandled() int

MessagesHandled returns the number of messages handled by this InfoHandler

func (*InfoHandler) Name

func (i *InfoHandler) Name() string

Name returns the name of this message handler

func (*InfoHandler) ReactionsActedUpon

func (i *InfoHandler) ReactionsActedUpon() int

ReactionsActedUpon returns the number of reactions acted upon by this InfoHandler

func (*InfoHandler) ReactionsHandled

func (i *InfoHandler) ReactionsHandled() int

ReactionsHandled returns the number of reactions handled by this InfoHandler

type MessageHandler

type MessageHandler interface {
	// should return true if no more handlers should run (i.e. the message was handled for good)
	HandleMessage(s *discordgo.Session, m *discordgo.MessageCreate, muted bool) bool
	MessagesHandled() int
	MessagesActedUpon() int
	Name() string
}

A MessageHandler can handle Discord messages

func GetMessageHandlers

func GetMessageHandlers() []MessageHandler

GetMessageHandlers returns the MessageHandlers the bot is using

type MuteManager

type MuteManager struct {
	sync.Mutex
	// contains filtered or unexported fields
}

MuteManager manages channel mutes (channels in which the bot will participate at a reduced rate)

func GetMuteManager

func GetMuteManager() *MuteManager

GetMuteManager returns the MuteManager the bot is using

func NewMuteManager

func NewMuteManager() *MuteManager

NewMuteManager initializes and returns a new MuteManager

func (*MuteManager) MuteChannel

func (m *MuteManager) MuteChannel(channelID string, muteDuration time.Duration)

MuteChannel mutes a channel temporarily for the specified duration

func (*MuteManager) MutedAny

func (m *MuteManager) MutedAny(channelID string) bool

MutedAny returns whether the specified channel is muted or perma-muted

func (*MuteManager) MutedPermanently

func (m *MuteManager) MutedPermanently(channelID string) bool

MutedPermanently returns whether the specified channel is perma-muted

func (*MuteManager) MutedTemporarily

func (m *MuteManager) MutedTemporarily(channelID string) bool

MutedTemporarily returns whether the specified channel is muted temporarily

func (*MuteManager) PermaMuteChannel

func (m *MuteManager) PermaMuteChannel(channelID string)

PermaMuteChannel mutes a channel permanently until PermaUnmuteChannel is called

func (*MuteManager) PermaUnmuteChannel

func (m *MuteManager) PermaUnmuteChannel(channelID string)

PermaUnmuteChannel perma-unmutes a channel

func (*MuteManager) UnmuteChannel

func (m *MuteManager) UnmuteChannel(channelID string)

UnmuteChannel ends the temporary mute on a channel

type PosPlayBridge

type PosPlayBridge struct {
	PlayerXPInfo                      func(userID string) (PosPlayXPInfo, error)
	OnEventWinCallback                func(userID, messageID string, XPreward int, eventType string) bool
	OnDiscussionParticipationCallback func(userID string, XPreward int) bool
	ReloadAchievementsCallback        func() error
	ReloadTemplatesCallback           func() error
	// contains filtered or unexported fields
}

PosPlayBridge manages PosPlay reaction events and rewards for user participation

func (*PosPlayBridge) EnsureUserInRole

func (e *PosPlayBridge) EnsureUserInRole(guildID, userID, roleID string)

EnsureUserInRole attempts to add an user to a role

func (*PosPlayBridge) HandleMessage

func (e *PosPlayBridge) HandleMessage(s *discordgo.Session, m *discordgo.MessageCreate, muted bool) bool

HandleMessage attempts to handle the provided message

func (*PosPlayBridge) HandleReaction

func (e *PosPlayBridge) HandleReaction(s *discordgo.Session, m *discordgo.MessageReactionAdd) bool

HandleReaction attempts to handle the provided reaction always returns false as this is a non-authoritative handler

func (*PosPlayBridge) MessagesActedUpon

func (e *PosPlayBridge) MessagesActedUpon() int

MessagesActedUpon returns the number of messages acted upon by this handler

func (*PosPlayBridge) MessagesHandled

func (e *PosPlayBridge) MessagesHandled() int

MessagesHandled returns the number of messages handled by this handler

func (*PosPlayBridge) Name

func (e *PosPlayBridge) Name() string

Name returns the name of this handler

func (*PosPlayBridge) ReactionsActedUpon

func (e *PosPlayBridge) ReactionsActedUpon() int

ReactionsActedUpon returns the number of reactions acted upon by this handler

func (*PosPlayBridge) ReactionsHandled

func (e *PosPlayBridge) ReactionsHandled() int

ReactionsHandled returns the number of reactions handled by this handler

func (*PosPlayBridge) StartMultipleChoiceQuizEvent

func (e *PosPlayBridge) StartMultipleChoiceQuizEvent(s *discordgo.Session, channel *discordgo.Channel, question string, choices []string, answer int, xpReward int, duration time.Duration) (*discordgo.Message, error)

StartMultipleChoiceQuizEvent starts a quiz event on the specified channel with the given XP reward and message, expiring after the given duration

func (*PosPlayBridge) StartQuizEvent

func (e *PosPlayBridge) StartQuizEvent(s *discordgo.Session, channel *discordgo.Channel, answerTrigger, answer string, numberOfAttempts int, xpReward int, duration time.Duration, messageContents string) (*discordgo.Message, error)

StartQuizEvent starts a quiz event on the specified channel with the given XP reward and message, expiring after the given duration

func (*PosPlayBridge) StartReactionEvent

func (e *PosPlayBridge) StartReactionEvent(s *discordgo.Session, channel *discordgo.Channel, xpReward int, duration time.Duration, messageContents string) (*discordgo.Message, error)

StartReactionEvent starts a reaction event on the specified channel with the given XP reward and message, expiring after the given duration

func (*PosPlayBridge) StopEvent

func (e *PosPlayBridge) StopEvent(eventID string) error

StopEvent stops the specified event, or returns an error if the ID does not match any event

type PosPlayXPInfo

type PosPlayXPInfo struct {
	Username      string
	ProfileURL    string
	AvatarURL     string
	Level         int
	LevelProgress float64
	XP            int
	XPthisWeek    int
	Rank          int
	RankThisWeek  int
}

PosPlayXPInfo contains information for the $xp command

type Privilege

type Privilege int

Privilege indicates the privilege of a user interacting with the bot, in order to restrict access to commands

const (
	// PrivilegeEveryone commands can be used by anyone
	PrivilegeEveryone Privilege = iota
	// PrivilegeAdmin commands can be user by the bot owner or by anyone in the
	// special admin channel
	PrivilegeAdmin
	// PrivilegeRoot commands can only be used by the bot owner
	PrivilegeRoot
	// PrivilegeNobody commands can not be used
	PrivilegeNobody
)

type ReactionHandler

type ReactionHandler interface {
	// should return true if no more handlers should run (i.e. the reaction was handled for good)
	HandleReaction(s *discordgo.Session, m *discordgo.MessageReactionAdd) bool
	ReactionsHandled() int
	ReactionsActedUpon() int
	Name() string
}

A ReactionHandler can handle Discord reactions

func GetReactionHandlers

func GetReactionHandlers() []ReactionHandler

GetReactionHandlers returns the ReactionHandlers the bot is using

type SQLSystem

type SQLSystem struct {
	sync.Mutex
	// contains filtered or unexported fields
}

SQLSystem handles running SQL statements as bot commands

func (*SQLSystem) Setup

func (ssys *SQLSystem) Setup(node sqalx.Node, cl *CommandLibrary, privilege Privilege)

Setup initializes the SQLSystem and configures a command library with SQL-related commands

type ScriptSystem

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

ScriptSystem handles scripting-related commands

func (*ScriptSystem) Setup

func (ssys *ScriptSystem) Setup(node sqalx.Node, cl *CommandLibrary, privilege Privilege)

Setup registers script-related commands

type Stats

type Stats struct {
	StartTime           time.Time
	UserCount           int
	BotCount            int
	DMChannels          map[string]bool
	GroupDMChannelCount int
	TextChannelCount    int
	VoiceChannelCount   int
}

Stats contains bot stats

func BotStats

func BotStats() *Stats

BotStats returns the bot stats

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL