Skip to content
This repository has been archived by the owner on Sep 17, 2024. It is now read-only.

Commit

Permalink
增加可配置的消息模板 (#25)
Browse files Browse the repository at this point in the history
增加可配置的消息模板
  • Loading branch information
indes authored Dec 17, 2019
2 parents 45576ba + ee354e3 commit 643d178
Show file tree
Hide file tree
Showing 3 changed files with 174 additions and 85 deletions.
110 changes: 34 additions & 76 deletions bot/service.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package bot

import (
"bytes"
"fmt"
strip "github.com/grokify/html-strip-tags-go"
"log"
"strings"

"github.com/indes/flowerss-bot/config"
"github.com/indes/flowerss-bot/model"
tb "gopkg.in/tucnak/telebot.v2"
"log"
"regexp"
"strings"
)

func FeedForChannelRegister(m *tb.Message, url string, channelMention string) {
Expand Down Expand Up @@ -92,84 +92,42 @@ func SendError(c *tb.Chat) {
func BroadNews(source *model.Source, subs []model.Subscribe, contents []model.Content) {

log.Printf("Source Title: <%s> Subscriber: %d New Contents: %d", source.Title, len(subs), len(contents))
var u tb.User
var message string
var buf []byte
wb := bytes.NewBuffer(buf)
for _, content := range contents {
for _, sub := range subs {
var disableNotification bool
if sub.EnableNotification == 1 {
disableNotification = false
} else {
disableNotification = true
}

u.ID = int(sub.UserID)

previewText := ""
previewText := trimDescription(content.Description, config.PreviewText)

if config.PreviewText > 0 {
contentDesc := strings.Trim(
strip.StripTags(
regexp.MustCompile(`\n+`).ReplaceAllLiteralString(
strings.ReplaceAll(
regexp.MustCompile(`<br(| /)>`).ReplaceAllString(content.Description, "<br>"),
"<br>", "\n"),
"\n")),
"\n")

contentDescRune := []rune(contentDesc)

previewText += "\n<b>---------- Preview ----------</b>\n"
if len(contentDescRune) > config.PreviewText {
previewText += string(contentDescRune[0:config.PreviewText])
} else {
previewText += contentDesc
}
previewText += "\n<b>-----------------------------</b>"
for _, sub := range subs {
tpldata := &config.TplData{
SourceTitle: source.Title,
ContentTitle: content.Title,
RawLink: content.RawLink,
PreviewText: previewText,
TelegraphURL: content.TelegraphUrl,
EnableTelegraph: sub.EnableTelegraph == 1 && content.TelegraphUrl != "",
}

if sub.EnableTelegraph == 1 && content.TelegraphUrl != "" {
message = `
<b>%s</b>%s
%s | <a href="%s">Telegraph</a> | <a href="%s">原文</a>
`
message = fmt.Sprintf(message, source.Title, previewText, content.Title, content.TelegraphUrl, content.RawLink)
_, err := B.Send(&u, message, &tb.SendOptions{
DisableWebPagePreview: false,
ParseMode: tb.ModeHTML,
DisableNotification: disableNotification,
})

if err != nil {
log.Println(err)
if strings.Contains(err.Error(), "Forbidden") {
log.Printf("Unsubscribe UserID:%d SourceID:%d", sub.UserID, sub.SourceID)
_ = sub.Unsub()
}
}
wb.Reset()
if err := config.MessageTpl.Execute(wb, tpldata); err != nil {
log.Println(err)
return
}

} else {
message = `
<b>%s</b>%s
<a href="%s">%s</a>
`
message = fmt.Sprintf(message, source.Title, previewText, content.RawLink, content.Title)

_, err := B.Send(&u, message, &tb.SendOptions{
DisableWebPagePreview: true,
ParseMode: tb.ModeHTML,
DisableNotification: disableNotification,
})

if err != nil {
log.Println(err)
if err != nil {
log.Println(err)
if strings.Contains(err.Error(), "Forbidden") {
log.Printf("Unsubscribe UserID:%d SourceID:%d", sub.UserID, sub.SourceID)
_ = sub.Unsub()
}
}
u := &tb.User{
ID: int(sub.UserID),
}
o := &tb.SendOptions{
DisableWebPagePreview: false,
ParseMode: config.MessageMode,
DisableNotification: sub.EnableNotification != 1,
}
msg := strings.TrimSpace(string(wb.Bytes()))
if _, err := B.Send(u, msg, o); err != nil {
log.Println(err)
if strings.Contains(err.Error(), "Forbidden") {
log.Printf("Unsubscribe UserID:%d SourceID:%d", sub.UserID, sub.SourceID)
_ = sub.Unsub()
}
}
}
Expand Down
29 changes: 29 additions & 0 deletions bot/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package bot

import (
"regexp"
"strings"

strip "github.com/grokify/html-strip-tags-go"
)

func trimDescription(desc string, limit int) string {
if limit == 0 {
return ""
}
desc = strings.Trim(
strip.StripTags(
regexp.MustCompile(`\n+`).ReplaceAllLiteralString(
strings.ReplaceAll(
regexp.MustCompile(`<br(| /)>`).ReplaceAllString(desc, "<br>"),
"<br>", "\n"),
"\n")),
"\n")

contentDescRune := []rune(desc)
if len(contentDescRune) > limit {
desc = string(contentDescRune[:limit])
}

return desc
}
120 changes: 111 additions & 9 deletions config/autoload.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package config

import (
"bytes"
"flag"
"fmt"
"github.com/spf13/viper"
tb "gopkg.in/tucnak/telebot.v2"
"log"
"os"
"path"
"strconv"
"strings"
"text/template"
)

var (
Expand All @@ -21,6 +25,29 @@ var (
EnableMysql bool
UpdateInterval int = 10
ErrorThreshold uint = 100
MessageTpl *template.Template
MessageMode tb.ParseMode
)

const (
logo = `
__ _
/ _| | _____ _____ _ __ ___ ___
| |_| |/ _ \ \ /\ / / _ \ '__/ __/ __|
| _| | (_) \ V V / __/ | \__ \__ \
|_| |_|\___/ \_/\_/ \___|_| |___/___/
`
defaultMessageTplMode = "md"
defaultMessageTpl = `** {{.SourceTitle}} **{{ if .PreviewText }}
---------- Preview ----------
{{.PreviewText}}
-----------------------------
{{- end}}{{if .EnableTelegraph}}
{{.ContentTitle}} [Telegraph]({{.TelegraphURL}}) | [原文]({{.RawLink}})
{{- else }}
[{{.ContentTitle}}]({{.RawLink}})
{{- end }}`
)

type MysqlConfig struct {
Expand All @@ -31,24 +58,91 @@ type MysqlConfig struct {
DB string
}

func init() {
type TplData struct {
SourceTitle string
ContentTitle string
RawLink string
PreviewText string
TelegraphURL string
EnableTelegraph bool
}

logo := `
__ _
/ _| | _____ _____ _ __ ___ ___
| |_| |/ _ \ \ /\ / / _ \ '__/ __/ __|
| _| | (_) \ V V / __/ | \__ \__ \
|_| |_|\___/ \_/\_/ \___|_| |___/___/
func validateTPL() {
testData := []TplData{
TplData{
"RSS 源标识 - 无预览无telegraph的消息",
"这是标题",
"https://www.github.com/",
"",
"",
false,
},
TplData{
"RSS源标识 - 有预览无telegraph的消息",
"这是标题",
"https://www.github.com/",
"这里是很长很长很长的消息预览字数补丁紫薯补丁紫薯补丁紫薯补丁紫薯补丁",
"",
false,
},
TplData{
"RSS源标识 - 有预览有telegraph的消息",
"这是标题",
"https://www.github.com/",
"这里是很长很长很长的消息预览字数补丁紫薯补丁紫薯补丁紫薯补丁紫薯补丁",
"https://telegra.ph/markdown-07-07",
true,
},
}

var buf []byte
w := bytes.NewBuffer(buf)

for _, d := range testData {
w.Reset()
fmt.Println("\n////////////////////////////////////////////")
if err := MessageTpl.Execute(os.Stdout, d); err != nil {
log.Fatal(err)
}
}
fmt.Println("\n////////////////////////////////////////////")
}

func initTPL() {

var tplMsg string
if viper.IsSet("message_tpl") {
tplMsg = viper.GetString("message_tpl")
} else {
tplMsg = defaultMessageTpl
}
MessageTpl = template.Must(template.New("message").Parse(tplMsg))

if viper.IsSet("message_mode") {
switch strings.ToLower(viper.GetString("message_mode")) {
case "md", "markdown":
MessageMode = tb.ModeMarkdown
case "html":
MessageMode = tb.ModeHTML
default:
MessageMode = tb.ModeDefault
}
} else {
MessageMode = tb.ModeMarkdown
}

}

func init() {

`
fmt.Println(logo)
telegramTokenCli := flag.String("b", "", "Telegram Bot Token")
telegraphTokenCli := flag.String("t", "", "Telegraph API Token")
previewTextCli := flag.Int("p", 0, "Preview Text Length")
dbPathCli := flag.String("dbpath", "", "SQLite DB Path")
errorThresholdCli := flag.Int("threshold", 0, "Error Threshold")
socks5Cli := flag.String("s", "", "Socks5 Proxy")
intervalCli := flag.Int("i", 0, "Update Interval")
testTpl := flag.Bool("testtpl", false, "Test Template")
flag.Parse()

projectName := "flowerss-bot"
Expand All @@ -63,6 +157,14 @@ func init() {
panic(fmt.Errorf("Fatal error config file: %s", err))
}

initTPL()
if *testTpl {
validateTPL()
os.Exit(0)
}

fmt.Println(logo)

if *telegramTokenCli == "" {
BotToken = viper.GetString("bot_token")

Expand Down

0 comments on commit 643d178

Please sign in to comment.