Add MessageComponentFromJSON

This commit is contained in:
Carson Hoffman 2021-12-02 15:07:38 -05:00
parent fd6228c0d5
commit 55f4934ba7
No known key found for this signature in database
GPG key ID: 05B660CB452C657F

View file

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