mirror of
https://github.com/woodchen-ink/Q58Bot.git
synced 2025-07-18 05:42:06 +08:00
(服务稳定性优化与功能增强)
This commit is contained in:
parent
5d05e0a343
commit
f27f87b708
17
core/init.go
17
core/init.go
@ -40,6 +40,8 @@ func mustParseInt64(s string) (int64, error) {
|
||||
return value, nil
|
||||
}
|
||||
func Init() error {
|
||||
var err error
|
||||
|
||||
// 从环境变量获取 BOT_TOKEN
|
||||
BOT_TOKEN = os.Getenv("BOT_TOKEN")
|
||||
if BOT_TOKEN == "" {
|
||||
@ -48,14 +50,25 @@ func Init() error {
|
||||
|
||||
// 从环境变量获取 ADMIN_ID
|
||||
adminIDStr := os.Getenv("ADMIN_ID")
|
||||
var err error
|
||||
ADMIN_ID, err = mustParseInt64(adminIDStr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Invalid ADMIN_ID: %v", err)
|
||||
}
|
||||
|
||||
// 设置数据库文件路径
|
||||
// 初始化 Bot API
|
||||
Bot, err = tgbotapi.NewBotAPI(BOT_TOKEN)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建 Bot API 失败: %v", err)
|
||||
}
|
||||
|
||||
log.Printf("账户已授权 %s", Bot.Self.UserName)
|
||||
|
||||
// 初始化数据库
|
||||
DB_FILE = filepath.Join("/app/data", "q58.db")
|
||||
_, err = NewDatabase()
|
||||
if err != nil {
|
||||
return fmt.Errorf("初始化数据库失败: %v", err)
|
||||
}
|
||||
|
||||
// 从环境变量中读取调试模式设置
|
||||
DEBUG_MODE = os.Getenv("DEBUG_MODE") == "true"
|
||||
|
6
main.go
6
main.go
@ -16,12 +16,10 @@ func main() {
|
||||
log.Fatalf("Failed to initialize service: %v", err)
|
||||
}
|
||||
|
||||
go binance.RunBinance()
|
||||
|
||||
err = service.RunMessageHandler()
|
||||
if err != nil {
|
||||
log.Fatalf("Error in RunMessageHandler: %v", err)
|
||||
}
|
||||
|
||||
go binance.RunBinance()
|
||||
|
||||
select {}
|
||||
}
|
||||
|
@ -10,6 +10,7 @@ import (
|
||||
|
||||
"github.com/adshao/go-binance/v2"
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/woodchen-ink/Q58Bot/core"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -110,6 +111,13 @@ func sendPriceUpdate() {
|
||||
func RunBinance() {
|
||||
log.Println("Starting Binance service...")
|
||||
|
||||
// 初始化必要的变量
|
||||
botToken = core.BOT_TOKEN
|
||||
bot = core.Bot
|
||||
chatID = core.ChatID
|
||||
symbols = core.Symbols
|
||||
singaporeTZ = core.SingaporeTZ
|
||||
|
||||
// 立即发送一次价格更新
|
||||
sendPriceUpdate()
|
||||
|
||||
|
@ -1,12 +1,12 @@
|
||||
package link_filter
|
||||
|
||||
// 链接处理
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/woodchen-ink/Q58Bot/core"
|
||||
)
|
||||
@ -18,72 +18,47 @@ type LinkFilter struct {
|
||||
keywords []string
|
||||
whitelist []string
|
||||
linkPattern *regexp.Regexp
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewLinkFilter 创建一个新的LinkFilter实例。这个实例用于过滤链接,且在创建时会初始化数据库连接和链接过滤正则表达式。
|
||||
// 它首先尝试创建一个数据库连接,然后加载链接过滤所需的配置,最后返回一个包含所有初始化设置的LinkFilter实例。
|
||||
// 如果在任何步骤中发生错误,错误将被返回,LinkFilter实例将不会被创建。
|
||||
func NewLinkFilter() (*LinkFilter, error) {
|
||||
// 初始化数据库连接
|
||||
db, err := core.NewDatabase()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 创建LinkFilter实例
|
||||
|
||||
lf := &LinkFilter{
|
||||
db: db,
|
||||
db: db,
|
||||
linkPattern: regexp.MustCompile(`(?i)\b(?:(?:https?://)?(?:(?:www\.)?(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}|(?:t\.me|telegram\.me))(?:/[^\s]*)?)`),
|
||||
}
|
||||
// 编译链接过滤正则表达式
|
||||
lf.linkPattern = regexp.MustCompile(`(?i)\b(?:(?:https?://)?(?:(?:www\.)?(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}|(?:t\.me|telegram\.me))(?:/[^\s]*)?)`)
|
||||
// 从文件中加载额外的链接过滤数据
|
||||
err = lf.LoadDataFromFile()
|
||||
if err != nil {
|
||||
|
||||
if err := lf.LoadDataFromFile(); err != nil {
|
||||
db.Close() // Close the database if loading fails
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return lf, nil
|
||||
}
|
||||
|
||||
// LoadDataFromFile 从文件中加载数据到 LinkFilter 结构体的 keywords 和 whitelist 字段。
|
||||
// 它首先从数据库中获取所有的关键词和白名单条目,如果数据库操作出现错误,它会立即返回错误。
|
||||
// 一旦数据成功加载,它会通过日志记录加载的关键词和白名单条目的数量。
|
||||
// 参数: 无
|
||||
// 返回值: 如果加载过程中发生错误,返回该错误;否则返回 nil。
|
||||
func (lf *LinkFilter) LoadDataFromFile() error {
|
||||
// 从数据库中加载所有关键词到 lf.keywords
|
||||
lf.mu.Lock()
|
||||
defer lf.mu.Unlock()
|
||||
|
||||
var err error
|
||||
lf.keywords, err = lf.db.GetAllKeywords()
|
||||
if err != nil {
|
||||
// 如果发生错误,立即返回
|
||||
return err
|
||||
}
|
||||
|
||||
// 从数据库中加载所有白名单条目到 lf.whitelist
|
||||
lf.whitelist, err = lf.db.GetAllWhitelist()
|
||||
if err != nil {
|
||||
// 如果发生错误,立即返回
|
||||
return err
|
||||
}
|
||||
|
||||
// 记录成功加载的关键词和白名单条目的数量
|
||||
logger.Printf("Loaded %d keywords and %d whitelist entries from database", len(lf.keywords), len(lf.whitelist))
|
||||
|
||||
// 数据加载成功,返回 nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// NormalizeLink 标准化链接地址。
|
||||
//
|
||||
// 该函数接受一个链接字符串,对其进行标准化处理,并返回处理后的链接。
|
||||
// 标准化过程包括移除协议头(http或https)、TrimPrefix去除链接中的斜杠、
|
||||
// 解析URL以获取主机名和路径、将查询参数附加到URL末尾。
|
||||
//
|
||||
// 参数:
|
||||
//
|
||||
// link - 需要被标准化的链接字符串。
|
||||
//
|
||||
// 返回值:
|
||||
//
|
||||
// 标准化后的链接字符串。
|
||||
func (lf *LinkFilter) NormalizeLink(link string) string {
|
||||
// 移除链接中的协议头(http或https)
|
||||
link = regexp.MustCompile(`^https?://`).ReplaceAllString(link, "")
|
||||
@ -109,16 +84,6 @@ func (lf *LinkFilter) NormalizeLink(link string) string {
|
||||
return result
|
||||
}
|
||||
|
||||
// ExtractDomain 从给定的URL字符串中提取域名。
|
||||
// 该函数首先解析URL字符串,然后返回解析得到的主机名,同时将其转换为小写。
|
||||
// 如果URL解析失败,错误信息将被记录,并且函数会返回原始的URL字符串。
|
||||
// 参数:
|
||||
//
|
||||
// urlStr - 待处理的URL字符串。
|
||||
//
|
||||
// 返回值:
|
||||
//
|
||||
// 解析后的主机名,如果解析失败则返回原始的URL字符串。
|
||||
func (lf *LinkFilter) ExtractDomain(urlStr string) string {
|
||||
// 尝试解析给定的URL字符串。
|
||||
parsedURL, err := url.Parse(urlStr)
|
||||
@ -204,9 +169,13 @@ func (lf *LinkFilter) RemoveKeywordsContaining(substring string) ([]string, erro
|
||||
// 检查消息是否包含关键词或者非白名单链接
|
||||
func (lf *LinkFilter) ShouldFilter(text string) (bool, []string) {
|
||||
logger.Printf("Checking text: %s", text)
|
||||
|
||||
lf.mu.RLock()
|
||||
defer lf.mu.RUnlock()
|
||||
|
||||
for _, keyword := range lf.keywords {
|
||||
if strings.Contains(strings.ToLower(text), strings.ToLower(keyword)) {
|
||||
logger.Printf("文字包含关键字: %s", text)
|
||||
logger.Printf("文字包含关键字: %s", keyword)
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
@ -219,16 +188,11 @@ func (lf *LinkFilter) ShouldFilter(text string) (bool, []string) {
|
||||
normalizedLink := lf.NormalizeLink(link)
|
||||
if !lf.IsWhitelisted(normalizedLink) {
|
||||
logger.Printf("链接未列入白名单: %s", normalizedLink)
|
||||
found := false
|
||||
for _, keyword := range lf.keywords {
|
||||
if keyword == normalizedLink {
|
||||
logger.Printf("找到现有关键字: %s", normalizedLink)
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
if !lf.containsKeyword(normalizedLink) {
|
||||
newNonWhitelistedLinks = append(newNonWhitelistedLinks, normalizedLink)
|
||||
lf.AddKeyword(normalizedLink)
|
||||
lf.AddKeyword(normalizedLink) // 注意:这里会修改 lf.keywords,可能需要额外的锁
|
||||
} else {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -238,3 +202,17 @@ func (lf *LinkFilter) ShouldFilter(text string) (bool, []string) {
|
||||
}
|
||||
return false, newNonWhitelistedLinks
|
||||
}
|
||||
|
||||
func (lf *LinkFilter) containsKeyword(link string) bool {
|
||||
for _, keyword := range lf.keywords {
|
||||
if keyword == link {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// 新增 Close 方法
|
||||
func (lf *LinkFilter) Close() error {
|
||||
return lf.db.Close()
|
||||
}
|
||||
|
@ -4,6 +4,7 @@ package service
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
@ -175,3 +176,260 @@ func RunMessageHandler() error {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 下面是辅助函数部分
|
||||
//
|
||||
//
|
||||
//
|
||||
|
||||
const (
|
||||
maxMessageLength = 4000
|
||||
)
|
||||
|
||||
func deleteMessageAfterDelay(bot *tgbotapi.BotAPI, chatID int64, messageID int, delay time.Duration) {
|
||||
go func() {
|
||||
time.Sleep(delay)
|
||||
deleteMsg := tgbotapi.NewDeleteMessage(chatID, messageID)
|
||||
_, err := bot.Request(deleteMsg)
|
||||
if err != nil {
|
||||
log.Printf("删除消息失败 (ChatID: %d, MessageID: %d): %v", chatID, messageID, err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func SendLongMessage(bot *tgbotapi.BotAPI, chatID int64, prefix string, items []string) error {
|
||||
message := prefix + "\n"
|
||||
for i, item := range items {
|
||||
newLine := fmt.Sprintf("%d. %s\n", i+1, item)
|
||||
if len(message)+len(newLine) > maxMessageLength {
|
||||
if err := sendMessage(bot, chatID, message); err != nil {
|
||||
return err
|
||||
}
|
||||
message = ""
|
||||
}
|
||||
message += newLine
|
||||
}
|
||||
|
||||
if message != "" {
|
||||
return sendMessage(bot, chatID, message)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func sendMessage(bot *tgbotapi.BotAPI, chatID int64, text string) error {
|
||||
msg := tgbotapi.NewMessage(chatID, text)
|
||||
_, err := bot.Send(msg)
|
||||
return err
|
||||
}
|
||||
|
||||
func sendErrorMessage(bot *tgbotapi.BotAPI, chatID int64, errMsg string) {
|
||||
sendMessage(bot, chatID, errMsg)
|
||||
}
|
||||
|
||||
func HandleKeywordCommand(bot *tgbotapi.BotAPI, message *tgbotapi.Message, command string, args string, db *core.Database) {
|
||||
args = strings.TrimSpace(args)
|
||||
|
||||
switch command {
|
||||
case "list":
|
||||
handleListKeywords(bot, message, db)
|
||||
case "add":
|
||||
handleAddKeyword(bot, message, args, db)
|
||||
case "delete":
|
||||
handleDeleteKeyword(bot, message, args, db)
|
||||
case "deletecontaining":
|
||||
handleDeleteContainingKeyword(bot, message, args, db)
|
||||
default:
|
||||
sendErrorMessage(bot, message.Chat.ID, "无效的命令或参数。")
|
||||
}
|
||||
}
|
||||
|
||||
func handleListKeywords(bot *tgbotapi.BotAPI, message *tgbotapi.Message, db *core.Database) {
|
||||
keywords, err := db.GetAllKeywords()
|
||||
if err != nil {
|
||||
sendErrorMessage(bot, message.Chat.ID, "获取关键词列表时发生错误。")
|
||||
return
|
||||
}
|
||||
if len(keywords) == 0 {
|
||||
sendMessage(bot, message.Chat.ID, "关键词列表为空。")
|
||||
} else {
|
||||
SendLongMessage(bot, message.Chat.ID, "当前关键词列表:", keywords)
|
||||
}
|
||||
}
|
||||
|
||||
func handleAddKeyword(bot *tgbotapi.BotAPI, message *tgbotapi.Message, keyword string, db *core.Database) {
|
||||
if keyword == "" {
|
||||
sendErrorMessage(bot, message.Chat.ID, "请提供要添加的关键词。")
|
||||
return
|
||||
}
|
||||
|
||||
exists, err := db.KeywordExists(keyword)
|
||||
if err != nil {
|
||||
sendErrorMessage(bot, message.Chat.ID, "检查关键词时发生错误。")
|
||||
return
|
||||
}
|
||||
if !exists {
|
||||
err = db.AddKeyword(keyword)
|
||||
if err != nil {
|
||||
sendErrorMessage(bot, message.Chat.ID, "添加关键词时发生错误。")
|
||||
} else {
|
||||
sendMessage(bot, message.Chat.ID, fmt.Sprintf("关键词 '%s' 已添加。", keyword))
|
||||
}
|
||||
} else {
|
||||
sendMessage(bot, message.Chat.ID, fmt.Sprintf("关键词 '%s' 已存在。", keyword))
|
||||
}
|
||||
}
|
||||
|
||||
func handleDeleteKeyword(bot *tgbotapi.BotAPI, message *tgbotapi.Message, keyword string, db *core.Database) {
|
||||
if keyword == "" {
|
||||
sendErrorMessage(bot, message.Chat.ID, "请提供要删除的关键词。")
|
||||
return
|
||||
}
|
||||
|
||||
err := db.RemoveKeyword(keyword)
|
||||
if err != nil {
|
||||
sendErrorMessage(bot, message.Chat.ID, fmt.Sprintf("删除关键词 '%s' 时发生错误: %v", keyword, err))
|
||||
return
|
||||
}
|
||||
|
||||
exists, err := db.KeywordExists(keyword)
|
||||
if err != nil {
|
||||
sendErrorMessage(bot, message.Chat.ID, fmt.Sprintf("检查关键词 '%s' 是否存在时发生错误: %v", keyword, err))
|
||||
return
|
||||
}
|
||||
|
||||
if !exists {
|
||||
sendMessage(bot, message.Chat.ID, fmt.Sprintf("关键词 '%s' 已成功删除。", keyword))
|
||||
} else {
|
||||
handleSimilarKeywords(bot, message, keyword, db)
|
||||
}
|
||||
}
|
||||
|
||||
func handleSimilarKeywords(bot *tgbotapi.BotAPI, message *tgbotapi.Message, keyword string, db *core.Database) {
|
||||
similarKeywords, err := db.SearchKeywords(keyword)
|
||||
if err != nil {
|
||||
sendErrorMessage(bot, message.Chat.ID, "搜索关键词时发生错误。")
|
||||
return
|
||||
}
|
||||
if len(similarKeywords) > 0 {
|
||||
SendLongMessage(bot, message.Chat.ID, fmt.Sprintf("未能删除关键词 '%s'。\n\n以下是相似的关键词:", keyword), similarKeywords)
|
||||
} else {
|
||||
sendMessage(bot, message.Chat.ID, fmt.Sprintf("未能删除关键词 '%s',且未找到相似的关键词。", keyword))
|
||||
}
|
||||
}
|
||||
|
||||
func handleDeleteContainingKeyword(bot *tgbotapi.BotAPI, message *tgbotapi.Message, substring string, db *core.Database) {
|
||||
if substring == "" {
|
||||
sendErrorMessage(bot, message.Chat.ID, "请提供要删除的子字符串。")
|
||||
return
|
||||
}
|
||||
|
||||
removedKeywords, err := db.RemoveKeywordsContaining(substring)
|
||||
if err != nil {
|
||||
sendErrorMessage(bot, message.Chat.ID, "删除关键词时发生错误。")
|
||||
return
|
||||
}
|
||||
if len(removedKeywords) > 0 {
|
||||
SendLongMessage(bot, message.Chat.ID, fmt.Sprintf("已删除包含 '%s' 的以下关键词:", substring), removedKeywords)
|
||||
} else {
|
||||
sendMessage(bot, message.Chat.ID, fmt.Sprintf("没有找到包含 '%s' 的关键词。", substring))
|
||||
}
|
||||
}
|
||||
|
||||
func HandleWhitelistCommand(bot *tgbotapi.BotAPI, message *tgbotapi.Message, command string, args string, db *core.Database) {
|
||||
args = strings.TrimSpace(args)
|
||||
|
||||
switch command {
|
||||
case "listwhite":
|
||||
handleListWhitelist(bot, message, db)
|
||||
case "addwhite":
|
||||
handleAddWhitelist(bot, message, args, db)
|
||||
case "delwhite":
|
||||
handleDeleteWhitelist(bot, message, args, db)
|
||||
default:
|
||||
sendErrorMessage(bot, message.Chat.ID, "无效的命令或参数。")
|
||||
}
|
||||
}
|
||||
|
||||
func handleListWhitelist(bot *tgbotapi.BotAPI, message *tgbotapi.Message, db *core.Database) {
|
||||
whitelist, err := db.GetAllWhitelist()
|
||||
if err != nil {
|
||||
sendErrorMessage(bot, message.Chat.ID, fmt.Sprintf("获取白名单时发生错误: %v", err))
|
||||
return
|
||||
}
|
||||
if len(whitelist) == 0 {
|
||||
sendMessage(bot, message.Chat.ID, "白名单为空。")
|
||||
} else {
|
||||
SendLongMessage(bot, message.Chat.ID, "白名单域名列表:", whitelist)
|
||||
}
|
||||
}
|
||||
|
||||
func handleAddWhitelist(bot *tgbotapi.BotAPI, message *tgbotapi.Message, domain string, db *core.Database) {
|
||||
if domain == "" {
|
||||
sendErrorMessage(bot, message.Chat.ID, "请提供要添加的域名。")
|
||||
return
|
||||
}
|
||||
|
||||
domain = strings.ToLower(domain)
|
||||
exists, err := db.WhitelistExists(domain)
|
||||
if err != nil {
|
||||
sendErrorMessage(bot, message.Chat.ID, fmt.Sprintf("检查白名单时发生错误: %v", err))
|
||||
return
|
||||
}
|
||||
if exists {
|
||||
sendMessage(bot, message.Chat.ID, fmt.Sprintf("域名 '%s' 已在白名单中。", domain))
|
||||
return
|
||||
}
|
||||
|
||||
err = db.AddWhitelist(domain)
|
||||
if err != nil {
|
||||
sendErrorMessage(bot, message.Chat.ID, fmt.Sprintf("添加到白名单时发生错误: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
exists, err = db.WhitelistExists(domain)
|
||||
if err != nil {
|
||||
sendErrorMessage(bot, message.Chat.ID, fmt.Sprintf("验证添加操作时发生错误: %v", err))
|
||||
return
|
||||
}
|
||||
if exists {
|
||||
sendMessage(bot, message.Chat.ID, fmt.Sprintf("域名 '%s' 已成功添加到白名单。", domain))
|
||||
} else {
|
||||
sendErrorMessage(bot, message.Chat.ID, fmt.Sprintf("未能添加域名 '%s' 到白名单。", domain))
|
||||
}
|
||||
}
|
||||
|
||||
func handleDeleteWhitelist(bot *tgbotapi.BotAPI, message *tgbotapi.Message, domain string, db *core.Database) {
|
||||
if domain == "" {
|
||||
sendErrorMessage(bot, message.Chat.ID, "请提供要删除的域名。")
|
||||
return
|
||||
}
|
||||
|
||||
domain = strings.ToLower(domain)
|
||||
exists, err := db.WhitelistExists(domain)
|
||||
if err != nil {
|
||||
sendErrorMessage(bot, message.Chat.ID, fmt.Sprintf("检查白名单时发生错误: %v", err))
|
||||
return
|
||||
}
|
||||
if !exists {
|
||||
sendMessage(bot, message.Chat.ID, fmt.Sprintf("域名 '%s' 不在白名单中。", domain))
|
||||
return
|
||||
}
|
||||
|
||||
err = db.RemoveWhitelist(domain)
|
||||
if err != nil {
|
||||
sendErrorMessage(bot, message.Chat.ID, fmt.Sprintf("从白名单删除时发生错误: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
exists, err = db.WhitelistExists(domain)
|
||||
if err != nil {
|
||||
sendErrorMessage(bot, message.Chat.ID, fmt.Sprintf("验证删除操作时发生错误: %v", err))
|
||||
return
|
||||
}
|
||||
if !exists {
|
||||
sendMessage(bot, message.Chat.ID, fmt.Sprintf("域名 '%s' 已成功从白名单中删除。", domain))
|
||||
} else {
|
||||
sendErrorMessage(bot, message.Chat.ID, fmt.Sprintf("未能从白名单中删除域名 '%s'。", domain))
|
||||
}
|
||||
}
|
||||
|
@ -1,225 +0,0 @@
|
||||
package service
|
||||
|
||||
// 消息处理辅助函数
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/woodchen-ink/Q58Bot/core"
|
||||
)
|
||||
|
||||
// deleteMessageAfterDelay 根据指定延迟删除消息。
|
||||
func deleteMessageAfterDelay(bot *tgbotapi.BotAPI, chatID int64, messageID int, delay time.Duration) {
|
||||
// 让线程暂停指定的延迟时间。
|
||||
time.Sleep(delay)
|
||||
|
||||
// 创建一个删除消息的请求。
|
||||
deleteMsg := tgbotapi.NewDeleteMessage(chatID, messageID)
|
||||
|
||||
// 尝试发送删除消息的请求,并检查是否有错误发生。
|
||||
// 注意: 错误情况下只是记录错误,不进行其他操作。
|
||||
_, err := bot.Request(deleteMsg)
|
||||
if err != nil {
|
||||
log.Printf("删除消息失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// SendLongMessage 如有必要,可将长消息拆分为多条消息来发送
|
||||
func SendLongMessage(bot *tgbotapi.BotAPI, chatID int64, prefix string, items []string) error {
|
||||
const maxMessageLength = 4000 // Leave some room for Telegram's message limit
|
||||
|
||||
message := prefix + "\n"
|
||||
for i, item := range items {
|
||||
newLine := fmt.Sprintf("%d. %s\n", i+1, item)
|
||||
if len(message)+len(newLine) > maxMessageLength {
|
||||
msg := tgbotapi.NewMessage(chatID, message)
|
||||
_, err := bot.Send(msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
message = ""
|
||||
}
|
||||
message += newLine
|
||||
}
|
||||
|
||||
if message != "" {
|
||||
msg := tgbotapi.NewMessage(chatID, message)
|
||||
_, err := bot.Send(msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// HandleKeywordCommand 处理关键词命令
|
||||
func HandleKeywordCommand(bot *tgbotapi.BotAPI, message *tgbotapi.Message, command string, args string, db *core.Database) {
|
||||
switch command {
|
||||
case "list":
|
||||
keywords, err := db.GetAllKeywords()
|
||||
if err != nil {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, "获取关键词列表时发生错误。"))
|
||||
return
|
||||
}
|
||||
if len(keywords) == 0 {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, "关键词列表为空。"))
|
||||
} else {
|
||||
SendLongMessage(bot, message.Chat.ID, "当前关键词列表:", keywords)
|
||||
}
|
||||
case "add":
|
||||
if args != "" {
|
||||
keyword := args
|
||||
exists, err := db.KeywordExists(keyword)
|
||||
if err != nil {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, "检查关键词时发生错误。"))
|
||||
return
|
||||
}
|
||||
if !exists {
|
||||
err = db.AddKeyword(keyword)
|
||||
if err != nil {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, "添加关键词时发生错误。"))
|
||||
} else {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("关键词 '%s' 已添加。", keyword)))
|
||||
}
|
||||
} else {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("关键词 '%s' 已存在。", keyword)))
|
||||
}
|
||||
}
|
||||
case "delete":
|
||||
if args != "" {
|
||||
keyword := args
|
||||
err := db.RemoveKeyword(keyword)
|
||||
if err != nil {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("删除关键词 '%s' 时发生错误: %v", keyword, err)))
|
||||
return
|
||||
}
|
||||
|
||||
// 检查关键词是否仍然存在
|
||||
exists, err := db.KeywordExists(keyword)
|
||||
if err != nil {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("检查关键词 '%s' 是否存在时发生错误: %v", keyword, err)))
|
||||
return
|
||||
}
|
||||
|
||||
if !exists {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("关键词 '%s' 已成功删除。", keyword)))
|
||||
} else {
|
||||
similarKeywords, err := db.SearchKeywords(keyword)
|
||||
if err != nil {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, "搜索关键词时发生错误。"))
|
||||
return
|
||||
}
|
||||
if len(similarKeywords) > 0 {
|
||||
SendLongMessage(bot, message.Chat.ID, fmt.Sprintf("未能删除关键词 '%s'。\n\n以下是相似的关键词:", keyword), similarKeywords)
|
||||
} else {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("未能删除关键词 '%s',且未找到相似的关键词。", keyword)))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, "请提供要删除的关键词。"))
|
||||
}
|
||||
case "deletecontaining":
|
||||
if args != "" {
|
||||
substring := args
|
||||
removedKeywords, err := db.RemoveKeywordsContaining(substring)
|
||||
if err != nil {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, "删除关键词时发生错误。"))
|
||||
return
|
||||
}
|
||||
if len(removedKeywords) > 0 {
|
||||
SendLongMessage(bot, message.Chat.ID, fmt.Sprintf("已删除包含 '%s' 的以下关键词:", substring), removedKeywords)
|
||||
} else {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("没有找到包含 '%s' 的关键词。", substring)))
|
||||
}
|
||||
}
|
||||
default:
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, "无效的命令或参数。"))
|
||||
}
|
||||
}
|
||||
|
||||
func HandleWhitelistCommand(bot *tgbotapi.BotAPI, message *tgbotapi.Message, command string, args string, db *core.Database) {
|
||||
switch command {
|
||||
case "listwhite":
|
||||
whitelist, err := db.GetAllWhitelist()
|
||||
if err != nil {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("获取白名单时发生错误: %v", err)))
|
||||
return
|
||||
}
|
||||
if len(whitelist) == 0 {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, "白名单为空。"))
|
||||
} else {
|
||||
SendLongMessage(bot, message.Chat.ID, "白名单域名列表:", whitelist)
|
||||
}
|
||||
|
||||
case "addwhite":
|
||||
if args == "" {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, "请提供要添加的域名。"))
|
||||
return
|
||||
}
|
||||
domain := strings.ToLower(args)
|
||||
exists, err := db.WhitelistExists(domain)
|
||||
if err != nil {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("检查白名单时发生错误: %v", err)))
|
||||
return
|
||||
}
|
||||
if exists {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("域名 '%s' 已在白名单中。", domain)))
|
||||
return
|
||||
}
|
||||
err = db.AddWhitelist(domain)
|
||||
if err != nil {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("添加到白名单时发生错误: %v", err)))
|
||||
return
|
||||
}
|
||||
// 再次检查以确保添加成功
|
||||
exists, err = db.WhitelistExists(domain)
|
||||
if err != nil {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("验证添加操作时发生错误: %v", err)))
|
||||
return
|
||||
}
|
||||
if exists {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("域名 '%s' 已成功添加到白名单。", domain)))
|
||||
} else {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("未能添加域名 '%s' 到白名单。", domain)))
|
||||
}
|
||||
|
||||
case "delwhite":
|
||||
if args == "" {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, "请提供要删除的域名。"))
|
||||
return
|
||||
}
|
||||
domain := strings.ToLower(args)
|
||||
exists, err := db.WhitelistExists(domain)
|
||||
if err != nil {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("检查白名单时发生错误: %v", err)))
|
||||
return
|
||||
}
|
||||
if !exists {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("域名 '%s' 不在白名单中。", domain)))
|
||||
return
|
||||
}
|
||||
err = db.RemoveWhitelist(domain)
|
||||
if err != nil {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("从白名单删除时发生错误: %v", err)))
|
||||
return
|
||||
}
|
||||
// 再次检查以确保删除成功
|
||||
exists, err = db.WhitelistExists(domain)
|
||||
if err != nil {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("验证删除操作时发生错误: %v", err)))
|
||||
return
|
||||
}
|
||||
if !exists {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("域名 '%s' 已成功从白名单中删除。", domain)))
|
||||
} else {
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, fmt.Sprintf("未能从白名单中删除域名 '%s'。", domain)))
|
||||
}
|
||||
|
||||
default:
|
||||
bot.Send(tgbotapi.NewMessage(message.Chat.ID, "无效的命令或参数。"))
|
||||
}
|
||||
}
|
@ -1,6 +1,5 @@
|
||||
package prompt_reply
|
||||
|
||||
//提示词回复
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
@ -13,6 +12,14 @@ import (
|
||||
|
||||
var db *core.Database
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
db, err = core.NewDatabase()
|
||||
if err != nil {
|
||||
log.Fatalf("Error initializing database: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func SetPromptReply(prompt, reply string) error {
|
||||
return db.AddPromptReply(prompt, reply)
|
||||
}
|
||||
@ -28,8 +35,9 @@ func GetPromptReply(message string) (string, bool) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
message = strings.ToLower(message)
|
||||
for prompt, reply := range promptReplies {
|
||||
if strings.Contains(strings.ToLower(message), prompt) {
|
||||
if strings.Contains(message, strings.ToLower(prompt)) {
|
||||
return reply, true
|
||||
}
|
||||
}
|
||||
@ -37,21 +45,21 @@ func GetPromptReply(message string) (string, bool) {
|
||||
}
|
||||
|
||||
func ListPromptReplies() string {
|
||||
promptReplies, err := db.GetAllPromptReplies()
|
||||
replies, err := db.GetAllPromptReplies()
|
||||
if err != nil {
|
||||
log.Printf("Error getting prompt replies: %v", err)
|
||||
return "获取提示词回复时发生错误。"
|
||||
return "Error retrieving prompt replies"
|
||||
}
|
||||
|
||||
if len(promptReplies) == 0 {
|
||||
return "目前没有设置任何提示词回复。"
|
||||
if len(replies) == 0 {
|
||||
return "No prompt replies found"
|
||||
}
|
||||
|
||||
var result strings.Builder
|
||||
result.WriteString("当前设置的提示词回复:\n")
|
||||
for prompt, reply := range promptReplies {
|
||||
result.WriteString(fmt.Sprintf("提示词: %s\n回复: %s\n\n", prompt, reply))
|
||||
for prompt, reply := range replies {
|
||||
result.WriteString(fmt.Sprintf("Prompt: %s\nReply: %s\n\n", prompt, reply))
|
||||
}
|
||||
|
||||
return result.String()
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user