Skip to content

Commit

Permalink
Merge pull request #173 from disgoorg/cleanup/gateway-structs-and-consts
Browse files Browse the repository at this point in the history
gateway structs & const cleanup
  • Loading branch information
topi314 authored Jul 2, 2022
2 parents b68c4aa + 81cdfac commit c682129
Show file tree
Hide file tree
Showing 129 changed files with 2,806 additions and 3,221 deletions.
4 changes: 2 additions & 2 deletions _examples/application_commands/gateway/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ var (
)

func main() {
log.SetLevel(log.LevelTrace)
log.SetLevel(log.LevelInfo)
log.Info("starting example...")
log.Info("disgo version: ", disgo.Version)

client, err := disgo.New(token,
bot.WithGatewayConfigOpts(gateway.WithGatewayIntents(discord.GatewayIntentsNone)),
bot.WithGatewayConfigOpts(gateway.WithIntents(gateway.IntentsNone)),
bot.WithEventListenerFunc(commandListener),
)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion _examples/application_commands/localization/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func main() {
log.Infof("disgo version: %s", disgo.Version)

client, err := disgo.New(token,
bot.WithGatewayConfigOpts(gateway.WithGatewayIntents(discord.GatewayIntentsNone)),
bot.WithGatewayConfigOpts(gateway.WithIntents(gateway.IntentsNone)),
bot.WithEventListenerFunc(commandListener),
)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions _examples/auto_moderation/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func main() {
log.Infof("disgo version: %s", disgo.Version)

client, err := disgo.New(token,
bot.WithGatewayConfigOpts(gateway.WithGatewayIntents(discord.GatewayIntentAutoModerationConfiguration, discord.GatewayIntentAutoModerationExecution)),
bot.WithGatewayConfigOpts(gateway.WithIntents(gateway.IntentAutoModerationConfiguration, gateway.IntentAutoModerationExecution)),
bot.WithEventListenerFunc(func(event *events.Ready) {
go showCaseAutoMod(event.Client())
}),
Expand All @@ -44,7 +44,7 @@ func main() {
fmt.Printf("rule deleted: %#v\n", event.AutoModerationRule)
}),
bot.WithEventListenerFunc(func(event *events.AutoModerationActionExecution) {
fmt.Printf("action executed: %#v\n", event.GatewayEventAutoModerationActionExecution)
fmt.Printf("action executed: %#v\n", event.EventAutoModerationActionExecution)
}),
)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion _examples/components/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func main() {
log.Infof("disgo version: %s", disgo.Version)

client, err := disgo.New(token,
bot.WithGatewayConfigOpts(gateway.WithGatewayIntents(discord.GatewayIntentGuilds, discord.GatewayIntentGuildMessages, discord.GatewayIntentDirectMessages)),
bot.WithGatewayConfigOpts(gateway.WithIntents(gateway.IntentGuilds, gateway.IntentGuildMessages, gateway.IntentDirectMessages)),
bot.WithEventListenerFunc(func(event *events.MessageCreate) {
if event.Message.Author.Bot || event.Message.Author.System {
return
Expand Down
2 changes: 1 addition & 1 deletion _examples/guild_scheduled_events/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func main() {

client, err := disgo.New(token,
bot.WithGatewayConfigOpts(
gateway.WithGatewayIntents(discord.GatewayIntentGuildScheduledEvents|discord.GatewayIntentGuilds|discord.GatewayIntentGuildMessages),
gateway.WithIntents(gateway.IntentGuildScheduledEvents|gateway.IntentGuilds|gateway.IntentGuildMessages),
),
bot.WithCacheConfigOpts(
cache.WithCacheFlags(cache.FlagsAll),
Expand Down
2 changes: 1 addition & 1 deletion _examples/message_collector/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func main() {
log.Infof("disgo version: %s", disgo.Version)

client, err := disgo.New(token,
bot.WithGatewayConfigOpts(gateway.WithGatewayIntents(discord.GatewayIntentGuilds, discord.GatewayIntentGuildMessages, discord.GatewayIntentDirectMessages, discord.GatewayIntentMessageContent)),
bot.WithGatewayConfigOpts(gateway.WithIntents(gateway.IntentGuilds, gateway.IntentGuildMessages, gateway.IntentDirectMessages, gateway.IntentMessageContent)),
bot.WithEventListenerFunc(onMessageCreate),
)
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions _examples/ping_pong/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ func main() {

client, err := disgo.New(os.Getenv("disgo_token"),
bot.WithGatewayConfigOpts(
gateway.WithGatewayIntents(
discord.GatewayIntentGuildMessages,
discord.GatewayIntentMessageContent,
gateway.WithIntents(
gateway.IntentGuildMessages,
gateway.IntentMessageContent,
),
),
bot.WithCacheConfigOpts(cache.WithCacheFlags(cache.FlagsDefault)),
Expand Down
2 changes: 1 addition & 1 deletion _examples/sharding/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func main() {
sharding.WithShardCount(2),
sharding.WithAutoScaling(true),
sharding.WithGatewayConfigOpts(
gateway.WithGatewayIntents(discord.GatewayIntentGuilds, discord.GatewayIntentGuildMessages, discord.GatewayIntentDirectMessages),
gateway.WithIntents(gateway.IntentGuilds, gateway.IntentGuildMessages, gateway.IntentDirectMessages),
gateway.WithCompress(true),
),
),
Expand Down
2 changes: 1 addition & 1 deletion _examples/test/examplebot.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func main() {

client, err := disgo.New(token,
bot.WithGatewayConfigOpts(
gateway.WithGatewayIntents(discord.GatewayIntentsNonPrivileged, discord.GatewayIntentMessageContent),
gateway.WithIntents(gateway.IntentsNonPrivileged, gateway.IntentMessageContent),
gateway.WithPresence(discord.NewListeningPresence("your bullshit", discord.OnlineStatusOnline, false)),
),
bot.WithCacheConfigOpts(
Expand Down
2 changes: 1 addition & 1 deletion _examples/threads/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func main() {

client, err := disgo.New(token,
bot.WithGatewayConfigOpts(
gateway.WithGatewayIntents(discord.GatewayIntentsAll),
gateway.WithIntents(gateway.IntentsAll),
),
bot.WithCacheConfigOpts(
cache.WithCacheFlags(cache.FlagsAll),
Expand Down
36 changes: 18 additions & 18 deletions bot/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,32 +70,32 @@ type Client interface {
// Shard returns the gateway.Gateway the specific guildID runs on.
Shard(guildID snowflake.ID) (gateway.Gateway, error)

// Connect sends a discord.GatewayMessageDataVoiceStateUpdate to the specific gateway.Gateway and connects the bot to the specified channel.
// Connect sends a discord.MessageDataVoiceStateUpdate to the specific gateway.Gateway and connects the bot to the specified channel.
Connect(ctx context.Context, guildID snowflake.ID, channelID snowflake.ID) error

// Disconnect sends a discord.GatewayMessageDataVoiceStateUpdate to the specific gateway.Gateway and disconnects the bot from this guild.
// Disconnect sends a discord.MessageDataVoiceStateUpdate to the specific gateway.Gateway and disconnects the bot from this guild.
Disconnect(ctx context.Context, guildID snowflake.ID) error

// RequestMembers sends a discord.GatewayMessageDataRequestGuildMembers to the specific gateway.Gateway and requests the Member(s) of the specified guild.
// RequestMembers sends a discord.MessageDataRequestGuildMembers to the specific gateway.Gateway and requests the Member(s) of the specified guild.
// guildID : is the snowflake of the guild to request the members of.
// presence : Weather or not to include discord.Presence data.
// nonce : The nonce to return to the discord.GatewayEventGuildMembersChunk.
// nonce : The nonce to return to the discord.EventGuildMembersChunk.
// userIDs : The snowflakes of the users to request the members of.
RequestMembers(ctx context.Context, guildID snowflake.ID, presence bool, nonce string, userIDs ...snowflake.ID) error

// RequestMembersWithQuery sends a discord.GatewayMessageDataRequestGuildMembers to the specific gateway.Gateway and requests the Member(s) of the specified guild.
// RequestMembersWithQuery sends a discord.MessageDataRequestGuildMembers to the specific gateway.Gateway and requests the Member(s) of the specified guild.
// guildID : is the snowflake of the guild to request the members of.
// presence : Weather or not to include discord.Presence data.
// nonce : The nonce to return to the discord.GatewayEventGuildMembersChunk.
// nonce : The nonce to return to the discord.EventGuildMembersChunk.
// query : The query to use for the request.
// limit : The number of discord.Member(s) to return.
RequestMembersWithQuery(ctx context.Context, guildID snowflake.ID, presence bool, nonce string, query string, limit int) error

// SetPresence sends a discord.GatewayMessageDataPresenceUpdate to the gateway.Gateway.
SetPresence(ctx context.Context, presenceUpdate discord.GatewayMessageDataPresenceUpdate) error
// SetPresence sends a discord.MessageDataPresenceUpdate to the gateway.Gateway.
SetPresence(ctx context.Context, presenceUpdate gateway.MessageDataPresenceUpdate) error

// SetPresenceForShard sends a discord.GatewayMessageDataPresenceUpdate to the specific gateway.Gateway.
SetPresenceForShard(ctx context.Context, shardId int, presenceUpdate discord.GatewayMessageDataPresenceUpdate) error
// SetPresenceForShard sends a discord.MessageDataPresenceUpdate to the specific gateway.Gateway.
SetPresenceForShard(ctx context.Context, shardId int, presenceUpdate gateway.MessageDataPresenceUpdate) error

// MemberChunkingManager returns the MemberChunkingManager used by the Client.
MemberChunkingManager() MemberChunkingManager
Expand Down Expand Up @@ -232,7 +232,7 @@ func (c *clientImpl) Connect(ctx context.Context, guildID snowflake.ID, channelI
if err != nil {
return err
}
return shard.Send(ctx, discord.GatewayOpcodeVoiceStateUpdate, discord.GatewayMessageDataVoiceStateUpdate{
return shard.Send(ctx, gateway.OpcodeVoiceStateUpdate, gateway.MessageDataVoiceStateUpdate{
GuildID: guildID,
ChannelID: &channelID,
})
Expand All @@ -243,7 +243,7 @@ func (c *clientImpl) Disconnect(ctx context.Context, guildID snowflake.ID) error
if err != nil {
return err
}
return shard.Send(ctx, discord.GatewayOpcodeVoiceStateUpdate, discord.GatewayMessageDataVoiceStateUpdate{
return shard.Send(ctx, gateway.OpcodeVoiceStateUpdate, gateway.MessageDataVoiceStateUpdate{
GuildID: guildID,
ChannelID: nil,
})
Expand All @@ -254,7 +254,7 @@ func (c *clientImpl) RequestMembers(ctx context.Context, guildID snowflake.ID, p
if err != nil {
return err
}
return shard.Send(ctx, discord.GatewayOpcodeRequestGuildMembers, discord.GatewayMessageDataRequestGuildMembers{
return shard.Send(ctx, gateway.OpcodeRequestGuildMembers, gateway.MessageDataRequestGuildMembers{
GuildID: guildID,
Presences: presence,
UserIDs: userIDs,
Expand All @@ -267,7 +267,7 @@ func (c *clientImpl) RequestMembersWithQuery(ctx context.Context, guildID snowfl
if err != nil {
return err
}
return shard.Send(ctx, discord.GatewayOpcodeRequestGuildMembers, discord.GatewayMessageDataRequestGuildMembers{
return shard.Send(ctx, gateway.OpcodeRequestGuildMembers, gateway.MessageDataRequestGuildMembers{
GuildID: guildID,
Query: &query,
Limit: &limit,
Expand All @@ -276,22 +276,22 @@ func (c *clientImpl) RequestMembersWithQuery(ctx context.Context, guildID snowfl
})
}

func (c *clientImpl) SetPresence(ctx context.Context, presenceUpdate discord.GatewayMessageDataPresenceUpdate) error {
func (c *clientImpl) SetPresence(ctx context.Context, presenceUpdate gateway.MessageDataPresenceUpdate) error {
if !c.HasGateway() {
return discord.ErrNoGateway
}
return c.gateway.Send(ctx, discord.GatewayOpcodePresenceUpdate, presenceUpdate)
return c.gateway.Send(ctx, gateway.OpcodePresenceUpdate, presenceUpdate)
}

func (c *clientImpl) SetPresenceForShard(ctx context.Context, shardId int, presenceUpdate discord.GatewayMessageDataPresenceUpdate) error {
func (c *clientImpl) SetPresenceForShard(ctx context.Context, shardId int, presenceUpdate gateway.MessageDataPresenceUpdate) error {
if !c.HasShardManager() {
return discord.ErrNoShardManager
}
shard := c.shardManager.Shard(shardId)
if shard == nil {
return discord.ErrShardNotFound
}
return shard.Send(ctx, discord.GatewayOpcodePresenceUpdate, presenceUpdate)
return shard.Send(ctx, gateway.OpcodePresenceUpdate, presenceUpdate)
}

func (c *clientImpl) MemberChunkingManager() MemberChunkingManager {
Expand Down
6 changes: 3 additions & 3 deletions bot/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
)

// DefaultConfig returns a Config with sensible defaults.
func DefaultConfig(gatewayHandlers map[discord.GatewayEventType]GatewayEventHandler, httpHandler HTTPServerEventHandler) *Config {
func DefaultConfig(gatewayHandlers map[gateway.EventType]GatewayEventHandler, httpHandler HTTPServerEventHandler) *Config {
return &Config{
Logger: log.Default(),
EventManagerConfigOpts: []EventManagerConfigOpt{WithGatewayHandlers(gatewayHandlers), WithHTTPServerHandler(httpHandler)},
Expand Down Expand Up @@ -232,7 +232,7 @@ func BuildClient(token string, config Config, gatewayEventHandlerFunc func(clien
}

config.GatewayConfigOpts = append([]gateway.ConfigOpt{
gateway.WithGatewayURL(gatewayRs.URL),
gateway.WithURL(gatewayRs.URL),
gateway.WithLogger(client.logger),
gateway.WithOS(os),
gateway.WithBrowser(name),
Expand Down Expand Up @@ -262,7 +262,7 @@ func BuildClient(token string, config Config, gatewayEventHandlerFunc func(clien
sharding.WithShardCount(gatewayBotRs.Shards),
sharding.WithShardIDs(shardIDs...),
sharding.WithGatewayConfigOpts(
gateway.WithGatewayURL(gatewayBotRs.URL),
gateway.WithURL(gatewayBotRs.URL),
gateway.WithLogger(client.logger),
gateway.WithOS(os),
gateway.WithBrowser(name),
Expand Down
62 changes: 30 additions & 32 deletions bot/event_manager.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package bot

import (
"io"
"runtime/debug"
"sync"

"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/disgo/gateway"
"github.com/disgoorg/disgo/httpserver"
"github.com/disgoorg/disgo/json"
)

var _ EventManager = (*eventManagerImpl)(nil)
Expand All @@ -25,20 +23,17 @@ func NewEventManager(client Client, opts ...EventManagerConfigOpt) EventManager

// EventManager lets you listen for specific events triggered by raw gateway events
type EventManager interface {
// RawEventsEnabled returns whether events.RawEvent are enabled
RawEventsEnabled() bool

// AddEventListeners adds one or more EventListener(s) to the EventManager
AddEventListeners(eventListeners ...EventListener)

// RemoveEventListeners removes one or more EventListener(s) from the EventManager
RemoveEventListeners(eventListeners ...EventListener)

// HandleGatewayEvent calls the correct GatewayEventHandler for the payload
HandleGatewayEvent(gatewayEventType discord.GatewayEventType, sequenceNumber int, shardID int, payload io.Reader)
HandleGatewayEvent(gatewayEventType gateway.EventType, sequenceNumber int, shardID int, event gateway.EventData)

// HandleHTTPEvent calls the HTTPServerEventHandler for the payload
HandleHTTPEvent(respondFunc httpserver.RespondFunc, payload io.Reader)
HandleHTTPEvent(respondFunc httpserver.RespondFunc, event gateway.EventInteractionCreate)

// DispatchEvent dispatches a new Event to the Client's EventListener(s)
DispatchEvent(event Event)
Expand Down Expand Up @@ -76,15 +71,33 @@ type Event interface {

// GatewayEventHandler is used to handle Gateway Event(s)
type GatewayEventHandler interface {
EventType() discord.GatewayEventType
New() any
HandleGatewayEvent(client Client, sequenceNumber int, shardID int, v any)
EventType() gateway.EventType
HandleGatewayEvent(client Client, sequenceNumber int, shardID int, event gateway.EventData)
}

// NewGatewayEventHandler returns a new GatewayEventHandler for the given GatewayEventType and handler func
func NewGatewayEventHandler[T gateway.EventData](eventType gateway.EventType, handleFunc func(client Client, sequenceNumber int, shardID int, event T)) GatewayEventHandler {
return &genericGatewayEventHandler[T]{eventType: eventType, handleFunc: handleFunc}
}

type genericGatewayEventHandler[T gateway.EventData] struct {
eventType gateway.EventType
handleFunc func(client Client, sequenceNumber int, shardID int, event T)
}

func (h *genericGatewayEventHandler[T]) EventType() gateway.EventType {
return h.eventType
}

func (h *genericGatewayEventHandler[T]) HandleGatewayEvent(client Client, sequenceNumber int, shardID int, event gateway.EventData) {
if e, ok := event.(T); ok {
h.handleFunc(client, sequenceNumber, shardID, e)
}
}

// HTTPServerEventHandler is used to handle HTTP Event(s)
type HTTPServerEventHandler interface {
New() any
HandleHTTPEvent(client Client, respondFunc func(response discord.InteractionResponse) error, v any)
HandleHTTPEvent(client Client, respondFunc httpserver.RespondFunc, event gateway.EventInteractionCreate)
}

type eventManagerImpl struct {
Expand All @@ -95,35 +108,20 @@ type eventManagerImpl struct {
mu sync.Mutex
}

func (e *eventManagerImpl) RawEventsEnabled() bool {
return e.config.RawEventsEnabled
}

func (e *eventManagerImpl) HandleGatewayEvent(gatewayEventType discord.GatewayEventType, sequenceNumber int, shardID int, reader io.Reader) {
func (e *eventManagerImpl) HandleGatewayEvent(gatewayEventType gateway.EventType, sequenceNumber int, shardID int, event gateway.EventData) {
e.mu.Lock()
defer e.mu.Unlock()
if handler, ok := e.config.GatewayHandlers[gatewayEventType]; ok {
v := handler.New()
if v != nil {
if err := json.NewDecoder(reader).Decode(&v); err != nil {
e.client.Logger().Errorf("error while unmarshalling event '%s'. error: %s", gatewayEventType, err.Error())
return
}
}
handler.HandleGatewayEvent(e.client, sequenceNumber, shardID, v)
handler.HandleGatewayEvent(e.client, sequenceNumber, shardID, event)
} else {
e.client.Logger().Warnf("no handler for gateway event '%s' found", gatewayEventType)
}
}

func (e *eventManagerImpl) HandleHTTPEvent(respondFunc httpserver.RespondFunc, reader io.Reader) {
func (e *eventManagerImpl) HandleHTTPEvent(respondFunc httpserver.RespondFunc, event gateway.EventInteractionCreate) {
e.mu.Lock()
defer e.mu.Unlock()
v := e.config.HTTPServerHandler.New()
if err := json.NewDecoder(reader).Decode(&v); err != nil {
e.client.Logger().Error("error while unmarshalling httpserver event. error: ", err)
}
e.config.HTTPServerHandler.HandleHTTPEvent(e.client, respondFunc, v)
e.config.HTTPServerHandler.HandleHTTPEvent(e.client, respondFunc, event)
}

func (e *eventManagerImpl) DispatchEvent(event Event) {
Expand Down
Loading

0 comments on commit c682129

Please sign in to comment.