Skip to content

Commit

Permalink
Merge branch 'master' into feature/rpc
Browse files Browse the repository at this point in the history
# Conflicts:
#	discord/application.go
#	go.mod
#	go.sum
  • Loading branch information
topi314 committed Oct 29, 2023
2 parents ea2ffae + 5a9ed66 commit c86b58e
Show file tree
Hide file tree
Showing 127 changed files with 3,080 additions and 1,244 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
.idea/
.env
go.work
go.work.sum
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func main() {
panic(err)
}
// connect to the gateway
if err = client.Open(context.TODO()); err != nil {
if err = client.OpenGateway(context.TODO()); err != nil {
panic(err)
}

Expand Down Expand Up @@ -178,3 +178,7 @@ Contributions are welcomed but for bigger changes we recommend first reaching ou
## License

Distributed under the [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/disgoorg/disgo/blob/master/LICENSE). See LICENSE for more information.

## Supported by Jetbrains

<a href="https://www.jetbrains.com/community/opensource" target="_blank" title="Jetbrain Open Source Community Support"><img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.png" alt="Jetbrain Open Source Community Support" width="400px">
16 changes: 7 additions & 9 deletions _examples/application_commands/http/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,18 @@ module github.com/disgoorg/disgo/_examples/application_commands/http

go 1.18

replace github.com/disgoorg/disgo => ../../../

require (
github.com/disgoorg/disgo v0.11.5
github.com/disgoorg/log v1.2.0
github.com/disgoorg/disgo v0.16.8
github.com/disgoorg/log v1.2.1
github.com/disgoorg/snowflake/v2 v2.0.1
github.com/oasisprotocol/curve25519-voi v0.0.0-20220317090546-adb2f9614b17
github.com/oasisprotocol/curve25519-voi v0.0.0-20230110094441-db37f07504ce
)

require (
github.com/disgoorg/json v1.0.0 // indirect
github.com/disgoorg/json v1.1.0 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/sasha-s/go-csync v0.0.0-20210812194225-61421b77c44b // indirect
golang.org/x/crypto v0.0.0-20210813211128-0a44fdfbc16e // indirect
golang.org/x/exp v0.0.0-20220325121720-054d8573a5d8 // indirect
golang.org/x/sys v0.0.0-20211019181941-9d821ace8654 // indirect
golang.org/x/crypto v0.12.0 // indirect
golang.org/x/exp v0.0.0-20230801115018-d63ba01acd4b // indirect
golang.org/x/sys v0.11.0 // indirect
)
32 changes: 14 additions & 18 deletions _examples/application_commands/http/go.sum
Original file line number Diff line number Diff line change
@@ -1,28 +1,24 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/disgoorg/json v1.0.0 h1:kDhSM661fgIuNoZF3BO5/odaR5NSq80AWb937DH+Pdo=
github.com/disgoorg/json v1.0.0/go.mod h1:BHDwdde0rpQFDVsRLKhma6Y7fTbQKub/zdGO5O9NqqA=
github.com/disgoorg/log v1.2.0 h1:sqlXnu/ZKAlIlHV9IO+dbMto7/hCQ474vlIdMWk8QKo=
github.com/disgoorg/log v1.2.0/go.mod h1:3x1KDG6DI1CE2pDwi3qlwT3wlXpeHW/5rVay+1qDqOo=
github.com/disgoorg/disgo v0.16.8 h1:tvUeX+3Iu8U6koDc8RAgcQadRciWJwsI95Y7edHqq2g=
github.com/disgoorg/disgo v0.16.8/go.mod h1:5fsaUpfu6Yv0p+PfmsAeQkV395KQskVu/d1bdq8vsNI=
github.com/disgoorg/json v1.1.0 h1:7xigHvomlVA9PQw9bMGO02PHGJJPqvX5AnwlYg/Tnys=
github.com/disgoorg/json v1.1.0/go.mod h1:BHDwdde0rpQFDVsRLKhma6Y7fTbQKub/zdGO5O9NqqA=
github.com/disgoorg/log v1.2.1 h1:kZYAWkUBcGy4LbZcgYtgYu49xNVLy+xG5Uq3yz5VVQs=
github.com/disgoorg/log v1.2.1/go.mod h1:hhQWYTFTnIGzAuFPZyXJEi11IBm9wq+/TVZt/FEwX0o=
github.com/disgoorg/snowflake/v2 v2.0.1 h1:CuUxGLwggUxEswZOmZ+mZ5i0xSumQdXW9tXW7uGqe+0=
github.com/disgoorg/snowflake/v2 v2.0.1/go.mod h1:SPU9c2CNn5DSyb86QcKtdZgix9osEtKrHLW4rMhfLCs=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/oasisprotocol/curve25519-voi v0.0.0-20220317090546-adb2f9614b17 h1:pxR+aWfo+famermIZvD+SiDQ3qmF7Iy2VPZuEsKTMtA=
github.com/oasisprotocol/curve25519-voi v0.0.0-20220317090546-adb2f9614b17/go.mod h1:WUcXjUd98qaCVFb6j8Xc87MsKeMCXDu9Nk8JRJ9SeC8=
github.com/oasisprotocol/curve25519-voi v0.0.0-20230110094441-db37f07504ce h1:/pEpMk55wH0X+E5zedGEMOdLuWmV8P4+4W3+LZaM6kg=
github.com/oasisprotocol/curve25519-voi v0.0.0-20230110094441-db37f07504ce/go.mod h1:hVoHR2EVESiICEMbg137etN/Lx+lSrHPTD39Z/uE+2s=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/sasha-s/go-csync v0.0.0-20210812194225-61421b77c44b h1:qYTY2tN72LhgDj2rtWG+LI6TXFl2ygFQQ4YezfVaGQE=
github.com/sasha-s/go-csync v0.0.0-20210812194225-61421b77c44b/go.mod h1:/pA7k3zsXKdjjAiUhB5CjuKib9KJGCaLvZwtxGC8U0s=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
golang.org/x/crypto v0.0.0-20210813211128-0a44fdfbc16e h1:VvfwVmMH40bpMeizC9/K7ipM5Qjucuu16RWfneFPyhQ=
golang.org/x/crypto v0.0.0-20210813211128-0a44fdfbc16e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/exp v0.0.0-20220325121720-054d8573a5d8 h1:Xt4/LzbTwfocTk9ZLEu4onjeFucl88iW+v4j4PWbQuE=
golang.org/x/exp v0.0.0-20220325121720-054d8573a5d8/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211019181941-9d821ace8654 h1:id054HUawV2/6IGm2IV8KZQjqtwAOo2CYlOToYqa0d0=
golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/crypto v0.12.0 h1:tFM/ta59kqch6LlvYnPa0yx5a83cL2nHflFhYKvv9Yk=
golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw=
golang.org/x/exp v0.0.0-20230801115018-d63ba01acd4b h1:r+vk0EmXNmekl0S0BascoeeoHk/L7wmaW2QF90K+kYI=
golang.org/x/exp v0.0.0-20230801115018-d63ba01acd4b/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc=
golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
29 changes: 17 additions & 12 deletions _examples/handler/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/disgoorg/disgo"
"github.com/disgoorg/disgo/bot"
"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/disgo/events"
"github.com/disgoorg/disgo/handler"
"github.com/disgoorg/disgo/handler/middleware"
)
Expand Down Expand Up @@ -72,18 +73,19 @@ func main() {
r.Group(func(r handler.Router) {
r.Use(middleware.Print("group1"))
r.Route("/test", func(r handler.Router) {
r.HandleCommand("/sub2", handleContent("/test/sub2"))
r.Command("/sub2", handleContent("/test/sub2"))
r.Route("/{group}", func(r handler.Router) {
r.HandleCommand("/sub", handleVariableContent)
r.Command("/sub", handleVariableContent)
})
})
})
r.Group(func(r handler.Router) {
r.Use(middleware.Print("group2"))
r.HandleCommand("/ping", handlePing)
r.HandleCommand("/ping2", handleContent("pong2"))
r.HandleComponent("button1/{data}", handleComponent)
r.Command("/ping", handlePing)
r.Command("/ping2", handleContent("pong2"))
r.Component("button1/{data}", handleComponent)
})
r.NotFound(handleNotFound)

client, err := disgo.New(token,
bot.WithDefaultGateway(),
Expand All @@ -93,9 +95,8 @@ func main() {
log.Fatal("error while building bot: ", err)
}

// register commands
if _, err = client.Rest().SetGuildCommands(client.ApplicationID(), guildID, commands); err != nil {
log.Fatal("error while setting global commands: ", err)
if err = handler.SyncCommands(client, commands, []snowflake.ID{guildID}); err != nil {
log.Fatal("error while syncing commands: ", err)
}

defer client.Close(context.TODO())
Expand All @@ -111,17 +112,17 @@ func main() {
}

func handleContent(content string) handler.CommandHandler {
return func(client bot.Client, event *handler.CommandEvent) error {
return func(event *handler.CommandEvent) error {
return event.CreateMessage(discord.MessageCreate{Content: content})
}
}

func handleVariableContent(client bot.Client, event *handler.CommandEvent) error {
func handleVariableContent(event *handler.CommandEvent) error {
group := event.Variables["group"]
return event.CreateMessage(discord.MessageCreate{Content: "group: " + group})
}

func handlePing(client bot.Client, event *handler.CommandEvent) error {
func handlePing(event *handler.CommandEvent) error {
return event.CreateMessage(discord.MessageCreate{
Content: "pong",
Components: []discord.ContainerComponent{
Expand All @@ -132,7 +133,11 @@ func handlePing(client bot.Client, event *handler.CommandEvent) error {
})
}

func handleComponent(client bot.Client, event *handler.ComponentEvent) error {
func handleComponent(event *handler.ComponentEvent) error {
data := event.Variables["data"]
return event.CreateMessage(discord.MessageCreate{Content: "component: " + data})
}

func handleNotFound(event *events.InteractionCreate) error {
return event.Respond(discord.InteractionResponseTypeCreateMessage, discord.MessageCreate{Content: "not found"})
}
10 changes: 6 additions & 4 deletions _examples/oauth2/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ var (
logger = log.Default()
httpClient = http.DefaultClient
client oauth2.Client
sessions map[string]oauth2.Session
)

func init() {
Expand All @@ -49,8 +50,8 @@ func handleRoot(w http.ResponseWriter, r *http.Request) {
var body string
cookie, err := r.Cookie("token")
if err == nil {
session := client.SessionController().GetSession(cookie.Value)
if session != nil {
session, ok := sessions[cookie.Value]
if ok {
var user *discord.OAuth2User
user, err = client.GetUser(session)
if err != nil {
Expand Down Expand Up @@ -89,7 +90,7 @@ func handleRoot(w http.ResponseWriter, r *http.Request) {
}

func handleLogin(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, client.GenerateAuthorizationURL(baseURL+"/trylogin", discord.PermissionsNone, 0, false, discord.OAuth2ScopeIdentify, discord.OAuth2ScopeGuilds, discord.OAuth2ScopeEmail, discord.OAuth2ScopeConnections, discord.OAuth2ScopeWebhookIncoming), http.StatusMovedPermanently)
http.Redirect(w, r, client.GenerateAuthorizationURL(baseURL+"/trylogin", discord.PermissionsNone, 0, false, discord.OAuth2ScopeIdentify, discord.OAuth2ScopeGuilds, discord.OAuth2ScopeEmail, discord.OAuth2ScopeConnections, discord.OAuth2ScopeWebhookIncoming), http.StatusSeeOther)
}

func handleTryLogin(w http.ResponseWriter, r *http.Request) {
Expand All @@ -100,11 +101,12 @@ func handleTryLogin(w http.ResponseWriter, r *http.Request) {
)
if code != "" && state != "" {
identifier := randStr(32)
_, err := client.StartSession(code, state, identifier)
session, _, err := client.StartSession(code, state)
if err != nil {
writeError(w, "error while starting session", err)
return
}
sessions[identifier] = session
http.SetCookie(w, &http.Cookie{Name: "token", Value: identifier})
}
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
Expand Down
17 changes: 17 additions & 0 deletions _examples/proxy/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Proxy

This example shows how to use disgo with a gateway-proxy & rest-proxy such as https://github.com/Gelbpunkt/gateway-proxy and https://github.com/twilight-rs/http-proxy

For configuring those proxies, please refer to their documentation.

## Environment Variables

```env
disgo_token=discord bot token
disgo_guild_id=guild id to register commmands to
disgo_gateway_url=url to your gateway proxy. example: ws://gateway-proxy:7878
disgo_rest_url=url to your rest proxy. example: http://rest-proxy:7979/api/v10
```
100 changes: 100 additions & 0 deletions _examples/proxy/example.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package main

import (
"context"
"os"
"os/signal"
"syscall"

"github.com/disgoorg/log"
"github.com/disgoorg/snowflake/v2"

"github.com/disgoorg/disgo"
"github.com/disgoorg/disgo/bot"
"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/disgo/events"
"github.com/disgoorg/disgo/gateway"
"github.com/disgoorg/disgo/rest"
"github.com/disgoorg/disgo/sharding"
)

var (
token = os.Getenv("disgo_token")
guildID = snowflake.GetEnv("disgo_guild_id")
gatewayURL = os.Getenv("disgo_gateway_url")
restURL = os.Getenv("disgo_rest_url")

commands = []discord.ApplicationCommandCreate{
discord.SlashCommandCreate{
Name: "say",
Description: "says what you say",
Options: []discord.ApplicationCommandOption{
discord.ApplicationCommandOptionString{
Name: "message",
Description: "What to say",
Required: true,
},
discord.ApplicationCommandOptionBool{
Name: "ephemeral",
Description: "If the response should only be visible to you",
Required: true,
},
},
},
}
)

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

client, err := disgo.New(token,
bot.WithShardManagerConfigOpts(
sharding.WithGatewayConfigOpts( // gateway intents are set in the proxy not here
gateway.WithURL(gatewayURL), // set the custom gateway url
gateway.WithCompress(false), // we don't want compression as that would be additional overhead
),
sharding.WithRateLimiter(sharding.NewNoopRateLimiter()), // disable sharding rate limiter as the proxy handles it
),
bot.WithRestClientConfigOpts(
rest.WithURL(restURL), // set the custom rest url
rest.WithRateLimiter(rest.NewNoopRateLimiter()), // disable rest rate limiter as the proxy handles it
),
bot.WithEventListenerFunc(commandListener),
)

if err != nil {
log.Fatal("error while building disgo instance: ", err)
return
}

defer client.Close(context.TODO())

if _, err = client.Rest().SetGuildCommands(client.ApplicationID(), guildID, commands); err != nil {
log.Fatal("error while registering commands: ", err)
}

if err = client.OpenGateway(context.TODO()); err != nil {
log.Fatal("error while connecting to gateway: ", err)
}

log.Infof("example is now running. Press CTRL-C to exit.")
s := make(chan os.Signal, 1)
signal.Notify(s, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
<-s
}

func commandListener(event *events.ApplicationCommandInteractionCreate) {
data := event.SlashCommandInteractionData()
if data.CommandName() == "say" {
err := event.CreateMessage(discord.NewMessageCreateBuilder().
SetContent(data.String("message")).
SetEphemeral(data.Bool("ephemeral")).
Build(),
)
if err != nil {
event.Client().Logger().Error("error on sending response: ", err)
}
}
}
2 changes: 1 addition & 1 deletion _examples/test/examplebot.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func main() {
client, err := disgo.New(token,
bot.WithGatewayConfigOpts(
gateway.WithIntents(gateway.IntentsNonPrivileged, gateway.IntentMessageContent),
gateway.WithPresenceOpts(gateway.WithListeningActivity("your bullshit"), gateway.WithOnlineStatus(discord.OnlineStatusDND)),
gateway.WithPresenceOpts(gateway.WithListeningActivity("your bullshit", gateway.WithActivityState("lol")), gateway.WithOnlineStatus(discord.OnlineStatusDND)),
),
bot.WithCacheConfigOpts(
cache.WithCaches(cache.FlagsAll),
Expand Down
4 changes: 2 additions & 2 deletions _examples/test/listeners.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func componentListener(event *events.ComponentInteractionCreate) {
ids := strings.Split(data.CustomID(), ":")
switch ids[0] {
case "modal":
_ = event.CreateModal(discord.ModalCreate{
_ = event.Modal(discord.ModalCreate{
CustomID: "test" + ids[1],
Title: "Test" + ids[1] + " Modal",
Components: []discord.ContainerComponent{
Expand Down Expand Up @@ -159,7 +159,7 @@ func applicationCommandListener(event *events.ApplicationCommandInteractionCreat
func autocompleteListener(event *events.AutocompleteInteractionCreate) {
switch event.Data.CommandName {
case "test2":
if err := event.Result([]discord.AutocompleteChoice{
if err := event.AutocompleteResult([]discord.AutocompleteChoice{
discord.AutocompleteChoiceInt{
Name: "test1",
Value: 1,
Expand Down
11 changes: 1 addition & 10 deletions _examples/verified_roles/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,7 @@ func handleCallback(w http.ResponseWriter, r *http.Request) {
state = query.Get("state")
)
if code != "" && state != "" {
identifier := randStr(32)
session, err := oAuth2Client.StartSession(code, state, identifier)
session, _, err := oAuth2Client.StartSession(code, state)
if err != nil {
writeError(w, "error while starting session", err)
return
Expand Down Expand Up @@ -104,11 +103,3 @@ func writeError(w http.ResponseWriter, text string, err error) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(text + ": " + err.Error()))
}

func randStr(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
Loading

0 comments on commit c86b58e

Please sign in to comment.