slack-go / slack

Slack API in Go, originally by @nlopes; Maintainers needed, contact @parsley42
https://pkg.go.dev/github.com/slack-go/slack
BSD 2-Clause "Simplified" License
4.64k stars 1.13k forks source link

How to iterate over MsgOptionBlocks elements? #1111

Open JinoArch opened 1 year ago

JinoArch commented 1 year ago

Hello I was trying to create a block message where I want to dynamically set a MsgBlock to sent over to the channel. Like below

for _, ami := range getAmiList {
        actionBlock = slack.NewActionBlock(ami, chooseBtnEle)

        msg = slack.MsgOptionBlocks(
            headerSection,
            fieldsSection,
            actionBlock,
        )
    }

I am not able to iterate and create blocks with each ami details in MsgOptionBlocks section . Tried append but it only works with slices, not sure how to iterate and get all ami section blocks. any help is appreciated

The output I am getting is something like this in slack:

APP BOT
---------
<blank> - <button>

expecting something like this in slack:

APP BOT
----------
ami1 - <button>
ami2 - <button>
.
.
amiN - <button>
mtintes commented 1 year ago

@JinoArch I am not sure what you code looks like, or what AMI is supposed to be but you make a []slack.Blocks and store the actionBlocks using append and then append them to the MsgOptionBlocks using the spread operator.

getAmiList := []ami{
        {
            text: "1",
        },
        {
            text: "2",
        },
    }

    var blocks []slack.Block

    for _, ami := range getAmiList {

        newBlock := slack.NewSectionBlock(&slack.TextBlockObject{
            Text: ami.text,
            Type: "mrkdwn",
        }, nil, slack.NewAccessory(
            slack.NewButtonBlockElement("button", ami.text, &slack.TextBlockObject{
                Text: ami.text,
                Type: "plain_text",
            })),
        )

        blocks = append(blocks, *newBlock)
    }

    header := slack.NewSectionBlock(&slack.TextBlockObject{
        Type: "mrkdwn",
        Text: "header",
    }, nil, nil)

    msgBlocks := []slack.Block{
        header,
    }

    msgBlocks = append(msgBlocks, blocks...)

    message := slack.MsgOptionBlocks(msgBlocks...)

    channelID, timestamp, err := api.PostMessage(channel, message)

Is that what you are looking for?