welcomer

package module
v0.0.0-...-bdda2ce Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2026 License: AGPL-3.0 Imports: 51 Imported by: 14

Documentation

Overview

* Written in 2019 by Andrew Ayer * * To the extent possible under law, the author(s) have dedicated all * copyright and related and neighboring rights to this software to the * public domain worldwide. This software is distributed without any * warranty. * * You should have received a copy of the CC0 Public * Domain Dedication along with this software. If not, see * <https://creativecommons.org/publicdomain/zero/1.0/>.

Index

Constants

View Source
const (
	EmojiCheck   = "<:check:1196902761627914402>"
	EmojiCross   = "<:cross:1196902764048031744>"
	EmojiNeutral = "<:neutral:1196903241959620730>"

	EmojiRock = "<:rock:732274836038221855>"
)
View Source
const (
	EmbedColourInfo    = 0x2F80ED
	EmbedColourSuccess = 0x4CD787
	EmbedColourError   = 0xFC6A70
	EmbedColourWarn    = 0xFBC01B
)
View Source
const (
	CustomEventInvokeWelcomer = "WELCOMER_INVOKE_WELCOMER"
	CustomEventInvokeLeaver   = "WELCOMER_INVOKE_LEAVER"

	CustomEventInvokeTempChannels       = "WELCOMER_INVOKE_TEMPCHANNELS"
	CustomEventInvokeTempChannelsRemove = "WELCOMER_INVOKE_TEMPCHANNELS_REMOVE"

	CustomEventInvokeBorderwall           = "WELCOMER_INVOKE_BORDERWALL"
	CustomEventInvokeBorderwallCompletion = "WELCOMER_INVOKE_BORDERWALL_COMPLETION"
)
View Source
const (
	IPIntelFlagDefaultLookup               IPIntelFlags = ""
	IPIntelFlagDynamicBanList              IPIntelFlags = "m"
	IPIntelFlagDynamicBanListDynamicChecks IPIntelFlags = "b"
	IPIntelFlagForceFullLookup             IPIntelFlags = "f"

	IPIntelOFlagOnlyBadIP   IPIntelOFlags = "b"
	IPIntelOFlagShowCountry IPIntelOFlags = "c"
	IPIntelOFlagShowVPN     IPIntelOFlags = "i"
	IPIntelOFlgagShowASN    IPIntelOFlags = "a"
)
View Source
const (
	PatreonBase = "https://www.patreon.com/api/oauth2/v2/"
	CampaignID  = "1150593"
)
View Source
const (
	MaxRuleCount  = 25
	MaxRuleLength = 250
)
View Source
const (
	IPIntelEndpoint = "https://check.getipintel.net/check.php"
)
View Source
const (
	RecaptchaEndpoint = "https://www.google.com/recaptcha/api/siteverify"
)
View Source
const (
	UserAgent = "WelcomerService (https://github.com/WelcomerTeam/Welcomer)"
)

Variables

View Source
var (
	EmojiMessageBadge = discord.Emoji{ID: 987044175943970867, Name: "messagebadge"}
	EmojiShieldAlert  = discord.Emoji{ID: 987044177160331322, Name: "shieldalert"}
	EmojiCheckMark    = discord.Emoji{ID: 586907765662941185, Name: "checkboxmarkedoutline"}

	SupportInvite = "https://discord.gg/kQJz33ExK2"
	WebsiteURL    = "https://" + os.Getenv("DOMAIN") // https://welcomer.gg
)
View Source
var (
	ErrInvalidColour = errors.New("colour format is not recognised")

	ErrMissingGuild           = errors.New("missing guild")
	ErrMissingChannel         = errors.New("missing channel")
	ErrMissingUser            = errors.New("missing user")
	ErrMissingApplicationUser = errors.New("missing application user")

	ErrInvalidURL = errors.New("invalid url")

	ErrInvalidTempChannel = errors.New("channel is not a temporary channel")
)
View Source
var (
	CustomBackgroundPrefix = "custom:"
	SolidColourPrefix      = "solid:"
	SolidColourPrefixBased = "profile"
	UnsplashPrefix         = "unsplash:"
	StripesPrefix          = "stripes:"

	RGBAPrefix = "rgba"
	RGBPrefix  = "rgb"

	RGBRegex  = regexp.MustCompile(`^rgb\(([0-9]+)(\w+)?, ([0-9]+)(\w+)?, ([0-9]+)(\w+)?\)$`)
	RGBARegex = regexp.MustCompile(`^rgba\(([0-9]+)(\w+)?, ([0-9]+)(\w+)?, ([0-9].+)(\w+)?\)$`)
)
View Source
var (
	ErrInvalidNoInput                = errors.New("invalid no input")
	ErrInvalidIPAddress              = errors.New("invalid ip address")
	ErrUnroutableAddress             = errors.New("unroutable address / private address")
	ErrUnableToReachDatabase         = errors.New("unable to reach database")
	ErrIPBannedOrNoPermission        = errors.New("your connecting ip has been banned from the system or you do not have permission to access a particular service")
	ErrNoContactInfoOrInvalidContact = errors.New("you did not provide any contact information with your query or the contact information is invalid")
)
View Source
var (
	ErrMembershipAlreadyInUse = errors.New("membership is already in use")
	ErrMembershipInvalid      = errors.New("membership is invalid")
	ErrMembershipExpired      = errors.New("membership has expired")
	ErrMembershipNotInUse     = errors.New("membership is not in use")
	ErrUnhandledMembership    = errors.New("membership type is not handled")
	ErrTransactionNotComplete = errors.New("transaction not completed")

	ErrMissingPaypalTransaction = errors.New("missing paypal subscription transaction")
	ErrMissingPaypalUser        = errors.New("missing user for paypal subscription transaction")
)
View Source
var (
	WelcomerProDiscordSKU               = discord.Snowflake(TryParseInt(os.Getenv("WELCOMER_PRO_DISCORD_SKU_ID")))
	WelcomerCustomBackgroundsDiscordSKU = discord.Snowflake(TryParseInt(os.Getenv("WELCOMER_CUSTOM_BACKGROUNDS_DISCORD_SKU_ID")))
)
View Source
var (
	True  = true
	False = false
)
View Source
var CountryMapping = map[string]Currency{
	"IN": CurrencyINR,
}
View Source
var DefaultAutoroles database.GuildSettingsAutoroles = database.GuildSettingsAutoroles{
	ToggleEnabled: false,
	Roles:         []int64{},
}
View Source
var DefaultBorderwall database.GuildSettingsBorderwall = database.GuildSettingsBorderwall{
	ToggleEnabled: false,
	ToggleSendDm:  true,
	Channel:       0,
	MessageVerify: MustConvertToJSONB(discord.MessageParams{
		Embeds: []discord.Embed{
			{
				Description: "This server is protected by Borderwall. Please verify at {{Borderwall.Link}}.",
				Color:       EmbedColourInfo,
			},
		},
	}),
	MessageVerified: MustConvertToJSONB(discord.MessageParams{
		Embeds: []discord.Embed{
			{
				Description: "Thank you for verifying! You now have access to the server.",
				Color:       EmbedColourSuccess,
			},
		},
	}),
	RolesOnJoin:   []int64{},
	RolesOnVerify: []int64{},
}
View Source
var DefaultFreeRoles database.GuildSettingsFreeroles = database.GuildSettingsFreeroles{
	ToggleEnabled: false,
	Roles:         []int64{},
}
View Source
var DefaultGuild database.Guilds = database.Guilds{
	EmbedColour:      EmbedColourInfo,
	SiteSplashUrl:    "",
	SiteStaffVisible: false,
	SiteGuildVisible: false,
	SiteAllowInvites: false,
}
View Source
var DefaultLeaver database.GuildSettingsLeaver = database.GuildSettingsLeaver{
	ToggleEnabled: false,
	Channel:       0,
	MessageFormat: MustConvertToJSONB(discord.MessageParams{
		Content: "{{User.Name}} has left the server. We now have {{Guild.Members}} members.",
	}),
	AutoDeleteLeaverMessages: false,
	LeaverMessageLifetime:    0,
}
View Source
var DefaultManagerName string
View Source
var DefaultRules database.GuildSettingsRules = database.GuildSettingsRules{
	ToggleEnabled:    false,
	ToggleDmsEnabled: true,
	Rules:            []string{},
}
View Source
var DefaultTempChannels database.GuildSettingsTempchannels = database.GuildSettingsTempchannels{
	ToggleEnabled:    false,
	ToggleAutopurge:  true,
	ChannelLobby:     0,
	ChannelCategory:  0,
	DefaultUserCount: 0,
}
View Source
var DefaultTimeRoles database.GuildSettingsTimeroles = database.GuildSettingsTimeroles{
	ToggleEnabled: false,
	Timeroles:     pgtype.JSONB{Status: pgtype.Null},
}
View Source
var DefaultWelcomer database.GuildSettingsWelcomer = database.GuildSettingsWelcomer{
	AutoDeleteWelcomeMessages:        false,
	WelcomeMessageLifetime:           0,
	AutoDeleteWelcomeMessagesOnLeave: false,
}
View Source
var DefaultWelcomerDms database.GuildSettingsWelcomerDms = database.GuildSettingsWelcomerDms{
	ToggleEnabled:       false,
	ToggleUseTextFormat: true,
	ToggleIncludeImage:  true,
	MessageFormat: MustConvertToJSONB(discord.MessageParams{
		Content: "Welcome {{User.Mention}} to **{{Guild.Name}}**! You are the {{Ordinal(Guild.Members)}} member!",
	}),
}
View Source
var DefaultWelcomerImages database.GuildSettingsWelcomerImages = database.GuildSettingsWelcomerImages{
	ToggleEnabled:          false,
	ToggleImageBorder:      true,
	ToggleShowAvatar:       true,
	BackgroundName:         "solid:profile",
	ColourText:             "#FFFFFF",
	ColourTextBorder:       "#000000",
	ColourImageBorder:      "#FFFFFF",
	ColourProfileBorder:    "#FFFFFF",
	ImageAlignment:         int32(ImageAlignmentLeft),
	ImageTheme:             int32(ImageThemeDefault),
	ImageMessage:           "Welcome {{User.Name}}\nto {{Guild.Name}}you are the {{Ordinal(Guild.Members)}} member!",
	ImageProfileBorderType: int32(ImageProfileBorderTypeCircular),
	UseCustomBuilder:       false,
	CustomBuilderData: pgtype.JSONB{
		Status: pgtype.Present,
		Bytes:  []byte("{}"),
	},
}
View Source
var DefaultWelcomerText database.GuildSettingsWelcomerText = database.GuildSettingsWelcomerText{
	ToggleEnabled: false,
	Channel:       0,
	MessageFormat: MustConvertToJSONB(discord.MessageParams{
		Content: "Welcome {{User.Mention}} to **{{Guild.Name}}**! You are the {{Ordinal(Guild.Members)}} member!",
	}),
}
View Source
var DiscordPaymentsWebhookURL = os.Getenv("DISCORD_PAYMENTS_WEBHOOK_URL")
View Source
var ElevatedUsers []discord.Snowflake
View Source
var ErrInvalidBackgroundType = errors.New("not a valid BackgroundType")
View Source
var ErrInvalidGuildFeature = errors.New("not a valid GuildFeature")
View Source
var ErrInvalidImageAlignment = errors.New("not a valid ImageAlignment")
View Source
var ErrInvalidImageFileType = errors.New("not a valid ImageFileType")
View Source
var ErrInvalidImageProfileBorderType = errors.New("not a valid ImageProfileBorderType")
View Source
var ErrInvalidImageTheme = errors.New("not a valid ImageTheme")
View Source
var GRPCConnection *grpc.ClientConn
View Source
var OptinGuildFeatures = map[GuildFeature]bool{
	GuildFeatureCustomWelcomerImageBuilder: true,
}
View Source
var RESTInterface discord.RESTInterface
View Source
var SKUPricingTable = map[int]map[SKUName]PricingSKU{
	0: {
		SKUCustomBackgrounds: {
			ID:             SKUCustomBackgrounds,
			Name:           "Custom Backgrounds",
			Description:    "One-time purchase to unlock custom welcome backgrounds for your server.",
			MembershipType: database.MembershipTypeCustomBackgrounds,
			SoftDescriptor: "Backgrounds",
			MonthCount:     -1,
			Costs: map[Currency]string{
				CurrencyEUR: "12.00",
				CurrencyGBP: "10.00",
				CurrencyUSD: "12.00",
				CurrencyINR: "300",
			},
		},
		SKUWelcomerPro: {
			ID:             SKUWelcomerPro,
			Name:           "Welcomer Pro",
			Description:    "Unlock all Welcomer Pro features for your server.",
			MembershipType: database.MembershipTypeWelcomerPro,
			SoftDescriptor: "Pro",
			MonthCount:     1,
			Costs: map[Currency]string{
				CurrencyEUR: "8.00",
				CurrencyGBP: "7.00",
				CurrencyUSD: "8.00",
				CurrencyINR: "300",
			},
			IsRecurring: os.Getenv("WELCOMER_PRO_RECURRING") == "true",
			PaypalSubscriptionID: map[Currency]string{
				CurrencyEUR: os.Getenv("WELCOMER_PRO_PAYPAL_SUBSCRIPTION_EUR_ID"),
				CurrencyGBP: os.Getenv("WELCOMER_PRO_PAYPAL_SUBSCRIPTION_GBP_ID"),
				CurrencyUSD: os.Getenv("WELCOMER_PRO_PAYPAL_SUBSCRIPTION_USD_ID"),
			},
		},
		SKUWelcomerProBiAnnual: {
			ID:             SKUWelcomerProBiAnnual,
			Name:           "Welcomer Pro",
			Description:    "Unlock all Welcomer Pro features for your server.",
			MembershipType: database.MembershipTypeWelcomerPro,
			SoftDescriptor: "Pro",
			MonthCount:     6,
			Costs: map[Currency]string{
				CurrencyEUR: "40.00",
				CurrencyGBP: "35.00",
				CurrencyUSD: "40.00",
				CurrencyINR: "1500",
			},
		},
		SKUWelcomerProAnnual: {
			ID:             SKUWelcomerProAnnual,
			Name:           "Welcomer Pro",
			Description:    "Unlock all Welcomer Pro features for your server.",
			MembershipType: database.MembershipTypeWelcomerPro,
			SoftDescriptor: "Pro",
			MonthCount:     12,
			Costs: map[Currency]string{
				CurrencyEUR: "80.00",
				CurrencyGBP: "70.00",
				CurrencyUSD: "80.00",
				CurrencyINR: "3000",
			},
		},
	},

	1: {
		SKUCustomBackgrounds: {
			ID:             SKUCustomBackgrounds,
			Name:           "Custom Backgrounds",
			Description:    "One-time purchase to unlock custom welcome backgrounds for your server.",
			MembershipType: database.MembershipTypeCustomBackgrounds,
			SoftDescriptor: "Backgrounds",
			MonthCount:     -1,
			Costs: map[Currency]string{
				CurrencyEUR: "9.00",
				CurrencyGBP: "7.50",
				CurrencyUSD: "9.00",
				CurrencyINR: "225",
			},
		},
		SKUWelcomerPro: {
			ID:             SKUWelcomerPro,
			Name:           "Welcomer Pro",
			Description:    "Unlock all Welcomer Pro features for your server.",
			MembershipType: database.MembershipTypeWelcomerPro,
			SoftDescriptor: "Pro",
			MonthCount:     1,
			Costs: map[Currency]string{
				CurrencyEUR: "6.00",
				CurrencyGBP: "5.25",
				CurrencyUSD: "6.00",
				CurrencyINR: "250",
			},
		},
		SKUWelcomerProBiAnnual: {
			ID:             SKUWelcomerProBiAnnual,
			Name:           "Welcomer Pro",
			Description:    "Unlock all Welcomer Pro features for your server.",
			MembershipType: database.MembershipTypeWelcomerPro,
			SoftDescriptor: "Pro",
			MonthCount:     6,
			Costs: map[Currency]string{
				CurrencyEUR: "30.00",
				CurrencyGBP: "26.25",
				CurrencyUSD: "30.00",
				CurrencyINR: "1125",
			},
		},
		SKUWelcomerProAnnual: {
			ID:             SKUWelcomerProAnnual,
			Name:           "Welcomer Pro",
			Description:    "Unlock all Welcomer Pro features for your server.",
			MembershipType: database.MembershipTypeWelcomerPro,
			SoftDescriptor: "Pro",
			MonthCount:     12,
			Costs: map[Currency]string{
				CurrencyEUR: "60.00",
				CurrencyGBP: "52.50",
				CurrencyUSD: "80.00",
				CurrencyINR: "2250",
			},
		},
	},
}
View Source
var SandwichClient sandwich.SandwichClient
View Source
var UUIDGen = uuid.NewGen()

Functions

func Accelerator_CanAssignRole

func Accelerator_CanAssignRole(ctx context.Context, guildID discord.Snowflake, role *discord.Role) (canAssignRoles, isRoleAssignable, isRoleElevated bool, err error)

func AcquireSession

func AcquireSession(ctx context.Context, applicationIdentifier string) (*discord.Session, error)

func AddGuildFeatureWithAudit

func AddGuildFeatureWithAudit(ctx context.Context, params database.AddGuildFeatureParams, actor discord.Snowflake) error

func AddManagerNameToContext

func AddManagerNameToContext(ctx context.Context, managerName string) context.Context

func AddMembershipToServer

func AddMembershipToServer(ctx context.Context, membership database.GetUserMembershipsByUserIDRow, guildID discord.Snowflake) (newMembership database.UpdateUserMembershipParams, err error)

func AddSessionToContext

func AddSessionToContext(ctx context.Context, session *discord.Session) context.Context

func AssertLength

func AssertLength(name string, expectedLength int, arguments ...any) (err error)

func AssertMaxLength

func AssertMaxLength(name string, maximumLength int, arguments ...any) (err error)

func AssertMinLength

func AssertMinLength(name string, minimumLength int, arguments ...any) (err error)

func Atoi

func Atoi(s string) (int64, error)

func AuditChange

func AuditChange(ctx context.Context, guildID, userID discord.Snowflake, oldValue, newValue interface{}, auditType database.AuditType)

func BytesToJSONB

func BytesToJSONB(value []byte) pgtype.JSONB

func CanAssignRole

func CanAssignRole(role *discord.Role, guildRoles []*discord.Role, guildMembers []*discord.GuildMember) (isAssignable, isElevated bool)

func CheckChannelGuild

func CheckChannelGuild(ctx context.Context, c sandwich_protobuf.SandwichClient, guildID, channelID discord.Snowflake) (bool, error)

func Coalesce

func Coalesce(values ...string) string

func CompareStrings

func CompareStrings(query string, targets ...string) bool

func CompareStructsAsJSON

func CompareStructsAsJSON[T comparable](oldStruct, newStruct T) ([]byte, bool, error)

func ConvertToRGBA

func ConvertToRGBA(int32Color int64) color.RGBA

func CreateGuildWithAudit

func CreateGuildWithAudit(ctx context.Context, params database.CreateGuildParams, actor discord.Snowflake) (*database.Guilds, error)

CreateGuildWithAudit wraps CreateGuild and audits the creation of a guild row.

func CreateMembershipForUser

func CreateMembershipForUser(ctx context.Context, userID discord.Snowflake, transactionUUID uuid.UUID, membershipType database.MembershipType, expiresAt time.Time, guildID *discord.Snowflake) error

func CreateOrUpdateAutoRolesGuildSettingsWithAudit

func CreateOrUpdateAutoRolesGuildSettingsWithAudit(ctx context.Context, params database.CreateOrUpdateAutoRolesGuildSettingsParams, actor discord.Snowflake) (*database.GuildSettingsAutoroles, error)

Generic wrappers for guild settings create/update operations.

func CreateOrUpdateUserWithAudit

func CreateOrUpdateUserWithAudit(ctx context.Context, params database.CreateOrUpdateUserParams, actor discord.Snowflake) (*database.Users, error)

CreateOrUpdateUserWithAudit wraps Queries.CreateOrUpdateUser and logs an audit entry when changes are detected. It will attempt to fetch the existing user row (if any), call AuditChange comparing old and new, then perform the DB operation and return the resulting row.

func CreateTransactionForUser

func CreateTransactionForUser(ctx context.Context, userID discord.Snowflake, platformType database.PlatformType, transactionStatus database.TransactionStatus, transactionID, currencyCode, amount string) (*database.UserTransactions, error)

func CreateUserWithAudit

func CreateUserWithAudit(ctx context.Context, params database.CreateUserParams, actor discord.Snowflake) (*database.Users, error)

func CreateWelcomerImagesWithAudit

func CreateWelcomerImagesWithAudit(ctx context.Context, params database.CreateWelcomerImagesParams, actor discord.Snowflake) (*database.WelcomerImages, error)

Simple create wrappers for non-guild-specific objects.

func DecryptBotToken

func DecryptBotToken(encryptedToken string, botID uuid.UUID) (string, error)

func EncryptBotToken

func EncryptBotToken(token string, botID uuid.UUID) (string, error)

func EnsureGuild

func EnsureGuild(ctx context.Context, guildID discord.Snowflake) error

EnsureGuild will create or update a guild entry. This requires RequireMutualGuild to be called.

func EscapeStringForJSON

func EscapeStringForJSON(value string) string

EscapeStringForJSON escapes a string for JSON.

func FetchGuild

func FetchGuild(ctx context.Context, guildID discord.Snowflake) (*discord.Guild, error)

func FetchGuildChannels

func FetchGuildChannels(ctx context.Context, guildID discord.Snowflake) ([]*discord.Channel, error)

func FetchGuildName

func FetchGuildName(ctx context.Context, guildID discord.Snowflake) string

func FetchUser

func FetchUser(ctx context.Context, userID discord.Snowflake) (*discord.User, error)

func FilterAssignableRoles

func FilterAssignableRoles(ctx context.Context, sandwichClient pb.SandwichClient, guildID, applicationID int64, roleIDs []int64) (out []discord.Role, err error)

func FilterAssignableRolesAsSnowflakes

func FilterAssignableRolesAsSnowflakes(ctx context.Context, sandwichClient pb.SandwichClient, guildID, applicationID int64, roleIDs []int64) (out []discord.Snowflake, err error)

func FormatNumber

func FormatNumber(value int64, locale database.NumberLocale) string

func FormatString

func FormatString(funcs map[string]govaluate.ExpressionFunction, vars map[string]any, message string) (string, error)

func FormatTextStroke

func FormatTextStroke(v bool) int

func Ftoa

func Ftoa(v float64) string

func GatherFunctions

func GatherFunctions(numberLocale database.NumberLocale) (funcs map[string]govaluate.ExpressionFunction)

func GatherVariables

func GatherVariables(eventCtx *sandwich.EventContext, member *discord.GuildMember, guild GuildVariables, invite *discord.Invite, extraValues map[string]any) (vars map[string]any)

func GetConfigurationGatherer

func GetConfigurationGatherer(ctx context.Context) sandwich_daemon.ConfigProvider

func GetCustomBotConfiguration

func GetCustomBotConfiguration(customBotUUID uuid.UUID, botToken string, autoStart bool, guildID discord.Snowflake) sandwich_daemon.ApplicationConfiguration

func GetCustomBotEnvironmentType

func GetCustomBotEnvironmentType() string

func GetCustomBotKey

func GetCustomBotKey(v uuid.UUID) string

func GetGuildCustomBotLimit

func GetGuildCustomBotLimit(ctx context.Context, guildID discord.Snowflake) int

func GetGuildMemberDisplayName

func GetGuildMemberDisplayName(member *discord.GuildMember) string

func GetHighestRoleForGuildMember

func GetHighestRoleForGuildMember(roleMap map[discord.Snowflake]AssignableRole, guildMember *discord.GuildMember) int32

func GetManagerNameFromContext

func GetManagerNameFromContext(ctx context.Context) string

func GetOnboardingMessage

func GetOnboardingMessage(guildID discord.Snowflake) discord.MessageParams

func GetRolePermissionList

func GetRolePermissionList(permissions int) []string

func GetRolePermissionListAsString

func GetRolePermissionListAsString(permissions int) string

func GetSessionFromContext

func GetSessionFromContext(ctx context.Context) (*discord.Session, bool)

func GetUserAvatar

func GetUserAvatar(user *discord.User) string

func GetUserDisplayName

func GetUserDisplayName(user *discord.User) string

func GetWelcomerPresence

func GetWelcomerPresence(ctx context.Context, guildID discord.Snowflake) (guildMembers []*discord.GuildMember, err error)

func GuildMemberCanAssignRoles

func GuildMemberCanAssignRoles(guildMember *discord.GuildMember) bool

func HandleDiscordEntitlement

func HandleDiscordEntitlement(ctx context.Context, entitlement discord.Entitlement) error

func HandlePaypalSale

func HandlePaypalSale(ctx context.Context, paypalSale PaypalSale) error

Handles all paypal sales.

func HandlePaypalSubscription

func HandlePaypalSubscription(ctx context.Context, action string, paypalSubscription paypal.Subscription) error

Handles all subscription events.

func HumanizeDuration

func HumanizeDuration(seconds int, includeSeconds bool) string

func If

func If[T any](condition bool, trueValue, falseValue T) T

func IfFunc

func IfFunc[T any](condition bool, trueFunc, falseFunc func() T) T

func IncludeBorderwallVerifyButton

func IncludeBorderwallVerifyButton(messageParams discord.MessageParams, borderwallLink string) discord.MessageParams

func IncludeScamsButton

func IncludeScamsButton(messageParams discord.MessageParams) discord.MessageParams

func IncludeSentByButton

func IncludeSentByButton(messageParams discord.MessageParams, guildName string) discord.MessageParams

func Int64SliceToString

func Int64SliceToString(values []int64) []string

func Int64ToStringPointer

func Int64ToStringPointer(value int64) *string

func IsCustomBackgroundsMembership

func IsCustomBackgroundsMembership(membershipType database.MembershipType) bool

func IsInterationAuthorElevated

func IsInterationAuthorElevated(sub *subway.Subway, interaction discord.Interaction) bool

func IsJSONBEmpty

func IsJSONBEmpty(b []byte) bool

IsJSONBEmpty checks if a byte slice is empty or is a JSON empty object.

func IsMessageParamsEmpty

func IsMessageParamsEmpty(m discord.MessageParams) bool

IsMessageParamsEmpty checks if the given message parameters are empty. It returns true if the content and all the fields in the embeds are empty, otherwise it returns false.

func IsPublicIPAddress

func IsPublicIPAddress(address net.IP) bool

func IsValidBackground

func IsValidBackground(s string) bool

func IsValidColour

func IsValidColour(str string) bool

func IsValidDiscordToken

func IsValidDiscordToken(token string) bool

func IsValidEmbed

func IsValidEmbed(s string) error

func IsValidHex

func IsValidHex(str string, allowAlpha bool) bool

func IsValidHostname

func IsValidHostname(host string) bool

func IsValidImageAlignment

func IsValidImageAlignment(value string) bool

func IsValidImageProfileBorderType

func IsValidImageProfileBorderType(value string) bool

func IsValidImageTheme

func IsValidImageTheme(value string) bool

func IsValidInteger

func IsValidInteger(str string) bool

func IsValidPublicKey

func IsValidPublicKey(publicKey string) bool

func IsValidURL

func IsValidURL(url string) (*url.URL, bool)

Validates a URL and prevents SSRF.

func IsValidURLWithFormatting

func IsValidURLWithFormatting(url string) (*url.URL, bool)

func IsValidUnsplashID

func IsValidUnsplashID(str string) bool

func IsWelcomerProMembership

func IsWelcomerProMembership(membershipType database.MembershipType) bool

func Itoa

func Itoa(v int64) string

func JSONBToBytes

func JSONBToBytes(value pgtype.JSONB) []byte

func JSONBToString

func JSONBToString(value pgtype.JSONB) string

func LoadRSAKey

func LoadRSAKey(keyType KeyType) (interface{}, error)

LoadRSAKey loads an RSA public or private key from a file specified in environment variable

func MarshalTimeRolesJSON

func MarshalTimeRolesJSON(roles []GuildSettingsTimeRolesRole) (rolesJSON []byte)

func MemberHasElevation

func MemberHasElevation(discordGuild *discord.Guild, member *discord.GuildMember) bool

func MustConvertToJSONB

func MustConvertToJSONB(v any) pgtype.JSONB

func NewEmbed

func NewEmbed(message string, color int32) []discord.Embed

func NewTwilightProxy

func NewTwilightProxy(u string) discord.RESTInterface

func NotifyMembershipCreated

func NotifyMembershipCreated(ctx context.Context, session *discord.Session, membership database.UserMemberships) error

func NotifyMembershipExpired

func NotifyMembershipExpired(ctx context.Context, session *discord.Session, membership database.UserMemberships) error

func OnDiscordEntitlementCreated

func OnDiscordEntitlementCreated(ctx context.Context, entitlement discord.Entitlement) error

func OnDiscordEntitlementDeleted

func OnDiscordEntitlementDeleted(ctx context.Context, entitlement discord.Entitlement) error

func OnDiscordEntitlementUpdated

func OnDiscordEntitlementUpdated(ctx context.Context, entitlement discord.Entitlement) error

func OnMembershipExpired

func OnMembershipExpired(ctx context.Context, membership database.GetUserMembershipsByUserIDRow) error

Triggers when a membership has expired and not renewed.

func OnPatreonActive

func OnPatreonActive(ctx context.Context, patreonUser database.PatreonUsers, patreonMember PatreonMember) error

Triggered when a patron is still pledging.

func OnPatreonLinked

func OnPatreonLinked(ctx context.Context, patreonUser PatreonUser, automatic bool) error

Triggers when a patreon account has been linked.

func OnPatreonNoLongerPledging

func OnPatreonNoLongerPledging(ctx context.Context, patreonUser database.PatreonUsers, patreonMember PatreonMember) error

Triggers when a patron is no longer pledging

func OnPatreonTierChanged

func OnPatreonTierChanged(ctx context.Context, beforePatreonUser *database.PatreonUsers, patreonUser database.CreateOrUpdatePatreonUserParams) error

Triggers when a patreon tier has changed.

func OnPatreonTierChanged_Fallback

func OnPatreonTierChanged_Fallback(ctx context.Context, beforePatreonUser *database.PatreonUsers, patreonUser database.CreateOrUpdatePatreonUserParams, e error) error

Triggers when a patreon tier has changed. Ran if OnPatreonTierChange failed to run.

func OnPatreonUnlinked

func OnPatreonUnlinked(ctx context.Context, patreonUser *database.PatreonUsers) error

Triggers when a patreon account has been unlinked.

func OnPaypalSubscriptionActivated

func OnPaypalSubscriptionActivated(ctx context.Context, paypalSubscription paypal.Subscription) error

Triggers when a subscription has been activated.

func OnPaypalSubscriptionCancelled

func OnPaypalSubscriptionCancelled(ctx context.Context, paypalSubscription paypal.Subscription) error

Triggers when a subscription has been cancelled.

func OnPaypalSubscriptionCreated

func OnPaypalSubscriptionCreated(ctx context.Context, paypalSubscription paypal.Subscription) error

Triggers when a subscription is created.

func OnPaypalSubscriptionExpired

func OnPaypalSubscriptionExpired(ctx context.Context, paypalSubscription paypal.Subscription) error

Triggers when a subscription has expired.

func OnPaypalSubscriptionPaymentFailed

func OnPaypalSubscriptionPaymentFailed(ctx context.Context, paypalSubscription paypal.Subscription) error

Triggers when a subscription payment has failed.

func OnPaypalSubscriptionReactivated

func OnPaypalSubscriptionReactivated(ctx context.Context, paypalSubscription paypal.Subscription) error

Triggers when a subscription has been re-activated.

func OnPaypalSubscriptionSuspended

func OnPaypalSubscriptionSuspended(ctx context.Context, paypalSubscription paypal.Subscription) error

Triggers when a subscription has been suspended.

func OnPaypalSubscriptionUpdated

func OnPaypalSubscriptionUpdated(ctx context.Context, paypalSubscription paypal.Subscription) error

Triggers when a subscription has been updated.

func Overflow

func Overflow(s string, length int) string

func ParseColour

func ParseColour(str, defaultValue string) (*color.RGBA, error)

ParseColour parses a colour and returns RGBA. Expected formats: #FFAAAA #FFAAAAFF RGBA(255, 255, 255, 0.1) RGB(255, 255, 255)

func ParseDurationAsSeconds

func ParseDurationAsSeconds(input string) (int, error)

func RandStringBytesRmndr

func RandStringBytesRmndr(n int) string

func RemoveGuildFeatureWithAudit

func RemoveGuildFeatureWithAudit(ctx context.Context, params database.RemoveGuildFeatureParams, actor discord.Snowflake) error

func RemoveMembershipFromServer

func RemoveMembershipFromServer(ctx context.Context, membership database.GetUserMembershipsByUserIDRow) (newMembership database.UpdateUserMembershipParams, err error)

func RequireGuild

func RequireGuild(interaction discord.Interaction, handler BasicInteractionHandler) (*discord.InteractionResponse, error)

func RequireGuildElevation

func RequireGuildElevation(sub *subway.Subway, interaction discord.Interaction, handler BasicInteractionHandler) (*discord.InteractionResponse, error)

func RetryWithFallback

func RetryWithFallback(function, fallbackFunction func() error, predictate func(error) bool) (err error)

RetryWithFallback will attempt to run a function. If the function fails, it will run a fallback function. predictate is a function that will determine if the error is retryable and is optional. When the fallback function succeeds, the original function will be called again.

func SendWebhookMessage

func SendWebhookMessage(ctx context.Context, webhookURL string, message discord.WebhookMessageParams) error

func SetupDatabase

func SetupDatabase(ctx context.Context, connectionString string)

func SetupDedupeProvider

func SetupDedupeProvider(provider RedisDedupeProvider)

func SetupDefaultManagerName

func SetupDefaultManagerName(name string)

func SetupGRPCConnection

func SetupGRPCConnection(host string, opts ...grpc.DialOption)

func SetupJSONB

func SetupJSONB(jsonb pgtype.JSONB) pgtype.JSONB

func SetupLogger

func SetupLogger(loggingLevel string) io.Writer

func SetupPushGuildScience

func SetupPushGuildScience(limit int) func(ctx context.Context, interval time.Duration)

func SetupRESTInterface

func SetupRESTInterface(restInterface discord.RESTInterface)

func SetupSandwichClient

func SetupSandwichClient()

func SliceContains

func SliceContains[T comparable](slice []T, value T) bool

func StartCustomBot

func StartCustomBot(ctx context.Context, customBotUUID uuid.UUID, botToken string, guildID discord.Snowflake, blocking bool) error

func StopCustomBot

func StopCustomBot(ctx context.Context, customBotUUID uuid.UUID, blocking bool) error

func StringPointerToInt64

func StringPointerToInt64(value *string) int64

func StringSliceToInt64

func StringSliceToInt64(value []string) []int64

func StringToJSONB

func StringToJSONB(value string) pgtype.JSONB

func StringToJsonLiteral

func StringToJsonLiteral(s string) json.RawMessage

StringToJsonLiteral converts a string to a json.RawMessage.

func ToPointer

func ToPointer[K any](k K) *K

func TruncateUTF8

func TruncateUTF8(s string, length int) string

func TryGetURLFromContext

func TryGetURLFromContext(ctx context.Context) url.URL

func TryParseBool

func TryParseBool(str string) bool

func TryParseFloat

func TryParseFloat(str string) float64

func TryParseInt

func TryParseInt(str string) int64

func TryParseTime

func TryParseTime(str string) time.Time

func UpdateCustomBotWithAudit

func UpdateCustomBotWithAudit(ctx context.Context, params database.UpdateCustomBotParams, actor, guildID discord.Snowflake) (*database.CustomBots, error)

func UpdateGuildWithAudit

func UpdateGuildWithAudit(ctx context.Context, params database.UpdateGuildParams, actor discord.Snowflake) (*database.Guilds, error)

func ValidateRecaptcha

func ValidateRecaptcha(response, ipAddress string) (float64, error)

Types

type ApplicationValues

type ApplicationValues struct {
	IsCustomBot bool              `json:"custom_bot"`
	BotUUID     uuid.UUID         `json:"bot_uuid"`
	GuildID     discord.Snowflake `json:"guild_id"`
}

type AssignableRole

type AssignableRole struct {
	*discord.Role

	IsAssignable bool `json:"is_assignable"`
	IsElevated   bool `json:"is_elevated"`
}

func CalculateRoleValues

func CalculateRoleValues(roles []*discord.Role, guildMembers []*discord.GuildMember) (convertedRoles []*AssignableRole)

type Attributes

type Attributes struct {
	CurrentlyEntitledAmountCents int64                   `json:"currently_entitled_amount_cents"`
	Email                        string                  `json:"email"`
	FullName                     string                  `json:"full_name"`
	ThumbUrl                     string                  `json:"thumb_url"`
	IsFollower                   bool                    `json:"is_follower"`
	LastChargeDate               time.Time               `json:"last_charge_date"`
	LastChargeStatus             LastChargeStatus        `json:"last_charge_status"`
	LifetimeSupportCents         int64                   `json:"lifetime_support_cents"`
	PatronStatus                 PatronStatus            `json:"patron_status"`
	SocialConnections            PatronSocialConnections `json:"social_connections"`
}

type Background

type Background struct {
	Value string         `json:"value"`
	Type  BackgroundType `json:"type"`
}

func ParseBackground

func ParseBackground(str string) (Background, bool)

ParseBackground parses a background string provided by user. Expected formats: solid:FFAAAA - Solid colour with HEX code. solid:profile - Solid colour based on user profile picture. unsplash:Bnr_ZSmqbDY - Unsplash along with Id. custom:018c186a-4ce5-74c7-b2d1-b0639c2f4686 - per-guild background

type BackgroundType

type BackgroundType int32

ENUM(default, welcomer, solid, solidProfile, unsplash, url, stripes)

const (
	// BackgroundTypeDefault is a BackgroundType of type Default.
	BackgroundTypeDefault BackgroundType = iota
	// BackgroundTypeWelcomer is a BackgroundType of type Welcomer.
	BackgroundTypeWelcomer
	// BackgroundTypeSolid is a BackgroundType of type Solid.
	BackgroundTypeSolid
	// BackgroundTypeSolidProfile is a BackgroundType of type SolidProfile.
	BackgroundTypeSolidProfile
	// BackgroundTypeUnsplash is a BackgroundType of type Unsplash.
	BackgroundTypeUnsplash
	// BackgroundTypeUrl is a BackgroundType of type Url.
	BackgroundTypeUrl
	// BackgroundTypeStripes is a BackgroundType of type Stripes.
	BackgroundTypeStripes
)

func ParseBackgroundType

func ParseBackgroundType(name string) (BackgroundType, error)

ParseBackgroundType attempts to convert a string to a BackgroundType.

func (*BackgroundType) AppendText

func (x *BackgroundType) AppendText(b []byte) ([]byte, error)

AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.

Implementations must not retain b, nor mutate any bytes within b[:len(b)].

func (BackgroundType) IsValid

func (x BackgroundType) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (BackgroundType) MarshalText

func (x BackgroundType) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (BackgroundType) String

func (x BackgroundType) String() string

String implements the Stringer interface.

func (*BackgroundType) UnmarshalText

func (x *BackgroundType) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type BasicIPChecker

type BasicIPChecker struct{}

func NewBasicIPChecker

func NewBasicIPChecker() *BasicIPChecker

NewBasicIPChecker creates a new basic IP checker.

func (*BasicIPChecker) CheckIP

func (c *BasicIPChecker) CheckIP(ctx context.Context, ipaddress string, flags IPIntelFlags, oflags IPIntelOFlags) (IPIntelResponse, error)

type BasicInteractionHandler

type BasicInteractionHandler func() (*discord.InteractionResponse, error)

type CompareStructResult

type CompareStructResult map[string][2]any

func CompareStructs

func CompareStructs[T comparable](oldStruct, newStruct T) (CompareStructResult, bool)

type ContextKey

type ContextKey int
const (
	ManagerNameContextKey ContextKey = iota
	SessionContextKey
)

type Currency

type Currency string
const (
	CurrencyEUR Currency = "EUR"
	CurrencyGBP Currency = "GBP"
	CurrencyINR Currency = "INR"
	CurrencyUSD Currency = "USD"
)

type CustomEventInvokeBorderwallCompletionStructure

type CustomEventInvokeBorderwallCompletionStructure struct {
	Member discord.GuildMember
}

type CustomEventInvokeBorderwallStructure

type CustomEventInvokeBorderwallStructure struct {
	Member discord.GuildMember
}

type CustomEventInvokeLeaverStructure

type CustomEventInvokeLeaverStructure struct {
	Interaction *discord.Interaction
	User        discord.User
	GuildID     discord.Snowflake
}

type CustomEventInvokeTempChannelsRemoveStructure

type CustomEventInvokeTempChannelsRemoveStructure struct {
	Interaction *discord.Interaction
	Member      discord.GuildMember
}

type CustomEventInvokeTempChannelsStructure

type CustomEventInvokeTempChannelsStructure struct {
	Interaction *discord.Interaction
	Member      discord.GuildMember
}

type CustomEventInvokeWelcomerStructure

type CustomEventInvokeWelcomerStructure struct {
	Interaction  *discord.Interaction
	Member       discord.GuildMember
	IgnoreDedupe bool
}

type CustomWelcomerImage

type CustomWelcomerImage struct {
	Fill   string                     `json:"fill"`
	Stroke *CustomWelcomerImageStroke `json:"stroke,omitempty"`

	Dimensions [2]int `json:"dimensions"`

	Layers []CustomWelcomerImageLayer `json:"layers"`
}

type CustomWelcomerImageGenerateRequest

type CustomWelcomerImageGenerateRequest struct {
	CustomWelcomerImage CustomWelcomerImage `json:"custom_welcomer_image"`

	MembersJoined int32                 `json:"members_joined"`
	NumberLocale  database.NumberLocale `json:"number_locale"`

	Guild  discord.Guild   `json:"guild"`
	User   discord.User    `json:"user"`
	Invite *discord.Invite `json:"invite,omitempty"`
}

type CustomWelcomerImageLayer

type CustomWelcomerImageLayer struct {
	Type  CustomWelcomerImageLayerType `json:"type,omitempty"`
	Value string                       `json:"value"`

	Dimensions [2]int `json:"dimensions"`
	Position   [2]int `json:"position"`

	Rotation  int  `json:"rotation"`
	InvertedX bool `json:"inverted_x"`
	InvertedY bool `json:"inverted_y"`

	// BorderRadius will either be an integer or a percentage string.
	BorderRadius [4]string `json:"border_radius"`

	Fill   string                     `json:"fill,omitempty"`
	Stroke *CustomWelcomerImageStroke `json:"stroke,omitempty"`

	Typography *CustomWelcomerImageLayerTypography `json:"typography,omitempty"`
}

type CustomWelcomerImageLayerType

type CustomWelcomerImageLayerType int
const (
	CustomWelcomerImageLayerTypeText CustomWelcomerImageLayerType = iota
	CustomWelcomerImageLayerTypeImage
	CustomWelcomerImageLayerTypeShapeRectangle
	CustomWelcomerImageLayerTypeShapeCircle
)

type CustomWelcomerImageLayerTypography

type CustomWelcomerImageLayerTypography struct {
	FontFamily          string              `json:"font_family"`
	FontWeight          string              `json:"font_weight"`
	FontSize            int                 `json:"font_size"`
	LineHeight          float64             `json:"line_height"`
	LetterSpacing       float64             `json:"letter_spacing"`
	HorizontalAlignment HorizontalAlignment `json:"horizontal_alignment"`
	VerticalAlignment   VerticalAlignment   `json:"vertical_alignment"`
}

type CustomWelcomerImageStroke

type CustomWelcomerImageStroke struct {
	Color string `json:"color"`
	Width int    `json:"width"`
}

type EnvironmentType

type EnvironmentType int
const (
	EnvironmentTypeDevelopment EnvironmentType = iota
	EnvironmentTypeProduction
	EnvironmentTypeProductionOutsideDocker
)

type GenerateImageOptionsRaw

type GenerateImageOptionsRaw struct {
	ShowAvatar         bool
	AvatarURL          string
	Background         string
	Text               string
	TextFont           string
	TextColor          int64
	UserID             int64
	ProfileBorderColor int64
	GuildID            int64
	ImageBorderColor   int64
	TextStrokeColor    int64
	Theme              int32
	TextAlign          int32
	ImageBorderWidth   int32
	ProfileFloat       int32
	ProfileBorderWidth int32
	ProfileBorderCurve int32
	TextStroke         bool
	AllowAnimated      bool
}

type GetPatreonMembersResponse

type GetPatreonMembersResponse struct {
	Data []struct {
		Attributes    Attributes    `json:"attributes"`
		Relationships Relationships `json:"relationships"`
	} `json:"data"`
	Included []struct {
		Attributes Attributes        `json:"attributes"`
		ID         discord.Snowflake `json:"id"`
		Type       string            `json:"type"`
	}
	Links struct {
		Next string `json:"next"`
	} `json:"links"`
}

type GuildFeature

type GuildFeature string

ENUM(CustomWelcomerImageBuilder)

const (
	// GuildFeatureCustomWelcomerImageBuilder is a GuildFeature of type CustomWelcomerImageBuilder.
	GuildFeatureCustomWelcomerImageBuilder GuildFeature = "CustomWelcomerImageBuilder"
)

func CheckGuildMemberships

func CheckGuildMemberships(ctx context.Context, guildID discord.Snowflake) (hasWelcomerPro, hasCustomBackgrounds bool, features []GuildFeature, err error)

func ParseGuildFeature

func ParseGuildFeature(name string) (GuildFeature, error)

ParseGuildFeature attempts to convert a string to a GuildFeature.

func (*GuildFeature) AppendText

func (x *GuildFeature) AppendText(b []byte) ([]byte, error)

AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.

Implementations must not retain b, nor mutate any bytes within b[:len(b)].

func (GuildFeature) IsValid

func (x GuildFeature) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (GuildFeature) MarshalText

func (x GuildFeature) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (GuildFeature) String

func (x GuildFeature) String() string

String implements the Stringer interface.

func (*GuildFeature) UnmarshalText

func (x *GuildFeature) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type GuildScienceBorderwallChallenge

type GuildScienceBorderwallChallenge struct {
	HasMessage bool `json:"has_message,omitempty"`
	HasDM      bool `json:"has_dm,omitempty"`
}

type GuildScienceBorderwallCompleted

type GuildScienceBorderwallCompleted struct {
	HasMessage bool `json:"has_message,omitempty"`
	HasDM      bool `json:"has_dm,omitempty"`
}

type GuildScienceLeaverMessageRemoved

type GuildScienceLeaverMessageRemoved struct {
	HasMessage       bool              `json:"has_message,omitempty"`
	Successful       bool              `json:"successful,omitempty"`
	MessageID        discord.Snowflake `json:"message_id,omitempty"`
	MessageChannelID discord.Snowflake `json:"channel_id,omitempty"`
}

type GuildScienceMembershipReceived

type GuildScienceMembershipReceived struct {
	MembershipUUID uuid.UUID `json:"membership_uuid"`
}

type GuildScienceMembershipRemoved

type GuildScienceMembershipRemoved struct {
	MembershipUUID uuid.UUID `json:"membership_uuid"`
}

type GuildScienceTimeRoleGiven

type GuildScienceTimeRoleGiven struct {
	RoleID discord.Snowflake `json:"role_id"`
}

type GuildScienceUserJoined

type GuildScienceUserJoined struct {
	HasInviteTracking bool   `json:"has_invite_tracking,omitempty"`
	IsInviteTracked   bool   `json:"is_invite_tracked,omitempty"`
	InviteCode        string `json:"invite_code,omitempty"`
	MemberCount       int32  `json:"member_count,omitempty"`
	IsPending         bool   `json:"is_pending,omitempty"`
}

type GuildScienceUserLeftMessage

type GuildScienceUserLeftMessage struct {
	HasMessage       bool              `json:"has_message,omitempty"`
	MessageID        discord.Snowflake `json:"message_id,omitempty"`
	MessageChannelID discord.Snowflake `json:"channel_id,omitempty"`
}

type GuildScienceUserWelcomed

type GuildScienceUserWelcomed struct {
	HasImage bool `json:"has_image,omitempty"`

	HasMessage       bool              `json:"has_message,omitempty"`
	MessageID        discord.Snowflake `json:"message_id,omitempty"`
	MessageChannelID discord.Snowflake `json:"channel_id,omitempty"`

	HasDM             bool   `json:"has_dm,omitempty"`
	HasInviteTracking bool   `json:"has_invite_tracking,omitempty"`
	IsInviteTracked   bool   `json:"is_invite_tracked,omitempty"`
	InviteCode        string `json:"invite_code,omitempty"`
}

type GuildScienceWelcomeMessageRemoved

type GuildScienceWelcomeMessageRemoved struct {
	HasMessage       bool              `json:"has_message,omitempty"`
	Successful       bool              `json:"successful,omitempty"`
	MessageID        discord.Snowflake `json:"message_id,omitempty"`
	MessageChannelID discord.Snowflake `json:"channel_id,omitempty"`
}

type GuildSettingsTimeRolesRole

type GuildSettingsTimeRolesRole struct {
	Role    discord.Snowflake `json:"role_id"`
	Seconds int               `json:"seconds"`
}

func FilterAssignableTimeRoles

func FilterAssignableTimeRoles(ctx context.Context, sandwichClient pb.SandwichClient, guildID, applicationID int64, timeRoles []GuildSettingsTimeRolesRole) (out []GuildSettingsTimeRolesRole, err error)

func UnmarshalTimeRolesJSON

func UnmarshalTimeRolesJSON(rolesJSON []byte) (roles []GuildSettingsTimeRolesRole)

type GuildVariables

type GuildVariables struct {
	*discord.Guild
	MembersJoined int32
	NumberLocale  database.NumberLocale
}

type HorizontalAlignment

type HorizontalAlignment string
const (
	HorizontalAlignmentLeft   HorizontalAlignment = "left"
	HorizontalAlignmentCenter HorizontalAlignment = "center"
	HorizontalAlignmentRight  HorizontalAlignment = "right"
)

type IPChecker

type IPChecker interface {
	CheckIP(ctx context.Context, ipaddress string, flags IPIntelFlags, oflags IPIntelOFlags) (response IPIntelResponse, err error)
}

type IPIntelError

type IPIntelError struct {
	Code float64 `json:"code"`
}

func (IPIntelError) Error

func (e IPIntelError) Error() string

type IPIntelFlags

type IPIntelFlags string

type IPIntelOFlags

type IPIntelOFlags string

type IPIntelResponse

type IPIntelResponse struct {
	Success      string  `json:"success"`
	ResultString string  `json:"result"`
	Result       float64 `json:"-"`
	Country      string  `json:"Country"`
}

type ImageAlignment

type ImageAlignment int32

ENUM(left, center, right, topLeft, topCenter, topRight, bottomLeft, bottomCenter, bottomRight)

const (
	// ImageAlignmentLeft is a ImageAlignment of type Left.
	ImageAlignmentLeft ImageAlignment = iota
	// ImageAlignmentCenter is a ImageAlignment of type Center.
	ImageAlignmentCenter
	// ImageAlignmentRight is a ImageAlignment of type Right.
	ImageAlignmentRight
	// ImageAlignmentTopLeft is a ImageAlignment of type TopLeft.
	ImageAlignmentTopLeft
	// ImageAlignmentTopCenter is a ImageAlignment of type TopCenter.
	ImageAlignmentTopCenter
	// ImageAlignmentTopRight is a ImageAlignment of type TopRight.
	ImageAlignmentTopRight
	// ImageAlignmentBottomLeft is a ImageAlignment of type BottomLeft.
	ImageAlignmentBottomLeft
	// ImageAlignmentBottomCenter is a ImageAlignment of type BottomCenter.
	ImageAlignmentBottomCenter
	// ImageAlignmentBottomRight is a ImageAlignment of type BottomRight.
	ImageAlignmentBottomRight
)

func ParseImageAlignment

func ParseImageAlignment(name string) (ImageAlignment, error)

ParseImageAlignment attempts to convert a string to a ImageAlignment.

func (*ImageAlignment) AppendText

func (x *ImageAlignment) AppendText(b []byte) ([]byte, error)

AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.

Implementations must not retain b, nor mutate any bytes within b[:len(b)].

func (ImageAlignment) IsValid

func (x ImageAlignment) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (ImageAlignment) MarshalText

func (x ImageAlignment) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (ImageAlignment) String

func (x ImageAlignment) String() string

String implements the Stringer interface.

func (*ImageAlignment) UnmarshalText

func (x *ImageAlignment) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type ImageFileType

type ImageFileType int32

ENUM(unknown, image/png, image/jpeg, image/gif, image/webp)

const (
	// ImageFileTypeUnknown is a ImageFileType of type Unknown.
	ImageFileTypeUnknown ImageFileType = iota
	// ImageFileTypeImagePng is a ImageFileType of type Image/Png.
	ImageFileTypeImagePng
	// ImageFileTypeImageJpeg is a ImageFileType of type Image/Jpeg.
	ImageFileTypeImageJpeg
	// ImageFileTypeImageGif is a ImageFileType of type Image/Gif.
	ImageFileTypeImageGif
	// ImageFileTypeImageWebp is a ImageFileType of type Image/Webp.
	ImageFileTypeImageWebp
)

func ParseImageFileType

func ParseImageFileType(name string) (ImageFileType, error)

ParseImageFileType attempts to convert a string to a ImageFileType.

func (*ImageFileType) AppendText

func (x *ImageFileType) AppendText(b []byte) ([]byte, error)

AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.

Implementations must not retain b, nor mutate any bytes within b[:len(b)].

func (ImageFileType) GetExtension

func (i ImageFileType) GetExtension() string

func (ImageFileType) IsValid

func (x ImageFileType) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (ImageFileType) MarshalText

func (x ImageFileType) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (ImageFileType) String

func (x ImageFileType) String() string

String implements the Stringer interface.

func (*ImageFileType) UnmarshalText

func (x *ImageFileType) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type ImageProfileBorderType

type ImageProfileBorderType int32

ENUM(circular, rounded, squared, hexagonal)

const (
	// ImageProfileBorderTypeCircular is a ImageProfileBorderType of type Circular.
	ImageProfileBorderTypeCircular ImageProfileBorderType = iota
	// ImageProfileBorderTypeRounded is a ImageProfileBorderType of type Rounded.
	ImageProfileBorderTypeRounded
	// ImageProfileBorderTypeSquared is a ImageProfileBorderType of type Squared.
	ImageProfileBorderTypeSquared
	// ImageProfileBorderTypeHexagonal is a ImageProfileBorderType of type Hexagonal.
	ImageProfileBorderTypeHexagonal
)

func ParseImageProfileBorderType

func ParseImageProfileBorderType(name string) (ImageProfileBorderType, error)

ParseImageProfileBorderType attempts to convert a string to a ImageProfileBorderType.

func (*ImageProfileBorderType) AppendText

func (x *ImageProfileBorderType) AppendText(b []byte) ([]byte, error)

AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.

Implementations must not retain b, nor mutate any bytes within b[:len(b)].

func (ImageProfileBorderType) IsValid

func (x ImageProfileBorderType) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (ImageProfileBorderType) MarshalText

func (x ImageProfileBorderType) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (ImageProfileBorderType) String

func (x ImageProfileBorderType) String() string

String implements the Stringer interface.

func (*ImageProfileBorderType) UnmarshalText

func (x *ImageProfileBorderType) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type ImageTheme

type ImageTheme int32

ENUM(default, vertical, card)

const (
	// ImageThemeDefault is a ImageTheme of type Default.
	ImageThemeDefault ImageTheme = iota
	// ImageThemeVertical is a ImageTheme of type Vertical.
	ImageThemeVertical
	// ImageThemeCard is a ImageTheme of type Card.
	ImageThemeCard
)

func ParseImageTheme

func ParseImageTheme(name string) (ImageTheme, error)

ParseImageTheme attempts to convert a string to a ImageTheme.

func (*ImageTheme) AppendText

func (x *ImageTheme) AppendText(b []byte) ([]byte, error)

AppendText appends the textual representation of itself to the end of b (allocating a larger slice if necessary) and returns the updated slice.

Implementations must not retain b, nor mutate any bytes within b[:len(b)].

func (ImageTheme) IsValid

func (x ImageTheme) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (ImageTheme) MarshalText

func (x ImageTheme) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (ImageTheme) String

func (x ImageTheme) String() string

String implements the Stringer interface.

func (*ImageTheme) UnmarshalText

func (x *ImageTheme) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

type KeyType

type KeyType string

KeyType distinguishes between loading a public or private key

const (
	PublicKey  KeyType = "PUBLIC"
	PrivateKey KeyType = "PRIVATE"
)

type LRUIPChecker

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

func NewLRUIPChecker

func NewLRUIPChecker(maxSize int) *LRUIPChecker

NewLRUIPChecker creates a new LRU IP checker with the specified maximum cache size.

func (*LRUIPChecker) CheckIP

func (c *LRUIPChecker) CheckIP(ctx context.Context, ipaddress string, flags IPIntelFlags, oflags IPIntelOFlags) (IPIntelResponse, error)

type LastChargeStatus

type LastChargeStatus string
const (
	LastChargeStatusDeclined LastChargeStatus = "Declined"
	LastChargeStatusPaid     LastChargeStatus = "Paid"
	LastChargeStatusDeleted  LastChargeStatus = "Deleted"
	LastChargeStatusPending  LastChargeStatus = "Pending"
	LastChargeStatusRefunded LastChargeStatus = "Refunded"
	LastChargeStatusFraud    LastChargeStatus = "Fraud"
	LastChargeStatusOther    LastChargeStatus = "Other"
)

type OnInvokeBorderwallCompletionFuncType

type OnInvokeBorderwallCompletionFuncType func(eventCtx *sandwich.EventContext, member CustomEventInvokeBorderwallCompletionStructure) error

type OnInvokeBorderwallFuncType

type OnInvokeBorderwallFuncType func(eventCtx *sandwich.EventContext, member CustomEventInvokeBorderwallStructure) error

type OnInvokeLeaverFuncType

type OnInvokeLeaverFuncType func(eventCtx *sandwich.EventContext, member CustomEventInvokeLeaverStructure) error

type OnInvokeTempChannelsFuncType

type OnInvokeTempChannelsFuncType func(eventCtx *sandwich.EventContext, member CustomEventInvokeTempChannelsStructure) error

type OnInvokeTempChannelsRemoveFuncType

type OnInvokeTempChannelsRemoveFuncType func(eventCtx *sandwich.EventContext, member CustomEventInvokeTempChannelsRemoveStructure) error

type OnInvokeWelcomerFuncType

type OnInvokeWelcomerFuncType func(eventCtx *sandwich.EventContext, member CustomEventInvokeWelcomerStructure) error

type PatreonMember

type PatreonMember struct {
	PatreonUserID discord.Snowflake `json:"patreon_user_id"`
	EntitledTiers []PatreonTier     `json:"active_tier"`
	Attributes    Attributes        `json:"attributes"`
}

func GetAllPatreonMembers

func GetAllPatreonMembers(ctx context.Context, client *http.Client) ([]PatreonMember, error)

type PatreonTier

type PatreonTier int64
const (
	PatreonTierFree PatreonTier = 10503463

	PatreonTierUnpublishedWelcomerDonator PatreonTier = 3975266
	PatreonTierUnpublishedWelcomerPro1    PatreonTier = 3744919
	PatreonTierUnpublishedWelcomerPro3    PatreonTier = 3744921
	PatreonTierUnpublishedWelcomerPro5    PatreonTier = 3744926

	PatreonTierWelcomerPro PatreonTier = 23606682
)

func (*PatreonTier) UnmarshalJSON

func (s *PatreonTier) UnmarshalJSON(b []byte) error

type PatreonUser

type PatreonUser struct {
	ID                discord.Snowflake             `json:"id"`
	Email             string                        `json:"email"`
	FullName          string                        `json:"full_name"`
	SocialConnections PatreonUser_SocialConnections `json:"social_connections"`
	ThumbURL          string                        `json:"thumb_url"`
}

func IdentifyPatreonMember

func IdentifyPatreonMember(ctx context.Context, token string) (PatreonUser, error)

type PatreonUserOuter

type PatreonUserOuter struct {
	Data patreonUser `json:"data"`
}

type PatreonUser_Attributes

type PatreonUser_Attributes struct {
	Email             string                        `json:"email"`
	FullName          string                        `json:"full_name"`
	SocialConnections PatreonUser_SocialConnections `json:"social_connections"`
	ThumbURL          string                        `json:"thumb_url"`
}

type PatreonUser_Discord

type PatreonUser_Discord struct {
	UserID discord.Snowflake `json:"user_id"`
}

type PatreonUser_SocialConnections

type PatreonUser_SocialConnections struct {
	Discord PatreonUser_Discord `json:"discord"`
}

type PatronSocialConnections

type PatronSocialConnections struct {
	Discord struct {
		UserID discord.Snowflake `json:"user_id"`
	} `json:"discord"`
}

type PatronStatus

type PatronStatus string
const (
	PatreonStatusNeverPledged PatronStatus = ""
	PatreonStatusActive       PatronStatus = "active_patron"
	PatreonStatusDeclined     PatronStatus = "declined_patron"
	PatreonStatusFormer       PatronStatus = "former_patron"
)

type PaypalSale

type PaypalSale struct {
	ID string `json:"id"`

	Amount paypal.Amount `json:"amount"`
	State  string        `json:"state"`

	CreateTime   time.Time `json:"create_time"`
	ClearingTime time.Time `json:"clearing_time"`
	UpdateTime   time.Time `json:"update_time"`

	BillingAgreementID string `json:"billing_agreement_id"`
}

type PricingSKU

type PricingSKU struct {
	ID                SKUName                 `json:"id"`
	Name              string                  `json:"name"`
	Description       string                  `json:"-"`
	MembershipType    database.MembershipType `json:"-"`
	SoftDescriptor    string                  `json:"-"` // This should be 13 characters or less.
	MonthCount        int                     `json:"month_count"`
	Costs             map[Currency]string     `json:"costs"`
	PatreonCheckoutID string                  `json:"patreon_checkout_id"`

	IsRecurring          bool                `json:"is_recurring"`
	PaypalSubscriptionID map[Currency]string `json:"paypal_subscription_id"`
}

type PushGuildScienceHandler

type PushGuildScienceHandler struct {
	sync.RWMutex

	Buffer []database.CreateManyScienceGuildEventsParams
	// contains filtered or unexported fields
}
var PushGuildScience *PushGuildScienceHandler

func NewPushGuildScienceHandler

func NewPushGuildScienceHandler(limit int) *PushGuildScienceHandler

func (*PushGuildScienceHandler) Flush

func (h *PushGuildScienceHandler) Flush(ctx context.Context)

func (*PushGuildScienceHandler) Push

func (h *PushGuildScienceHandler) Push(ctx context.Context, guildID, userID discord.Snowflake, eventType database.ScienceGuildEventType, data any)

func (*PushGuildScienceHandler) PushRaw

func (*PushGuildScienceHandler) Run

func (h *PushGuildScienceHandler) Run(ctx context.Context, interval time.Duration)

type RecaptchaRequest

type RecaptchaRequest struct {
	Secret    string `json:"secret"`
	Response  string `json:"response"`
	IPAddress string `json:"ip_address"`
}

type RecaptchaResponse

type RecaptchaResponse struct {
	ChallengeTimestamp time.Time `json:"challenge_ts"`
	Action             string    `json:"action"`
	Hostname           string    `json:"hostname"`
	ErrorCodes         []string  `json:"error-codes"`
	Score              float64   `json:"score"`
	Success            bool      `json:"success"`
}

type RedisDedupeProvider

type RedisDedupeProvider struct {
	Logger *slog.Logger
	// contains filtered or unexported fields
}
var DedupeProvider *RedisDedupeProvider

func NewRedisDedupeProvider

func NewRedisDedupeProvider(client *redis.Client, logger *slog.Logger) *RedisDedupeProvider

func (*RedisDedupeProvider) Deduplicate

func (r *RedisDedupeProvider) Deduplicate(ctx context.Context, key string, ttl time.Duration) bool

func (*RedisDedupeProvider) Release

func (r *RedisDedupeProvider) Release(ctx context.Context, key string)

type Relationships

type Relationships struct {
	CurrentlyEntitledTiers struct {
		Data []struct {
			ID PatreonTier `json:"id"`
		} `json:"data"`
	} `json:"currently_entitled_tiers"`
	User struct {
		Data struct {
			ID discord.Snowflake `json:"id"`
		} `json:"data"`
	} `json:"user"`
}

type SKUName

type SKUName string
const (
	SKUCustomBackgrounds   SKUName = "WEL/CBG"
	SKUWelcomerPro         SKUName = "WEL/1P1"
	SKUWelcomerProBiAnnual SKUName = "WEL/1P6"
	SKUWelcomerProAnnual   SKUName = "WEL/1P12"
)

type StubGuild

type StubGuild struct {
	Name          string            `json:"name"`
	Icon          string            `json:"icon"`
	Splash        string            `json:"splash"`
	Banner        string            `json:"banner"`
	ID            discord.Snowflake `json:"id"`
	Members       int32             `json:"members"`
	MembersJoined int32             `json:"members_joined"`
}

Guild represents a guild on discord.

func (StubGuild) String

func (s StubGuild) String() string

type StubInvite

type StubInvite struct {
	ExpiresAt StubTime          `json:"expires_at"`
	CreatedAt StubTime          `json:"created_at"`
	Inviter   StubUser          `json:"inviter"`
	ChannelID discord.Snowflake `json:"channel"`
	Code      string            `json:"code"`
	Uses      int32             `json:"uses"`
	MaxUses   int32             `json:"max_uses"`
	MaxAge    int32             `json:"max_age"`
	Temporary bool              `json:"temporary"`
}

Invite represents the invite used on discord.

type StubTime

type StubTime time.Time

func (StubTime) Relative

func (s StubTime) Relative() string

func (StubTime) String

func (s StubTime) String() string

type StubUser

type StubUser struct {
	CreatedAt     StubTime          `json:"created_at"`
	JoinedAt      StubTime          `json:"joined_at"`
	Name          string            `json:"name"`
	Username      string            `json:"username"`
	Discriminator string            `json:"discriminator"`
	GlobalName    string            `json:"global_name"`
	Mention       string            `json:"mention"`
	Avatar        string            `json:"avatar"`
	ID            discord.Snowflake `json:"id"`
	Bot           bool              `json:"bot"`
	Pending       bool              `json:"pending"`
}

StubUser represents a user on discord.

func (StubUser) String

func (s StubUser) String() string

type Timing

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

func NewTiming

func NewTiming() *Timing

func (*Timing) String

func (st *Timing) String() string

func (*Timing) Track

func (st *Timing) Track(name string)

type TimingEntry

type TimingEntry struct {
	Name  string
	Value int64
}

type TwilightProxy

type TwilightProxy struct {
	HTTP       *http.Client
	APIVersion string
	URLHost    string
	URLScheme  string
	UserAgent  string

	Debug bool
}

TwilightProxy is a proxy that requests are sent through, instead of directly to discord that will handle distributed requests and ratelimit automatically. See more at: https://github.com/twilight-rs/http-proxy

func (*TwilightProxy) Fetch

func (tl *TwilightProxy) Fetch(ctx context.Context, session *discord.Session, method, endpoint, contentType string, body []byte, headers http.Header) ([]byte, error)

func (*TwilightProxy) FetchBJ

func (tl *TwilightProxy) FetchBJ(ctx context.Context, session *discord.Session, method, endpoint, contentType string, body []byte, headers http.Header, response any) error

func (*TwilightProxy) FetchJJ

func (tl *TwilightProxy) FetchJJ(ctx context.Context, session *discord.Session, method, endpoint string, payload any, headers http.Header, response any) error

func (*TwilightProxy) SetDebug

func (tl *TwilightProxy) SetDebug(value bool)

type UserAgentSetterTransport

type UserAgentSetterTransport struct {
	UserAgent string
	// contains filtered or unexported fields
}

func NewUserAgentSetterTransport

func NewUserAgentSetterTransport(roundTripper http.RoundTripper, userAgent string) *UserAgentSetterTransport

NewUserAgentSetterTransport creates a new UserAgentSetterTransport.

func (*UserAgentSetterTransport) RoundTrip

func (t *UserAgentSetterTransport) RoundTrip(req *http.Request) (*http.Response, error)

type UserProvidedEmbed

type UserProvidedEmbed struct {
	Content string          `json:"content"`
	Embeds  []discord.Embed `json:"embeds"`
}

type VerticalAlignment

type VerticalAlignment string
const (
	VerticalAlignmentTop    VerticalAlignment = "start"
	VerticalAlignmentCenter VerticalAlignment = "center"
	VerticalAlignmentBottom VerticalAlignment = "end"
)

type WelcomerDatabaseConfigProvider

type WelcomerDatabaseConfigProvider struct {
	DefaultConfigProvider sandwich_daemon.ConfigProvider
}

func (*WelcomerDatabaseConfigProvider) GetConfig

func (*WelcomerDatabaseConfigProvider) SaveConfig

Not implemented, as the configuration is read-only in this context.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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