Selaa lähdekoodia

Add MessageComponentFromJSON

Carson Hoffman 3 vuotta sitten
vanhempi
commit
55f4934ba7
1 muutettua tiedostoa jossa 15 lisäystä ja 10 poistoa
  1. 15 10
      components.go

+ 15 - 10
components.go

@@ -2,6 +2,7 @@ package discordgo
 
 import (
 	"encoding/json"
+	"fmt"
 )
 
 // ComponentType is type of component.
@@ -34,22 +35,26 @@ func (umc *unmarshalableMessageComponent) UnmarshalJSON(src []byte) error {
 		return err
 	}
 
-	var data MessageComponent
 	switch v.Type {
 	case ActionsRowComponent:
-		v := ActionsRow{}
-		err = json.Unmarshal(src, &v)
-		data = v
+		umc.MessageComponent = &ActionsRow{}
 	case ButtonComponent:
-		v := Button{}
-		err = json.Unmarshal(src, &v)
-		data = v
+		umc.MessageComponent = &Button{}
+	case SelectMenuComponent:
+		umc.MessageComponent = &SelectMenu{}
+	default:
+		return fmt.Errorf("unknown component type: %d", v.Type)
 	}
+	return json.Unmarshal(src, umc.MessageComponent)
+}
+
+func MessageComponentFromJSON(b []byte) (MessageComponent, error) {
+	var u unmarshalableMessageComponent
+	err := u.UnmarshalJSON(b)
 	if err != nil {
-		return err
+		return nil, fmt.Errorf("failed to unmarshal into MessageComponent: %w", err)
 	}
-	umc.MessageComponent = data
-	return err
+	return u.MessageComponent, nil
 }
 
 // ActionsRow is a container for components within one row.