Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: webhook URL parse #221

Merged
merged 3 commits into from Dec 17, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 24 additions & 0 deletions webhook/webhook_client_impl.go
Expand Up @@ -2,12 +2,36 @@ package webhook

import (
"context"
"errors"
"net/url"
"strings"

"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/disgo/rest"
"github.com/disgoorg/snowflake/v2"
)

// ParseURL parses a webhook URL
func NewWithURL(webhook string, opts ...ConfigOpt) (Client, error) {
u, err := url.Parse(webhook)
if err != nil {
return nil, err
}

parts := strings.FieldsFunc(u.Path, func(r rune) bool { return r == '/' })
topi314 marked this conversation as resolved.
Show resolved Hide resolved
if len(parts) != 4 {
return nil, errors.New("invalid webhook URL")
}
id, token := parts[2], parts[3]

sf, err := snowflake.Parse(id)
if err != nil {
return nil, err
}

return New(sf, token, opts...), nil
}

// New creates a new Client with the given ID, token and ConfigOpt(s).
func New(id snowflake.ID, token string, opts ...ConfigOpt) Client {
config := DefaultConfig()
Expand Down
56 changes: 56 additions & 0 deletions webhook/webook_test.go
@@ -0,0 +1,56 @@
package webhook

import (
"testing"

"github.com/disgoorg/snowflake/v2"
"github.com/stretchr/testify/require"
)

func TestParseURL(t *testing.T) {
tt := []struct {
URL string
ID snowflake.ID
Token string
Err bool
}{
{
URL: "https://discord.com/api/webhooks/123456789123456789/foo",
ID: snowflake.ID(123456789123456789),
Token: "foo",
},
{
URL: "https://discord.com/api/webhooks/123456789123456789/foo/",
ID: snowflake.ID(123456789123456789),
Token: "foo",
},
{
URL: "https://canary.discord.com/api/webhooks/123456789123456789/foo",
ID: snowflake.ID(123456789123456789),
Token: "foo",
},
{
URL: "foobarbaz",
Err: true,
},
{
URL: "https://discord.com/api/webhooks/123456789123456789/foo?wait=10",
ID: snowflake.ID(123456789123456789),
Token: "foo",
},
}

for _, tc := range tt {
t.Run(tc.URL, func(t *testing.T) {
assert := require.New(t)

c, err := ParseURL(tc.URL)
jolheiser marked this conversation as resolved.
Show resolved Hide resolved
if tc.Err {
assert.Error(err, "URL parsing should have resulted in an error")
return
}
assert.Equal(tc.ID, c.ID(), "URL ID should match")
assert.Equal(tc.Token, c.Token(), "URL token should match")
})
}
}