From adc5b70ffa285ac1d319c2862a5cc8b4058aee21 Mon Sep 17 00:00:00 2001 From: nitroflap Date: Fri, 18 Jun 2021 19:14:02 +0300 Subject: [PATCH] Fix components unmarshaling --- components.go | 39 +++++++++++++++++++++++++++++++++++---- message.go | 2 +- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/components.go b/components.go index 9c4ca99bd..0e3b27873 100644 --- a/components.go +++ b/components.go @@ -19,6 +19,37 @@ type MessageComponent interface { Type() ComponentType } +type UnmarshableMessageComponent struct { + MessageComponent +} + +func (umc *UnmarshableMessageComponent) UnmarshalJSON(src []byte) (err error) { + var v struct { + Type ComponentType `json:"type"` + } + err = json.Unmarshal(src, &v) + if err != nil { + return + } + + var data MessageComponent + switch v.Type { + case ActionsRowComponent: + v := ActionsRow{} + err = json.Unmarshal(src, &v) + data = v + case ButtonComponent: + v := Button{} + err = json.Unmarshal(src, &v) + data = v + } + if err != nil { + return + } + umc.MessageComponent = data + return +} + // ActionsRow is a container for components within one row. type ActionsRow struct { Components []MessageComponent `json:"components"` @@ -26,14 +57,14 @@ type ActionsRow struct { // MarshalJSON is a method for marshaling ActionsRow to a JSON object. func (r ActionsRow) MarshalJSON() ([]byte, error) { - type actionRow ActionsRow + type actionsRow ActionsRow return json.Marshal(struct { - actionRow + actionsRow Type ComponentType `json:"type"` }{ - actionRow: actionRow(r), - Type: r.Type(), + actionsRow: actionsRow(r), + Type: r.Type(), }) } diff --git a/message.go b/message.go index 25fad0460..8fabdf1f4 100644 --- a/message.go +++ b/message.go @@ -81,7 +81,7 @@ type Message struct { Attachments []*MessageAttachment `json:"attachments"` // A list of components attached to the message. - Components []MessageComponent `json:"components"` + Components []UnmarshableMessageComponent `json:"components"` // A list of embeds present in the message. Multiple // embeds can currently only be sent by webhooks.