95 lines
2.1 KiB
Go
95 lines
2.1 KiB
Go
package bot
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"strconv"
|
|
"unicode/utf8"
|
|
|
|
"github.com/pyed/transmission"
|
|
tgbotapi "gopkg.in/telegram-bot-api.v4"
|
|
"transmission-telegram/internal/config"
|
|
)
|
|
|
|
// sendMessage sends a message to Telegram, splitting if necessary
|
|
func sendMessage(bot *tgbotapi.BotAPI, chatID int64, text string, markdown bool) int {
|
|
// Set typing action
|
|
action := tgbotapi.NewChatAction(chatID, tgbotapi.ChatTyping)
|
|
bot.Send(action)
|
|
|
|
// Check the rune count, telegram is limited to 4096 chars per message
|
|
msgRuneCount := utf8.RuneCountInString(text)
|
|
|
|
var lastMsgID int
|
|
|
|
// Split message if too long
|
|
for msgRuneCount > config.TelegramMaxMessageLength {
|
|
stop := config.TelegramMaxMessageLength - 1
|
|
|
|
// Find the last newline before the limit
|
|
for stop > 0 && text[stop] != '\n' {
|
|
stop--
|
|
}
|
|
|
|
// If no newline found, just cut at the limit
|
|
if stop == 0 {
|
|
stop = config.TelegramMaxMessageLength - 1
|
|
}
|
|
|
|
chunk := text[:stop]
|
|
text = text[stop:]
|
|
msgRuneCount = utf8.RuneCountInString(text)
|
|
|
|
msg := tgbotapi.NewMessage(chatID, chunk)
|
|
msg.DisableWebPagePreview = true
|
|
if markdown {
|
|
msg.ParseMode = tgbotapi.ModeMarkdown
|
|
}
|
|
|
|
if resp, err := bot.Send(msg); err == nil {
|
|
lastMsgID = resp.MessageID
|
|
}
|
|
}
|
|
|
|
// Send remaining text
|
|
if len(text) > 0 {
|
|
msg := tgbotapi.NewMessage(chatID, text)
|
|
msg.DisableWebPagePreview = true
|
|
if markdown {
|
|
msg.ParseMode = tgbotapi.ModeMarkdown
|
|
}
|
|
|
|
if resp, err := bot.Send(msg); err == nil {
|
|
lastMsgID = resp.MessageID
|
|
}
|
|
}
|
|
|
|
return lastMsgID
|
|
}
|
|
|
|
// parseTorrentIDs parses torrent IDs from tokens
|
|
func parseTorrentIDs(tokens []string) ([]int, []string) {
|
|
var ids []int
|
|
var errors []string
|
|
|
|
for _, token := range tokens {
|
|
if id, err := strconv.Atoi(token); err == nil {
|
|
ids = append(ids, id)
|
|
} else {
|
|
errors = append(errors, fmt.Sprintf("%s is not a number", token))
|
|
}
|
|
}
|
|
|
|
return ids, errors
|
|
}
|
|
|
|
// formatTorrentList formats a list of torrents as a simple list
|
|
func formatTorrentList(torrents []*transmission.Torrent) string {
|
|
var buf bytes.Buffer
|
|
for _, torrent := range torrents {
|
|
buf.WriteString(fmt.Sprintf("<%d> %s\n", torrent.ID, torrent.Name))
|
|
}
|
|
return buf.String()
|
|
}
|
|
|