0

I'm creating a telegram bot using Golang, and I need some advice on how to retrieve a multiline string value from function in Golang, that has same logic like this Python string

answer = """1 John 95
2 Sam 89
3 Mike 72"""

I have a function that creates a MongoDB request that gets me a data in bson.M datatype. And after that I need to send this queried data to a user as a single string value using this form:

msg := tgbotapi.NewMessage(
    update.Message.Chat_ID,
    answer,
)
bot.Send(msg)

I don't really know how to transform this bson.M data into a single multiline string.

bson.M response that I get from the function:

[map[_id:ObjectID("62a4acf2a494a2814238c6e1") bandMember:John name:School12 points:95] 
map[_id:ObjectID("62a4acf2a494a2814238c6e2") bandMember:Sam name:School15 points:89] 
map[_id:ObjectID("62a4acf2a494a2814238c6e3") bandMember:Mike name:School7 points:72]]

And I have to insert it in a string variable of "answer" (see above example)

Thanks in advance!

4
  • No, the problem is not about indexing. I need to collect all the data into a string variable, in order to insert it in a one single bot "answer" response with all this data (code form above). In this case, I don't want to make three different messages sending to user by looping each element and inserting in into a new message.
    – LAPOVETS
    Jun 12, 2022 at 17:16
  • 2
    What have you tried? What problems do you have? Query the documents, use a loop and build the string either by concatenating or using a more efficient and sophisticated solution like strings.Builder. Post a minimal reproducible example.
    – icza
    Jun 12, 2022 at 17:21
  • Please provide enough code so others can better understand or reproduce the problem.
    – Community Bot
    Jun 12, 2022 at 22:52
  • Thank you guys for your time. The strings.Builder led me to the correct way to solve this problem. :)
    – LAPOVETS
    Jun 13, 2022 at 14:07

1 Answer 1

0

Loop through the documents and sprintf a line for each document. Join the lines with newline to get the final result.

var lines []string
for i, m := range data {
    lines = append(lines, fmt.Sprintf("%d %s %d", i+1, m["bandMember"], m["points"]))
}
result := strings.Join(lines, "\n")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.