1
0
Fork 0

Move SplitTextAtChunk function into a separate package

This commit is contained in:
Daniele Tricoli 2022-03-12 20:26:19 +01:00
parent 7fb169443c
commit 0059989510
2 changed files with 26 additions and 21 deletions

View File

@ -14,6 +14,8 @@ import (
"github.com/cking/go-mastodon" "github.com/cking/go-mastodon"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"noa.mornie.org/eriol/telegram-group2mastodon/utils"
) )
const ( const (
@ -77,7 +79,7 @@ the specified Mastodon account.`,
text := update.Message.Text text := update.Message.Text
in_reply_to := "" in_reply_to := ""
for _, message := range splitTextAtChunk(text, max_characters) { for _, message := range utils.SplitTextAtChunk(text, max_characters) {
status, err := c.PostStatus(context.Background(), &mastodon.Toot{ status, err := c.PostStatus(context.Background(), &mastodon.Toot{
Status: message, Status: message,
Visibility: parseMastodonVisibility(os.Getenv(MASTODON_TOOT_VISIBILITY)), Visibility: parseMastodonVisibility(os.Getenv(MASTODON_TOOT_VISIBILITY)),
@ -201,23 +203,3 @@ func parseTelegramChatID(s string) int64 {
return r return r
} }
// Split text in chunks of almost specified size.
func splitTextAtChunk(text string, size int) []string {
words := strings.SplitN(text, " ", -1)
chunks := []string{}
var message string
for _, word := range words {
if len(message+" "+word) > size {
chunks = append(chunks, message)
message = word
continue
}
message += " " + word
}
chunks = append(chunks, message)
return chunks
}

23
utils/text.go Normal file
View File

@ -0,0 +1,23 @@
package utils
import "strings"
// Split text in chunks of almost specified size.
func SplitTextAtChunk(text string, size int) []string {
words := strings.SplitN(text, " ", -1)
chunks := []string{}
var message string
for _, word := range words {
if len(message+" "+word) > size {
chunks = append(chunks, message)
message = word
continue
}
message += " " + word
}
chunks = append(chunks, message)
return chunks
}