common

package
v0.29.1 Latest Latest
Warning

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

Go to latest
Published: May 23, 2018 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

this package provides core functinality to yagpdb, important security stuff here

Index

Constants

View Source
const (
	VERSIONMAJOR = 0
	VERSIONMINOR = 30
	VERSIONPATCH = 1
	Testing      = false // Disables stuff like command cooldowns
)

Variables

View Source
var (
	ErrNotFound    = errors.New("Not found")
	CacheKeyPrefix = "cache_"

	Cache *ccache.Cache
)
View Source
var (
	VERSIONNUMBER = fmt.Sprintf("%d.%d.%d", VERSIONMAJOR, VERSIONMINOR, VERSIONPATCH)
	VERSION       = VERSIONNUMBER + " Skeletal"

	GORM *gorm.DB
	PQ   *sql.DB

	// RedisPool   *pool.Pool
	RedisPool redisPool

	BotSession *discordgo.Session
	BotUser    *discordgo.User
	Conf       *CoreConfig

	RedisPoolSize = 25
)
View Source
var Adjectives = []string{}/* 1345 elements not displayed */
View Source
var (
	ErrMaxLockAttemptsExceeded = errors.New("Max lock attempts exceeded")
)
View Source
var (
	Plugins []Plugin
)
View Source
var StringPerms = map[int]string{
	discordgo.PermissionReadMessages:       "Read Messages",
	discordgo.PermissionSendMessages:       "Send Messages",
	discordgo.PermissionSendTTSMessages:    "Send TTS Messages",
	discordgo.PermissionManageMessages:     "Manage Messages",
	discordgo.PermissionEmbedLinks:         "Embed Links",
	discordgo.PermissionAttachFiles:        "Attach Files",
	discordgo.PermissionReadMessageHistory: "Read Message History",
	discordgo.PermissionMentionEveryone:    "Mention Everyone",
	discordgo.PermissionVoiceConnect:       "Voice Connect",
	discordgo.PermissionVoiceSpeak:         "Voice Speak",
	discordgo.PermissionVoiceMuteMembers:   "Voice Mute Members",
	discordgo.PermissionVoiceDeafenMembers: "Voice Deafen Members",
	discordgo.PermissionVoiceMoveMembers:   "Voice Move Members",
	discordgo.PermissionVoiceUseVAD:        "Voice Use VAD",

	discordgo.PermissionCreateInstantInvite: "Create Instant Invite",
	discordgo.PermissionKickMembers:         "Kick Members",
	discordgo.PermissionBanMembers:          "Ban Members",
	discordgo.PermissionManageRoles:         "Manage Roles",
	discordgo.PermissionManageChannels:      "Manage Channels",
	discordgo.PermissionManageServer:        "Manage Server",
}

Functions

func AddCPLogEntry

func AddCPLogEntry(user *discordgo.User, guild int64, args ...interface{})

func AddRole

func AddRole(member *discordgo.Member, role int64, guildID int64) error

func BlockingLockRedisKey

func BlockingLockRedisKey(client *redis.Client, key string, maxTryDuration time.Duration, maxLockDur int) error

BlockingLockRedisKey blocks until it suceeded to lock the key

func ContainsInt64Slice

func ContainsInt64Slice(slice []int64, search int64) bool

func ContainsStringSlice

func ContainsStringSlice(strs []string, search string) bool

func ContainsStringSliceFold

func ContainsStringSliceFold(strs []string, search string) bool

func CutStringShort

func CutStringShort(s string, l int) string

CutStringShort stops a strinng at "l"-3 if it's longer than "l" and adds "..."

func DelayedMessageDelete

func DelayedMessageDelete(session *discordgo.Session, delay time.Duration, cID, mID int64)

DelayedMessageDelete Deletes a message after delay

func DiscordError

func DiscordError(err error) (code int, msg string)

DiscordError extracts the errorcode discord sent us

func ErrWithCaller

func ErrWithCaller(err error) error

func EscapeSpecialMentions

func EscapeSpecialMentions(in string) string

EscapeSpecialMentions Escapes an everyone mention, adding a zero width space between the '@' and rest

func EscapeSpecialMentionsConditional

func EscapeSpecialMentionsConditional(s string, allowEveryone, allowHere bool, allowRoles []int64) string

EscapeSpecialMentionsConditional Escapes an everyone mention, adding a zero width space between the '@' and rest

func FallbackEmbed

func FallbackEmbed(embed *discordgo.MessageEmbed) string

func GenID

func GenID(client *redis.Client, key string) string

func GetCacheData

func GetCacheData(client *redis.Client, key string) ([]byte, error)

Items in the cache expire after 1 min

func GetCacheDataJson

func GetCacheDataJson(client *redis.Client, key string, dest interface{}) error

func GetGuild

func GetGuild(client *redis.Client, guildID int64) (guild *discordgo.Guild, err error)

GetGuild returns the guild from guildid either from cache or api

func GetGuildChannels

func GetGuildChannels(client *redis.Client, guildID int64) (channels []*discordgo.Channel, err error)

GetGuildChannels returns the guilds channels either from cache or api

func GetRedisJson

func GetRedisJson(client *redis.Client, key string, out interface{}) error

GetRedisJson executes a get redis command and unmarshals the value into out

func GetRedisJsonDefault

func GetRedisJsonDefault(client *redis.Client, key string, out interface{}) error

GetRedisJson executes a get redis command and unmarshals the value into out

func GetRedisReplies

func GetRedisReplies(client *redis.Client, n int) ([]*redis.Resp, error)

GetRedisReplies is a helper func when using redis pipelines It retrieves n amount of replies and returns the first error it finds (but still continues to retrieve replies after that)

func HumanizeDuration

func HumanizeDuration(precision DurationFormatPrecision, in time.Duration) string

func HumanizeTime

func HumanizeTime(precision DurationFormatPrecision, in time.Time) string

func Init

func Init() error

Initalizes all database connections, config loading and so on

func InitTest

func InitTest()

func IsDiscordErr

func IsDiscordErr(err error, codes ...int) bool

IsDiscordErr returns true if this was a discord error and one of the codes matches

func KeyGuild

func KeyGuild(guildID int64) string

func KeyGuildChannels

func KeyGuildChannels(guildID int64) string

func MustGetRedisClient

func MustGetRedisClient() *redis.Client

func MustParseInt

func MustParseInt(s string) int64

func RandomAdjective

func RandomAdjective() string

func RedisBool

func RedisBool(resp *redis.Resp) (b bool, err error)

func RedisDialFunc

func RedisDialFunc(network, addr string) (client *redis.Client, err error)

func RefreshConnectedGuilds

func RefreshConnectedGuilds(session *discordgo.Session, client *redis.Client) error

RefreshConnectedGuilds deletes the connected_guilds set and fill it up again This is incase servers are removed/bot left servers while it was offline

func RegisterPlugin

func RegisterPlugin(plugin Plugin)

RegisterPlugin registers a plugin, should be called when the bot is starting up

func RegisterPluginL

func RegisterPluginL(pl Plugin)

RegisterPluginL registers a plugin, should be called when the bot is starting up

func RemoveRole

func RemoveRole(member *discordgo.Member, role int64, guildID int64) error

func RetrySendMessage

func RetrySendMessage(channel int64, msg interface{}, maxTries int) error

func SafeRedisCommands

func SafeRedisCommands(client *redis.Client, cmds []*RedisCmd) ([]*redis.Resp, error)

SafeRedisCommands Will do the following commands and stop if an error occurs

func SendEmbedWithFallback

func SendEmbedWithFallback(s *discordgo.Session, channelID int64, embed *discordgo.MessageEmbed) (*discordgo.Message, error)

func SendTempMessage

func SendTempMessage(session *discordgo.Session, duration time.Duration, cID int64, msg string)

SendTempMessage sends a message that gets deleted after duration

func SetCacheData

func SetCacheData(client *redis.Client, key string, expire int, data []byte) error

Stores an entry in the cache and sets it to expire after expire

func SetCacheDataJson

func SetCacheDataJson(client *redis.Client, key string, expire int, data interface{}) error

Helper methods

func SetCacheDataJsonSimple

func SetCacheDataJsonSimple(client *redis.Client, key string, data interface{}) error

func SetCacheDataSimple

func SetCacheDataSimple(client *redis.Client, key string, data []byte) error

Stores an entry in the cache and sets it to expire after a minute

func SetRedisJson

func SetRedisJson(client *redis.Client, key string, value interface{}) error

SetRedisJson marshals the value and runs a set redis command for key

func TryLockRedisKey

func TryLockRedisKey(client *redis.Client, key string, maxDur int) (bool, error)

Locks the lock and if succeded sets it to expire after maxdur So that if someting went wrong its not locked forever

func UnlockRedisKey

func UnlockRedisKey(client *redis.Client, key string)

func ValidateSQLSchema

func ValidateSQLSchema(input string)

ValidateSQLSchema does some simple security checks on a sql schema file At the moment it only checks for drop table/index statements accidentally left in the schema file

Types

type BasePlugin

type BasePlugin struct {
	Entry *logrus.Entry
}

func (*BasePlugin) Logger

func (p *BasePlugin) Logger() *logrus.Entry

func (*BasePlugin) SetLogger

func (p *BasePlugin) SetLogger(entry *logrus.Entry)

type CPLogEntry

type CPLogEntry struct {
	Timestamp int64  `json:"ts"`
	Action    string `json:"action"`

	TimestampString string `json:"-"`
}

func GetCPLogEntries

func GetCPLogEntries(client *redis.Client, guild int64) ([]*CPLogEntry, error)

type ContextHook

type ContextHook struct{}

func (ContextHook) Fire

func (hook ContextHook) Fire(entry *logrus.Entry) error

func (ContextHook) Levels

func (hook ContextHook) Levels() []logrus.Level

type ContextKey

type ContextKey int
const (
	ContextKeyRedis ContextKey = iota
	ContextKeyDiscordSession
	ContextKeyTemplateData
	ContextKeyUser
	ContextKeyGuilds
	ContextKeyCurrentGuild
	ContextKeyCurrentUserGuild
	ContextKeyGuildChannels
	ContextKeyGuildRoles
	ContextKeyParsedForm
	ContextKeyFormOk
	ContextKeyBotMember
	ContextKeyBotPermissions
	ContextKeyHighestBotRole
	ContextKeyLogger
)

type CoreConfig

type CoreConfig struct {
	Owner int64
	BotID int64

	ClientID     string
	ClientSecret string
	BotToken     string
	Host         string
	Email        string // The letsencrypt cert will use this email

	PQHost     string
	PQUsername string
	PQPassword string
	Redis      string
}

func LoadConfig

func LoadConfig() (c *CoreConfig, err error)

type DurationFormatPrecision

type DurationFormatPrecision int
const (
	DurationPrecisionSeconds DurationFormatPrecision = iota
	DurationPrecisionMinutes
	DurationPrecisionHours
	DurationPrecisionDays
	DurationPrecisionWeeks
	DurationPrecisionYears
)

func (DurationFormatPrecision) FromSeconds

func (d DurationFormatPrecision) FromSeconds(in int64) int64

func (DurationFormatPrecision) String

func (d DurationFormatPrecision) String() string

type LoggedExecutedCommand

type LoggedExecutedCommand struct {
	SmallModel

	UserID    string
	ChannelID string
	GuildID   string

	// Name of command that was triggered
	Command string
	// Raw command with arguments passed
	RawCommand string
	// If command returned any error this will be no-empty
	Error string

	TimeStamp    time.Time
	ResponseTime int64
}

func (LoggedExecutedCommand) TableName

func (l LoggedExecutedCommand) TableName() string

type Plugin

type Plugin interface {
	Name() string
}

Plugin represents a plugin, all plugins needs to implement this at a bare minimum

type PluginWithLogging

type PluginWithLogging interface {
	Logger() *logrus.Entry
	SetLogger(entry *logrus.Entry)
}

type RedisCmd

type RedisCmd struct {
	Name string
	Args []interface{}
}

type STDLogProxy

type STDLogProxy struct{}

func (*STDLogProxy) Write

func (p *STDLogProxy) Write(b []byte) (n int, err error)

type SmallModel

type SmallModel struct {
	ID        uint `gorm:"primary_key"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type WrappedGuild

type WrappedGuild struct {
	*discordgo.UserGuild
	Connected bool
}

func GetWrapped

func GetWrapped(in []*discordgo.UserGuild, client *redis.Client) ([]*WrappedGuild, error)

GetWrapped Returns a wrapped guild with connected set

Directories

Path Synopsis
IMPORTANT! This is auto generated code by https://github.com/src-d/go-kallax Please, do not touch the code below, and if you do, do it under your own risk.
IMPORTANT! This is auto generated code by https://github.com/src-d/go-kallax Please, do not touch the code below, and if you do, do it under your own risk.
Package pastebin wraps the basic functions of the Pastebin API and exposes a Go API.
Package pastebin wraps the basic functions of the Pastebin API and exposes a Go API.

Jump to

Keyboard shortcuts

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