Skip to content

Commit

Permalink
Merge pull request #129 from Cyb3r-Jak3/discordgo-rewrite
Browse files Browse the repository at this point in the history
Discordgo rewrite
  • Loading branch information
Lucky authored Apr 27, 2024
2 parents 6852c02 + 00d6c6f commit eca997a
Show file tree
Hide file tree
Showing 46 changed files with 1,631 additions and 892 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,7 @@ terraform.tfstate
terraform.tfstate.backup

.terraform/

.idea/

.env
50 changes: 9 additions & 41 deletions discord/config.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
package discord

import (
"fmt"
"net/http"
"strconv"
"time"

"github.com/andersfylling/disgord"
"github.com/bwmarrin/discordgo"
)

type Config struct {
Expand All @@ -16,43 +11,16 @@ type Config struct {
}

type Context struct {
Client *disgord.Client
Config *Config
}

// This type implements the http.RoundTripper interface
type LimitedRoundTripper struct {
Proxied http.RoundTripper
Session *discordgo.Session
Config *Config
}

func (lrt LimitedRoundTripper) RoundTrip(req *http.Request) (res *http.Response, e error) {
// Do "before sending requests" actions here.
fmt.Printf("Sending request to %v\n", req.URL)

// Send the request, get the response (or the error)
res, e = lrt.Proxied.RoundTrip(req)

if res != nil && res.StatusCode == 429 {
retryAfter := res.Header.Get("X-RateLimit-Reset-After")
if retryAfter == "" {
retryAfter = res.Header.Get("Retry-After")
}

dur, _ := strconv.Atoi(retryAfter)
time.Sleep(time.Duration(dur) * time.Millisecond)

return lrt.RoundTrip(req)
func (c *Config) Client(version string) (*Context, error) {
session, err := discordgo.New(c.Token)
session.UserAgent = "discord-terraform/" + version
if err != nil {
return nil, err
}

return
}

func (c *Config) Client() (*Context, error) {
httpClient := &http.Client{Transport: LimitedRoundTripper{http.DefaultTransport}}
client := disgord.New(disgord.Config{
BotToken: c.Token,
HTTPClient: httpClient,
})

return &Context{Client: client, Config: c}, nil
return &Context{Config: c, Session: session}, nil
}
42 changes: 42 additions & 0 deletions discord/data_source_discord_color_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package discord

import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"testing"
)

func TestAccDatasourceDiscordColor(t *testing.T) {
name := "data.discord_color.example"
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: providerFactories,
Steps: []resource.TestStep{
{
Config: testAccDatasourceDiscordColorRGB,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
name, "dec", "203569"),
),
},
{
Config: testAccDatasourceDiscordColorHex,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
name, "dec", "203569"),
),
},
},
})
}

const testAccDatasourceDiscordColorHex = `
data "discord_color" "example" {
hex = "#031b31"
}
`

const testAccDatasourceDiscordColorRGB = `
data "discord_color" "example" {
rgb = "rgb(3, 27, 49)"
}
`
29 changes: 29 additions & 0 deletions discord/data_source_discord_local_image_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package discord

import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"testing"
)

func TestAccDatasourceDiscordLocalImage(t *testing.T) {
name := "data.discord_local_image.example"
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: providerFactories,
Steps: []resource.TestStep{
{
Config: testAccDatasourceDiscordLocalImage,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(name, "file", "provider.go"),
resource.TestCheckResourceAttrSet(name, "data_uri"),
),
},
},
})
}

const testAccDatasourceDiscordLocalImage = `
data "discord_local_image" "example" {
file = "provider.go"
}
`
39 changes: 21 additions & 18 deletions discord/data_source_discord_member.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package discord

import (
"fmt"
"github.com/bwmarrin/discordgo"

"github.com/andersfylling/disgord"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"golang.org/x/net/context"
Expand All @@ -25,14 +25,13 @@ func dataSourceDiscordMember() *schema.Resource {
},
"username": {
ExactlyOneOf: []string{"user_id", "username"},
RequiredWith: []string{"username", "discriminator"},
Type: schema.TypeString,
Optional: true,
},
"discriminator": {
RequiredWith: []string{"username", "discriminator"},
Type: schema.TypeString,
Optional: true,
Type: schema.TypeString,
Optional: true,
Deprecated: "Discriminator is being deprecated by Discord. Only use this if there are users who haven't migrated their username.",
},
"joined_at": {
Type: schema.TypeString,
Expand Down Expand Up @@ -66,34 +65,36 @@ func dataSourceDiscordMember() *schema.Resource {

func dataSourceMemberRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
var diags diag.Diagnostics
var member *disgord.Member
var member *discordgo.Member
var memberErr error
client := m.(*Context).Client
serverId := getId(d.Get("server_id").(string))
client := m.(*Context).Session
serverId := d.Get("server_id").(string)

if v, ok := d.GetOk("user_id"); ok {
member, memberErr = client.Guild(serverId).Member(getId(v.(string))).Get()

member, memberErr = client.GuildMember(serverId, v.(string), discordgo.WithContext(ctx))
}

if v, ok := d.GetOk("username"); ok {
username := v.(string)
discriminator := d.Get("discriminator").(string)

members, err := client.Guild(serverId).GetMembers(&disgord.GetMembers{Limit: 0})
members, err := client.GuildMembersSearch(serverId, username, 1, discordgo.WithContext(ctx))
if err != nil {
return diag.Errorf("Failed to fetch members for %s: %s", serverId.String(), err.Error())
return diag.Errorf("Failed to fetch members for %s: %s", serverId, err.Error())
}

discriminator := d.Get("discriminator").(string)
memberErr = fmt.Errorf("failed to find member by name#discriminator: %s#%s", username, discriminator)
for _, m := range members {
if m.User.Username == username && m.User.Discriminator.String() == discriminator {
if m.User.Username == username && m.User.Discriminator == discriminator {
member = m
memberErr = nil
break
}
}
}

if memberErr != nil {
return diag.FromErr(memberErr)
}
d.Set("in_server", memberErr == nil)
if memberErr != nil {
d.Set("joined_at", nil)
Expand All @@ -108,12 +109,14 @@ func dataSourceMemberRead(ctx context.Context, d *schema.ResourceData, m interfa

roles := make([]string, 0, len(member.Roles))
for _, r := range member.Roles {
roles = append(roles, r.String())
roles = append(roles, r)
}
if member.PremiumSince == nil {
d.Set("premium_since", nil)
}

d.SetId(member.User.ID.String())
d.SetId(member.User.ID)
d.Set("joined_at", member.JoinedAt.String())
d.Set("premium_since", member.PremiumSince.String())
d.Set("roles", roles)
d.Set("username", member.User.Username)
d.Set("discriminator", member.User.Discriminator)
Expand Down
64 changes: 64 additions & 0 deletions discord/data_source_discord_member_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package discord

import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"os"
"testing"
)

func TestAccDatasourceDiscordMember(t *testing.T) {
testServerID := os.Getenv("DISCORD_TEST_SERVER_ID")
testUserID := os.Getenv("DISCORD_TEST_USER_ID")
testUsername := os.Getenv("DISCORD_TEST_USERNAME")
if testServerID == "" || testUserID == "" || testUsername == "" {
t.Skip("DISCORD_TEST_SERVER_ID, DISCORD_TEST_USER_ID, and DISCORD_TEST_USERNAME envvars must be set for acceptance tests")
}

name := "data.discord_member.example"
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: providerFactories,
Steps: []resource.TestStep{
{
Config: testAccDatasourceDiscordMemberUserID(testServerID, testUserID),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(name, "server_id", testServerID),
resource.TestCheckResourceAttr(name, "user_id", testUserID),
resource.TestCheckResourceAttrSet(name, "joined_at"),
resource.TestCheckResourceAttrSet(name, "avatar"),
resource.TestCheckResourceAttrSet(name, "roles.#"),
resource.TestCheckResourceAttr(name, "in_server", "true"),
),
},
{
Config: testAccDatasourceDiscordMemberUsername(testServerID, testUsername),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(name, "server_id", testServerID),
resource.TestCheckResourceAttr(name, "username", testUsername),
resource.TestCheckResourceAttrSet(name, "joined_at"),
resource.TestCheckResourceAttrSet(name, "avatar"),
resource.TestCheckResourceAttrSet(name, "roles.#"),
resource.TestCheckResourceAttr(name, "in_server", "true"),
),
},
},
})
}

func testAccDatasourceDiscordMemberUserID(serverId string, userID string) string {
return fmt.Sprintf(`
data "discord_member" "example" {
server_id = "%[1]s"
user_id = "%[2]s"
}`, serverId, userID)
}

func testAccDatasourceDiscordMemberUsername(serverId string, username string) string {
return fmt.Sprintf(`
data "discord_member" "example" {
server_id = "%[1]s"
username = "%[2]s"
discriminator = "0"
}`, serverId, username)
}
19 changes: 5 additions & 14 deletions discord/data_source_discord_permission.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package discord
import (
"context"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"strconv"

"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
Expand Down Expand Up @@ -83,19 +83,10 @@ func dataSourceDiscordPermission() *schema.Resource {
}
for k := range permissions {
schemaMap[k] = &schema.Schema{
Optional: true,
Type: schema.TypeString,
Default: "unset",
ValidateDiagFunc: func(v interface{}, path cty.Path) (diags diag.Diagnostics) {
str := v.(string)
allowed := []string{"allow", "unset", "deny"}

if contains(allowed, str) {
return diags
} else {
return append(diags, diag.Errorf("%s is not an allowed value. Pick one of: allowed, unset, deny", str)...)
}
},
Optional: true,
Type: schema.TypeString,
Default: "unset",
ValidateFunc: validation.StringInSlice([]string{"allow", "unset", "deny"}, false),
}
}

Expand Down
49 changes: 49 additions & 0 deletions discord/data_source_discord_permission_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package discord

import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"testing"
)

func TestAccDatasourceDiscordPermission(t *testing.T) {
name := "data.discord_permission.example"
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProviderFactories: providerFactories,
Steps: []resource.TestStep{
{
Config: testAccDatasourceDiscordPermissionSimple,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(name, "administrator", "allow"),
resource.TestCheckResourceAttr(name, "allow_bits", "8"),
),
},
{
Config: testAccDatasourceDiscordPermissionComplex,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(name, "send_messages", "allow"),
resource.TestCheckResourceAttr(name, "embed_links", "allow"),
resource.TestCheckResourceAttr(name, "allow_bits", "18432"),
resource.TestCheckResourceAttr(name, "speak", "deny"),
resource.TestCheckResourceAttr(name, "change_nickname", "deny"),
resource.TestCheckResourceAttr(name, "deny_bits", "69206016"),
),
},
},
})
}

const testAccDatasourceDiscordPermissionSimple = `
data "discord_permission" "example" {
administrator = "allow"
}
`

const testAccDatasourceDiscordPermissionComplex = `
data "discord_permission" "example" {
send_messages = "allow"
embed_links = "allow"
speak = "deny"
change_nickname = "deny"
}
`
Loading

0 comments on commit eca997a

Please sign in to comment.