dhelpers

package module
v0.0.0-...-905ac89 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2018 License: MIT Imports: 44 Imported by: 3

Documentation

Index

Constants

View Source
const (
	// ZeroWidthSpace is a zero width space character, can be used to invalid mentions or fill embed fields
	ZeroWidthSpace = "\u200B"

	// DiscordDarkThemeBackgroundColor is the Background Colour of Discord Dark Theme
	DiscordDarkThemeBackgroundColor = "#36393F"
)
View Source
const (
	ChannelCreateEventType            EventType = "CHANNEL_CREATE"
	ChannelDeleteEventType                      = "CHANNEL_DELETE"
	ChannelPinsUpdateEventType                  = "CHANNEL_PINS_UPDATE"
	ChannelUpdateEventType                      = "CHANNEL_UPDATE"
	GuildBanAddEventType                        = "GUILD_BAN_ADD"
	GuildBanRemoveEventType                     = "GUILD_BAN_REMOVE"
	GuildCreateEventType                        = "GUILD_CREATE"
	GuildDeleteEventType                        = "GUILD_DELETE"
	GuildEmojisUpdateEventType                  = "GUILD_EMOJIS_UPDATE"
	GuildMemberAddEventType                     = "GUILD_MEMBER_ADD"
	GuildMemberRemoveEventType                  = "GUILD_MEMBER_REMOVE"
	GuildMemberUpdateEventType                  = "GUILD_MEMBER_UPDATE"
	GuildMembersChunkEventType                  = "GUILD_MEMBERS_CHUNK"
	GuildRoleCreateEventType                    = "GUILD_ROLE_CREATE"
	GuildRoleDeleteEventType                    = "GUILD_ROLE_DELETE"
	GuildRoleUpdateEventType                    = "GUILD_ROLE_UPDATE"
	GuildUpdateEventType                        = "GUILD_UPDATE"
	MessageCreateEventType                      = "MESSAGE_CREATE"
	MessageDeleteEventType                      = "MESSAGE_DELETE"
	MessageReactionAddEventType                 = "MESSAGE_REACTION_ADD"
	MessageReactionRemoveEventType              = "MESSAGE_REACTION_REMOVE"
	MessageReactionRemoveAllEventType           = "MESSAGE_REACTION_REMOVE_ALL"
	MessageUpdateEventType                      = "MESSAGE_UPDATE"
	PresenceUpdateEventType                     = "PRESENCE_UPDATE"
)

defines discordgo event types for the EventContainer

View Source
const (
	LambdaDestinationType DestinationType = "lambda"
	SqsDestinationType                    = "sqs"
	KafkaDestinationType                  = "kafka"
)

defines possible destination types

View Source
const (
	LastFmPeriodOverall LastFmPeriod = "overall"
	LastFmPeriod7day                 = "7day"
	LastFmPeriod1month               = "1month"
	LastFmPeriod3month               = "3month"
	LastFmPeriod6month               = "6month"
	LastFmPeriod12month              = "12month"
)

defines possible LastFM periods

Variables

This section is empty.

Functions

func AddFile

func AddFile(ctx context.Context, name string, data []byte, metadata AddFileMetadata, source string, public bool) (objectName string, err error)

AddFile stores a file name : the name of the new object, can be empty to generate an unique name data : the file data metadata : metadata attached to the object source : the source name for the file, for example the module name, can not be empty public : if true file will be available via the website proxy TODO: prevent duplicates

func CheckErr

func CheckErr(err error, message ...string)

CheckErr panics if err is not nil

func CleanURL

func CleanURL(uncleanedURL string) (url string)

CleanURL makes a URL posted in discord ready to use for further usage

func DecimalToHex

func DecimalToHex(colour int) (hex string)

DecimalToHex returns a hex color form a decimal color

func DeleteFile

func DeleteFile(ctx context.Context, objectName string) (err error)

DeleteFile deletes a file objectName : the name of the object

func DiscordTime

func DiscordTime(theTime time.Time) string

DiscordTime returns a time formatted to be used in Embeds

func EditComplexWithBot

func EditComplexWithBot(botID string, data *discordgo.MessageEdit) (message *discordgo.Message, err error)

EditComplexWithBot edits a specific message using a discordgo.MessageEdit object, takes care of sanitising the content

func EditEmbedWithBot

func EditEmbedWithBot(botID, channelID, messageID string, embed *discordgo.MessageEmbed) (message *discordgo.Message, err error)

EditEmbedWithBot edits a specific embed, takes care of sanitising the content

func EditMessageWithBot

func EditMessageWithBot(botID, channelID, messageID, content string) (message *discordgo.Message, err error)

EditMessageWithBot edits a specific message, takes care of sanitising the content

func EditMessagefWithBot

func EditMessagefWithBot(botID, channelID, messageID, content string, fields ...interface{}) (message *discordgo.Message, err error)

EditMessagefWithBot edits a specific message, takes care of sanitising the content, and replacing the fields

func EditMessagefcWithBot

func EditMessagefcWithBot(botID, channelID, messageID, content string, count int, fields ...interface{}) (message *discordgo.Message, err error)

EditMessagefcWithBot edits a specific message, takes care of sanitising the content, and replacing the fields, and applying pluralization

func EscapeLinkForMarkdown

func EscapeLinkForMarkdown(input string) (result string)

EscapeLinkForMarkdown escapes a link to be ready to used in markdown

func GetAllPrefix

func GetAllPrefix(botUserID, guildID string) (prefixes []string)

GetAllPrefix returns all possible prefixes for a specific guildID

func GetEventKey

func GetEventKey(i interface{}) (key string)

GetEventKey returns an unique key for a discordgo event for deduplication

func GetMD5Hash

func GetMD5Hash(text string) string

GetMD5Hash returns the md5 hash for a string

func GetMessageArguments

func GetMessageArguments(content string, prefixes []string) (args []string, prefix string)

GetMessageArguments trims the prefix and returns all arguments, including the command, and the prefix used

func GetPrefix

func GetPrefix(guildID string) (prefix string)

GetPrefix returns the default prefix for a specific GuildID

func HandleErrWith

func HandleErrWith(service string, err error, event *EventContainer, errorHandlers ...ErrorHandlerType)

HandleErrWith handles an error with the given error handles event can be nil currently supported ErrorHandlerTypes: SentryErrorHandler, and DiscordErrorHandler

func HandleHTTPErrorWith

func HandleHTTPErrorWith(service string, request *http.Request, err error, errorHandlers ...ErrorHandlerType)

HandleHTTPErrorWith handles a HTTP error, if errorHandlers is nil it will be sent to sentry currently supported ErrorHandlerTypes: SentryErrorHandler

func HandleJobErrorWith

func HandleJobErrorWith(service, job string, err error, errorHandlers ...ErrorHandlerType)

HandleJobErrorWith handles a Job error, if errorHandlers is nil it will be sent to sentry currently supported ErrorHandlerTypes: SentryErrorHandler

func HexToDecimal

func HexToDecimal(hex string) int

HexToDecimal returns a decimal color from a hex color

func IsNetworkErr

func IsNetworkErr(err error) (is bool)

IsNetworkErr returns true if an error is network related

func IsNewEvent

func IsNewEvent(redisClient *redis.Client, source, eventKey string) (new bool)

IsNewEvent returns true if the event key is new, returns false if the event key has already been handled by other gateways

func JobErrorHandler

func JobErrorHandler(jobName string)

JobErrorHandler handles errors at jobs, defer to this: defer JobErrorHandler(jobName)

func JobFinishSuccess

func JobFinishSuccess(healthcheckURL string) error

JobFinishSuccess calls the healthcheck if exists

func JobStart

func JobStart(jobName string, timeout time.Duration) (start bool, locker *lock.Locker, err error)

JobStart returns true and a locker if the Job has been started successfully, returns false if the Job is already running after timeout the locks unlock itself, use locker.Lock() to renew a lock

func LastFmGuildTopTracksKey

func LastFmGuildTopTracksKey(guildID string, period LastFmPeriod) (key string)

LastFmGuildTopTracksKey returns the redis key for LastFmGuildTopTracks

func LogError

func LogError(err error)

LogError sends an error to sentry and logs it, can be nil

func RecoverLog

func RecoverLog()

RecoverLog can be recovered to, all errors will be logged

func RetrieveFile

func RetrieveFile(ctx context.Context, objectName string) (data []byte, err error)

RetrieveFile retrieves a file objectName : the name of the file to retrieve

func RetrieveFileByHash

func RetrieveFileByHash(ctx context.Context, hash string) (filename, filetype string, data []byte, err error)

RetrieveFileByHash retrieves a file by the object name md5 hash hash : the md5 hash

func RetrieveFileInformation

func RetrieveFileInformation(ctx context.Context, objectName string) (info models.StorageEntry, err error)

RetrieveFileInformation retrieves information about a file objectName : the name of the file to retrieve

func RetrieveFilesByAdditionalObjectMetadata

func RetrieveFilesByAdditionalObjectMetadata(ctx context.Context, key, value string) (objectNames []string, err error)

RetrieveFilesByAdditionalObjectMetadata retrieves files by additional object metadta currently supported file sources: custom commands hash : the md5 hash

func RoutingMatchMessage

func RoutingMatchMessage(routingEntry RoutingRule, author, bot *discordgo.User, channel *discordgo.Channel, content string, args []string, prefix string) (match bool)

RoutingMatchMessage checks if a message content matches the requirements of the routing rule

func SendComplexWithBot

func SendComplexWithBot(botID, channelID string, data *discordgo.MessageSend) (messages []*discordgo.Message, err error)

SendComplexWithBot sends a discordgo.MessageSend object to a specific channel, takes care of splitting and sanitising the content

func SendEmbedWithBot

func SendEmbedWithBot(botID, channelID string, embed *discordgo.MessageEmbed) (messages []*discordgo.Message, err error)

SendEmbedWithBot sends an embed to a specific channel, takes care of splitting and sanitising the content

func SendFileWithBot

func SendFileWithBot(botID, channelID string, filename string, reader io.Reader, message string) (messages []*discordgo.Message, err error)

SendFileWithBot sends a file to a specific channel, takes care of splitting and sanitising the content

func SendMessageBoxedWithBot

func SendMessageBoxedWithBot(botID, channelID, content string) (messages []*discordgo.Message, err error)

SendMessageBoxedWithBot sends a message to a specific channel, will put a box around it, takes care of splitting and sanitising the content

func SendMessageBoxedfWithBot

func SendMessageBoxedfWithBot(botID, channelID, content string, fields ...interface{}) (messages []*discordgo.Message, err error)

SendMessageBoxedfWithBot sends a message to a specific channel, will put a box around it, takes care of splitting and sanitising the content, and replacing the fields

func SendMessageWithBot

func SendMessageWithBot(botID, channelID, content string) (messages []*discordgo.Message, err error)

SendMessageWithBot sends a message to a specific channel, takes care of splitting and sanitising the content

func SendMessagefWithBot

func SendMessagefWithBot(botID, channelID, content string, fields ...interface{}) (messages []*discordgo.Message, err error)

SendMessagefWithBot sends a message to a specific channel, takes care of splitting and sanitising the content, and replacing the fields

func SendMessagefcWithBot

func SendMessagefcWithBot(botID, channelID, content string, count int, fields ...interface{}) (messages []*discordgo.Message, err error)

SendMessagefcWithBot sends a message to a specific channel, takes care of splitting and sanitising the content, and replacing the fields, and applying pluralization

func SetDiscordEndpoints

func SetDiscordEndpoints(endpointDiscord string)

SetDiscordEndpoints sets endpoints with a custom base discord host https://github.com/bwmarrin/discordgo/blob/master/endpoints.go#L181

func T

func T(messageID string) (result string)

T returns the translation for the given message ID Example: T("HelloWorld")

func Tf

func Tf(messageID string, fields ...interface{}) (result string)

Tf returns the translation for the given message ID applying the fields Example: Tf("HelloWorld", "key", "value")

func Tfc

func Tfc(messageID string, count int, fields ...interface{}) (result string)

Tfc returns the translation for the given message ID applying the fields and pluralization count Example: Tfc("HelloWorld", 3, "key", "value")

func ToArgv

func ToArgv(s string) ([]string, error)

ToArgv converts string s into an string array

text in quotes will be counted as 1 array element

Source: https://github.com/Seklfreak/Robyul2/blob/master/helpers/text.go#L14

Types

type AddFileMetadata

type AddFileMetadata struct {
	Filename           string            // the actual file name, can be empty
	ChannelID          string            // the source channel ID, can be empty, but should be set if possible
	UserID             string            // the source user ID, can be empty, but should be set if possible
	GuildID            string            // the source guild ID, can be empty but should be set if possible, will be set automatically if ChannelID has been set
	AdditionalMetadata map[string]string // additional metadata attached to the object
}

AddFileMetadata defines possible metadta for new objects

type DestinationData

type DestinationData struct {
	Type          DestinationType
	Name          string
	ErrorHandlers []ErrorHandlerType
	Alias         string
}

DestinationData contains all information for one destination

func ContainerDestinations

func ContainerDestinations(session *discordgo.Session, routingConfig []RoutingRule, container EventContainer) (destinations []DestinationData)

ContainerDestinations figures out the correct destinations for an event container

type DestinationType

type DestinationType string

DestinationType is a type for destination types

type Environment

type Environment string

Environment is the type for possible Environments

const (
	// EnvironmentDevelopment is the development environment
	EnvironmentDevelopment Environment = "development"
	// EnvironmentTesting is the testing environment
	EnvironmentTesting Environment = "testing"
	// EnvironmentStaging is the staging environment
	EnvironmentStaging Environment = "staging"
	// EnvironmentProduction is the production environment
	EnvironmentProduction Environment = "production"
)

func GetEnvironment

func GetEnvironment() Environment

GetEnvironment returns the current environment it reads the environment from the Environment variable ENV or Environment if none is set it is always development

type ErrorHandlerType

type ErrorHandlerType string

ErrorHandlerType is the Error Handler Type used for the EventContainer

const (
	SentryErrorHandler  ErrorHandlerType = "sentry"
	DiscordErrorHandler                  = "discord"
)

defines ErrorHandler types

type EventContainer

type EventContainer struct {
	Type           EventType
	Key            string
	ReceivedAt     time.Time
	GatewayStarted time.Time
	Modules        []string
	Destinations   []DestinationData
	Prefix         string
	Args           []string
	BotUserID      string
	// Events
	ChannelCreate            *discordgo.ChannelCreate
	ChannelDelete            *discordgo.ChannelDelete
	ChannelPinsUpdate        *discordgo.ChannelPinsUpdate
	ChannelUpdate            *discordgo.ChannelUpdate
	GuildBanAdd              *discordgo.GuildBanAdd
	GuildBanRemove           *discordgo.GuildBanRemove
	GuildCreate              *discordgo.GuildCreate
	GuildDelete              *discordgo.GuildDelete
	GuildEmojisUpdate        *discordgo.GuildEmojisUpdate
	GuildMemberAdd           *discordgo.GuildMemberAdd
	GuildMemberRemove        *discordgo.GuildMemberRemove
	GuildMemberUpdate        *discordgo.GuildMemberUpdate
	GuildMembersChunk        *discordgo.GuildMembersChunk
	GuildRoleCreate          *discordgo.GuildRoleCreate
	GuildRoleDelete          *discordgo.GuildRoleDelete
	GuildRoleUpdate          *discordgo.GuildRoleUpdate
	GuildUpdate              *discordgo.GuildUpdate
	MessageCreate            *discordgo.MessageCreate
	MessageDelete            *discordgo.MessageDelete
	MessageReactionAdd       *discordgo.MessageReactionAdd
	MessageReactionRemove    *discordgo.MessageReactionRemove
	MessageReactionRemoveAll *discordgo.MessageReactionRemoveAll
	MessageUpdate            *discordgo.MessageUpdate
	PresenceUpdate           *discordgo.PresenceUpdate
}

EventContainer is a container for all events sent to Lambdas or the SQS Queue

func CreateEventContainer

func CreateEventContainer(gatewayStartedAt, receivedAt time.Time, session *discordgo.Session, eventKey string, i interface{}) (container EventContainer)

CreateEventContainer creates an EventContainer from a discord event

func (EventContainer) EditComplex

func (event EventContainer) EditComplex(data *discordgo.MessageEdit) (message *discordgo.Message, err error)

EditComplex edits a specific message using a discordgo.MessageEdit object, takes care of sanitising the content

func (EventContainer) EditEmbed

func (event EventContainer) EditEmbed(channelID, messageID string, embed *discordgo.MessageEmbed) (message *discordgo.Message, err error)

EditEmbed edits a specific embed, takes care of sanitising the content

func (EventContainer) EditMessage

func (event EventContainer) EditMessage(channelID, messageID, content string) (message *discordgo.Message, err error)

EditMessage edits a specific message, takes care of sanitising the content

func (EventContainer) EditMessagef

func (event EventContainer) EditMessagef(channelID, messageID, content string, fields ...interface{}) (message *discordgo.Message, err error)

EditMessagef edits a specific message, takes care of sanitising the content, and replacing the fields, the event variable is being set

func (EventContainer) EditMessagefc

func (event EventContainer) EditMessagefc(channelID, messageID, content string, count int, fields ...interface{}) (message *discordgo.Message, err error)

EditMessagefc edits a specific message, takes care of sanitising the content, and replacing the fields, and applying pluralization, the event variable is being set

func (EventContainer) GoType

func (event EventContainer) GoType(channelID ...string)

GoType starts a goroutine to start a typing indicator in a channel it will use the channelID if given, if not it will try to use the channelID from the event, the following events are supported at the moment: MESSAGE_CREATE, MESSAGE_UPDATE, MESSAGE_DELETE, MESSAGE_REACTION_ADD, MESSAGE_REACTION_REMOVE,

MESSAGE_REACTION_REMOVE_ALL, CHANNEL_CREATE, CHANNEL_UPDATE, CHANNEL_DELETE, CHANNEL_PINS_UPDATE

func (EventContainer) SendComplex

func (event EventContainer) SendComplex(channelID string, data *discordgo.MessageSend) (messages []*discordgo.Message, err error)

SendComplex sends a discordgo.MessageSend object to a specific channel, takes care of splitting and sanitising the content

func (EventContainer) SendEmbed

func (event EventContainer) SendEmbed(channelID string, embed *discordgo.MessageEmbed) (messages []*discordgo.Message, err error)

SendEmbed sends an embed to a specific channel, takes care of splitting and sanitising the content

func (EventContainer) SendFile

func (event EventContainer) SendFile(channelID string, filename string, reader io.Reader, message string) (messages []*discordgo.Message, err error)

SendFile sends a file to a specific channel, takes care of splitting and sanitising the content

func (EventContainer) SendMessage

func (event EventContainer) SendMessage(channelID, content string) (messages []*discordgo.Message, err error)

SendMessage sends a message to a specific channel, takes care of splitting and sanitising the content, the event variable is being set

func (EventContainer) SendMessageBoxed

func (event EventContainer) SendMessageBoxed(channelID, content string) (messages []*discordgo.Message, err error)

SendMessageBoxed sends a message to a specific channel, will put a box around it, takes care of splitting and sanitising the content, the event variable is being set

func (EventContainer) SendMessagef

func (event EventContainer) SendMessagef(channelID, content string, fields ...interface{}) (messages []*discordgo.Message, err error)

SendMessagef sends a message to a specific channel, takes care of splitting and sanitising the content, and replacing the fields, the event variable is being set

func (EventContainer) SendMessagefc

func (event EventContainer) SendMessagefc(channelID, content string, count int, fields ...interface{}) (messages []*discordgo.Message, err error)

SendMessagefc sends a message to a specific channel, takes care of splitting and sanitising the content, and replacing the fields, and applying pluralization, the event variable is being set

func (EventContainer) T

func (event EventContainer) T(messageID string) (result string)

T returns the translation for the given message ID, the event variable is being set Example: T("HelloWorld")

func (EventContainer) Tf

func (event EventContainer) Tf(messageID string, fields ...interface{}) (result string)

Tf returns the translation for the given message ID applying the fields, the event variable is being set Example: Tf("HelloWorld", "key", "value")

func (EventContainer) Tfc

func (event EventContainer) Tfc(messageID string, count int, fields ...interface{}) (result string)

Tfc returns the translation for the given message ID applying the fields and pluralization count, the event variable is being set Example: Tfc("HelloWorld", 3, "key", "value")

type EventType

type EventType string

EventType is the Type used for the EventContainer

type Job

type Job struct {
	// Name should be unique, prefixed by module
	Name string
	// Cron is a cron expression https://godoc.org/github.com/robfig/cron#hdr-CRON_Expression_Format, https://crontab.guru/
	Cron string
	// AtLaunch if set to true will start the Job at launch
	AtLaunch bool
	Job      func()
}

Job defines setting for a job

type LastFmGuildTopTracks

type LastFmGuildTopTracks struct {
	GuildID       string
	NumberOfUsers int
	Period        LastFmPeriod
	Tracks        []LastfmTrackData
	CachedAt      time.Time
}

LastFmGuildTopTracks contains the top tracks for a guild, it is built by the Worker and stored in redis

type LastFmPeriod

type LastFmPeriod string

LastFmPeriod is a type for periods used for Last.FM requests

func LastFmGetPeriodFromArgs

func LastFmGetPeriodFromArgs(args []string) (period LastFmPeriod, newArgs []string)

LastFmGetPeriodFromArgs parses args to figure out the correct period

type LastfmAlbumData

type LastfmAlbumData struct {
	Name      string
	URL       string
	ImageURL  string
	Artist    string
	ArtistURL string
	Scrobbles int
}

LastfmAlbumData contains information about an Album on LastFM

func LastFmGetTopAlbums

func LastFmGetTopAlbums(ctx context.Context, lastfmUsername string, limit int, period LastFmPeriod) (albumsData []LastfmAlbumData, err error)

LastFmGetTopAlbums returns the top albums of an user

type LastfmArtistData

type LastfmArtistData struct {
	Name      string
	URL       string
	ImageURL  string
	Scrobbles int
}

LastfmArtistData contains information about an Artist on LastFM

func LastFmGetTopArtists

func LastFmGetTopArtists(ctx context.Context, lastfmUsername string, limit int, period LastFmPeriod) (artistsData []LastfmArtistData, err error)

LastFmGetTopArtists returns the top artists of an user

type LastfmTrackData

type LastfmTrackData struct {
	Name           string
	URL            string
	ImageURL       string
	Artist         string
	ArtistURL      string
	ArtistImageURL string
	Album          string
	Time           time.Time
	Loved          bool
	NowPlaying     bool
	Scrobbles      int
	// used for guild stats
	Users int
}

LastfmTrackData contains information about a Track on LastFM

func LastFmGetRecentTracks

func LastFmGetRecentTracks(ctx context.Context, lastfmUsername string, limit int) (tracksData []LastfmTrackData, err error)

LastFmGetRecentTracks returns recent tracks listened to by an user

func LastFmGetTopTracks

func LastFmGetTopTracks(ctx context.Context, lastfmUsername string, limit int, period LastFmPeriod) (tracksData []LastfmTrackData, err error)

LastFmGetTopTracks returns the top tracks of an user

type LastfmUserData

type LastfmUserData struct {
	Username        string
	Name            string
	Icon            string
	Scrobbles       int
	Country         string
	AccountCreation time.Time
}

LastfmUserData contains information about an User on LastFM

func LastFmGetUserinfo

func LastFmGetUserinfo(ctx context.Context, lastfmUsername string) (userData LastfmUserData, err error)

LastFmGetUserinfo returns information about a LastFM user

type PrefixRule

type PrefixRule struct {
	GuildID string
	Prefix  []string
}

PrefixRule stores the Prefix Config for a Guild

func GetPrefixes

func GetPrefixes() (prefixRules []PrefixRule)

GetPrefixes returns all customized prefix entries for guilds

type RoutingRule

type RoutingRule struct {
	Event              EventType
	ErrorHandlers      []ErrorHandlerType
	Module             string
	DestinationMain    string
	DestinationSub     string
	Beginning          string
	Alias              string
	Regex              *regexp.Regexp
	DoNotPrependPrefix bool
	CaseSensitive      bool
	Always             bool
	AllowBots          bool
	AllowMyself        bool
	AllowDM            bool
}

RoutingRule is a a compiled routing rule used for matching

func GetRoutings

func GetRoutings() (routingRules []RoutingRule, err error)

GetRoutings returns a sorted slice (by priority) with all rules

Jump to

Keyboard shortcuts

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