Skip to content

Commit

Permalink
Merge pull request #42 from CSUSTers/dev
Browse files Browse the repository at this point in the history
command /mc back again
  • Loading branch information
icceey authored Feb 6, 2021
2 parents b17ce67 + 41cb6b1 commit a50cecf
Show file tree
Hide file tree
Showing 16 changed files with 177 additions and 130 deletions.
136 changes: 33 additions & 103 deletions base/mc.go
Original file line number Diff line number Diff line change
@@ -1,113 +1,43 @@
package base

import (
"csust-got/config"
"csust-got/log"
"csust-got/prom"
"csust-got/util"

"fmt"
"go.uber.org/zap"
. "gopkg.in/tucnak/telebot.v2"
)

// MC we not use message count anymore
func MC(m *Message) {
util.SendReply(m.Chat, "再mc自杀", m)
if !config.BotConfig.PromConfig.Enabled {
util.SendReply(m.Chat, "再mc自杀", m)
return
}
msgR := util.SendMessage(m.Chat, "稍等。。。")
data, err := prom.QueryMessageCount(m.Chat.Title)
if err != nil {
log.Error("MC error", zap.Error(err))
util.EditMessage(msgR, "再mc自杀!!!")
return
}
if len(data) == 0 {
util.EditMessage(msgR, "再mc自杀!")
return
}
text := "本群大水怪名单(数据有半分钟延迟):\n"
// rankCN := []string{"零", "一", "二", "三", "四", "wu", "六", "七", "八", "九", "十"}
text += fmt.Sprintf("第一名:'%v'!他的一生,是龙王的一生,他把有限的生命贡献在了无限的发送 message 上,24h内数量高达 %v 条!群友因为他感受到这个群还有活人,我们把最热烈 fake_ban 送给他,让他在新的一天里享受快乐的退休时光吧!\n",
data[0].Name, data[0].Value)
if len(data) > 1 {
text += fmt.Sprintf("第二名:'%v'!他用上洪荒之力,在24h内水了 %v 条消息,这个数字证明了它他的决心,虽然没能夺冠,让我们仍旧把掌声送给他!\n",
data[1].Name, data[1].Value)
}
if len(data) > 2 {
text += fmt.Sprintf("第三名:'%v'!这位朋友很努力,在24h内水了 %v 条消息!很棒,再接再厉!\n",
data[2].Name, data[2].Value)
}
util.EditMessage(msgR, text)
}

// message type
// const (
// MESSAGE = "message"
// STICKER = "sticker"
// TOTAL = "total"
// )

// MC is handler for command `mc`.
// func MC() module.Module {
// handler := func(ctx context.Context, update tgbotapi.Update, bot *tgbotapi.BotAPI) {
// text := "啊等等,刚才数到多少来着,完了,忘记了QAQ..."
// defer func() {
// msg := tgbotapi.NewMessage(update.Message.Chat.ID, text)
// util.SendMessage(bot, msg)
// }()
// resSticker, err := ctx.GlobalClient().ZRevRangeWithScores(ctx.WrapKey(STICKER), 0, 3).Result()
// if err != nil {
// log.Error("Get Sticker count in redis ZRevRangeWithScores failed", zap.Error(err))
// return
// }
// err = ctx.GlobalClient().ZUnionStore(ctx.WrapKey(TOTAL), &redis.ZStore{
// Keys: []string{ctx.WrapKey(STICKER), ctx.WrapKey(MESSAGE)},
// Weights: nil,
// Aggregate: "",
// }).Err()
// if err != nil {
// log.Error("Redis ZUnionStore failed", zap.Error(err))
// return
// }
// resTotal, err := ctx.GlobalClient().ZRevRangeWithScores(ctx.WrapKey(TOTAL), 0, 3).Result()
// if err != nil {
// log.Error("Get total message count in redis ZRevRangeWithScores failed", zap.Error(err))
// return
// }
// text = wrapText(bot, update.Message.Chat.ID, resSticker, resTotal)
// }
// return module.Stateful(handler)
// }

// MessageCount is used to count message.
// func MessageCount() module.Module {
// handler := func(ctx context.Context, update tgbotapi.Update, bot *tgbotapi.BotAPI) {
// message := update.Message
// // We won't count commands
// if message.IsCommand() {
// return
// }
// userID := message.From.ID
// ctx.GlobalClient().ZIncr(ctx.WrapKey(getMessageType(message)), IncrKey(userID))
// }
// return module.Stateful(handler)
// }

// func wrapText(bot *tgbotapi.BotAPI, chatID int64, resSticker, resTotal []redis.Z) string {
// if len(resTotal) == 0 {
// return "从我记事起。。。。没人嗦过话呢"
// }
// text := "本群大水怪名单:\n"
// userID, _ := strconv.Atoi(resTotal[0].Member.(string))
// user := util.GetChatMember(bot, chatID, userID).User
// text += fmt.Sprintf("第一名:'%v'!他的一生,是龙王的一生,他把有限的生命贡献在了无限的发送 message 上,累计数量高达 %v 条!群友因为他感受到这个群还有活人,我们把最热烈 fake_ban 送给他,让他在新的一天里享受快乐的退休时光吧!\n",
// user.FirstName+user.LastName, int(resTotal[0].Score))
// if len(resTotal) > 1 {
// userID, _ := strconv.Atoi(resTotal[1].Member.(string))
// user := util.GetChatMember(bot, chatID, userID).User
// text += fmt.Sprintf("第二名:'%v'!他用上洪荒之力,水了 %v 条消息,这个数字证明了它他的决心,虽然没能夺冠,让我们仍旧把掌声送给他!\n",
// user.FirstName+user.LastName, int(resTotal[1].Score))
// }
// if len(resTotal) > 2 {
// userID, _ := strconv.Atoi(resTotal[2].Member.(string))
// user := util.GetChatMember(bot, chatID, userID).User
// text += fmt.Sprintf("第三名:'%v'!这位朋友很努力,累计水了 %v 条消息!很棒,再接再厉!\n",
// user.FirstName+user.LastName, int(resTotal[2].Score))
// }
// return text
// }

// // We count Stickers and other Messages separately.
// func getMessageType(message *tgbotapi.Message) string {
// if message.Sticker != nil {
// return STICKER
// }
// return MESSAGE
// }
//
// // IncrKey return a ZSET config to increase message count
// func IncrKey(userID int) *redis.Z {
// return &redis.Z{
// Score: 1,
// Member: strconv.Itoa(userID),
// }
// }
//
// // DecrKey return a ZSET config to decrease message count
// func DecrKey(userID int) *redis.Z {
// return &redis.Z{
// Score: -1,
// Member: strconv.Itoa(userID),
// }
// }
3 changes: 2 additions & 1 deletion base/notification.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package base

import (
"csust-got/config"
"csust-got/prom"
"csust-got/util"

Expand All @@ -11,7 +12,7 @@ import (
// when someone new join group, bot will send welcome message.
func WelcomeNewMember(m *Message) {
for _, member := range m.UsersJoined {
text := "Welcome to this group!" + util.GetName(&member)
text := config.BotConfig.MessageConfig.WelcomeMessage + util.GetName(&member)
util.SendMessage(m.Chat, text)
prom.NewMember(m.Chat.Title)
}
Expand Down
2 changes: 1 addition & 1 deletion base/time_task.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func RunTask(m *Message) {
cmd := entities.FromMessage(m)
delay, err := util.EvalDuration(cmd.Arg(0))
info := cmd.ArgAllInOneFrom(1)
if err != nil || delay < 1 {
if err != nil || delay < time.Second {
util.SendReply(m.Chat, text, m)
return
}
Expand Down
18 changes: 11 additions & 7 deletions base/yiban.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ func SubYiban(m *Message) {
return
}
resp := requestYiban(tel)
if resp == nil {
util.SendMessage(m.Chat, "bot请求易班失败 x_x")
return
}
if resp.ErrCode == codeWaiting || resp.ErrCode == codeOK {
if orm.RegisterYiban(m.Sender.ID, tel) {
util.SendMessage(m.Chat, "bot记下了,以后查询 /yiban 不再需要填写参数,每日打卡结果bot会推送通知,如需bot忘记手机号请使用 /no_yiban")
Expand All @@ -94,7 +98,6 @@ func NoYiban(m *Message) {

func YibanService() {
for range time.Tick(30 * time.Minute) {
log.Info("start yiban status check")
mp := orm.GetAllYiban()
for userID, tel := range mp {
if orm.IsYibanNotified(userID) {
Expand All @@ -116,6 +119,7 @@ func YibanService() {
log.Warn("yiban service user not found, try delete")
orm.DelYiban(userID)
case codeServerError:
log.Warn("yiban service error", zap.Any("response", *resp))
util.SendMessage(chat, getMsg(resp))
}
}
Expand All @@ -137,11 +141,11 @@ func getMsg(resp *yibanResp) string {

switch resp.ErrCode {
case codeWaiting:
return "别急,自动打卡时间还没到呢"
return "别急,自动打卡时间还没到呐~"
case codeOK:
return "自动打卡成功\n" + resp.Data
return "好耶,自动打卡成功辣~\n" + resp.Data
case codeNotFound:
return "您尚未注册群友特供版"
return "您尚未注册群友特供版~"
case codeServerError:
return "打卡失败,可能是表单有变动或服务器异常"
}
Expand All @@ -152,21 +156,21 @@ func getMsg(resp *yibanResp) string {
func requestYiban(tel string) *yibanResp {
rsp, err := http.Get(config.BotConfig.YibanApi + tel)
if err != nil {
log.Error("request yiban failed.")
log.Error("request yiban failed.", zap.Error(err))
return nil
}
defer rsp.Body.Close()

bytes, err := ioutil.ReadAll(rsp.Body)
if err != nil {
log.Error("request yiban read yibanResp failed.")
log.Error("request yiban read yibanResp failed.", zap.Error(err))
return nil
}

resp := new(yibanResp)
err = json.Unmarshal(bytes, resp)
if err != nil {
log.Error("request yiban unmarshal yibanResp failed.")
log.Error("request yiban unmarshal yibanResp failed.", zap.Error(err))
return nil
}
return resp
Expand Down
5 changes: 5 additions & 0 deletions config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,10 @@ message:
hitokoto_not_found: "过去那些零碎的细语并不构成这个世界:对于你而言,该看,该想,该体会身边那些微小事物的律动。忘了这些话吧。忘了这个功能吧——只今它已然不能给予你更多。而你的未来属于新的旅途:去欲望、去收获、去爱、去恨。去做只属于你自己的选择,写下只有你深谙个中滋味的诗篇。我们的生命以后可能还会交织之时,但如今,再见辣。"
no_sleep: "睡你麻痹起来嗨!"
boot_failed: "我不愿面对这苦涩的一天……:("
welcome: "Welcome to this group!"

yiban_api: ""
prometheus:
enabled: false
address: "prometheus:9090"
message_query: 'topk(10, sum(rate(bot_message_count[24h])*(24*3600-5)) by (username))'
9 changes: 4 additions & 5 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package config

import (
"csust-got/prom"
"fmt"
"strings"

Expand Down Expand Up @@ -42,6 +41,7 @@ func NewBotConfig() *Config {
config.MessageConfig = new(messageConfig)
config.WhiteListConfig = new(specialListConfig)
config.BlackListConfig = new(specialListConfig)
config.PromConfig = new(promConfig)
config.WhiteListConfig.SetName("white_list")
config.BlackListConfig.SetName("black_list")
return config
Expand All @@ -61,6 +61,7 @@ type Config struct {
MessageConfig *messageConfig
BlackListConfig *specialListConfig
WhiteListConfig *specialListConfig
PromConfig *promConfig

YibanApi string
}
Expand All @@ -86,8 +87,6 @@ func initViper(configFile, envPrefix string) {
zap.String("configFile", configFile), zap.Error(err))
}
zap.L().Warn("config file is not available...", zap.String("configFile", configFile), zap.Error(err))
prom.Log(zap.WarnLevel.String())
prom.Log(zap.WarnLevel.String())
return
}
}
Expand All @@ -113,6 +112,7 @@ func readConfig() {
BotConfig.MessageConfig.readConfig()
BotConfig.WhiteListConfig.readConfig()
BotConfig.BlackListConfig.readConfig()
BotConfig.PromConfig.readConfig()

BotConfig.YibanApi = viper.GetString("yiban_api")
}
Expand All @@ -121,11 +121,9 @@ func readConfig() {
func checkConfig() {
if BotConfig.Token == "" {
zap.L().Panic(noTokenMsg)
prom.Log(zap.PanicLevel.String())
}
if BotConfig.DebugMode {
zap.L().Warn("DEBUG MODE IS ON")
prom.Log(zap.WarnLevel.String())
}
if BotConfig.Worker <= 0 {
BotConfig.Worker = 1
Expand All @@ -137,4 +135,5 @@ func checkConfig() {
BotConfig.MessageConfig.checkConfig()
BotConfig.BlackListConfig.checkConfig()
BotConfig.WhiteListConfig.checkConfig()
BotConfig.PromConfig.checkConfig()
}
4 changes: 2 additions & 2 deletions config/message.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package config

import (
"csust-got/prom"
"reflect"

"github.com/spf13/viper"
Expand All @@ -17,6 +16,7 @@ type messageConfig struct {
HitokotoNotFound string
NoSleep string
BootFailed string
WelcomeMessage string
}

func (c *messageConfig) readConfig() {
Expand All @@ -26,6 +26,7 @@ func (c *messageConfig) readConfig() {
c.HitokotoNotFound = viper.GetString("message.hitokoto_not_found")
c.NoSleep = viper.GetString("message.no_sleep")
c.BootFailed = viper.GetString("message.boot_failed")
c.WelcomeMessage = viper.GetString("message.welcome")
}

func (c *messageConfig) checkConfig() {
Expand All @@ -35,7 +36,6 @@ func (c *messageConfig) checkConfig() {
if s == "" {
zap.L().Warn("message config not set, use default value",
zap.String("key", v.Type().Field(i).Name))
prom.Log(zap.WarnLevel.String())
v.Field(i).SetString(missMsg)
}
}
Expand Down
3 changes: 0 additions & 3 deletions config/orm.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package config

import (
"csust-got/prom"

"github.com/spf13/viper"
"go.uber.org/zap"
)
Expand All @@ -22,6 +20,5 @@ func (c *redisConfig) readConfig() {
func (c *redisConfig) checkConfig() {
if c.RedisAddr == "" {
zap.L().Panic(noRedisMsg)
prom.Log(zap.PanicLevel.String())
}
}
21 changes: 21 additions & 0 deletions config/prom.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package config

import (
"github.com/spf13/viper"
)

type promConfig struct {
Enabled bool
Address string
MessageQuery string
}

func (c *promConfig) readConfig() {
c.Enabled = viper.GetBool("prometheus.enabled")
c.Address = viper.GetString("prometheus.address")
c.MessageQuery = viper.GetString("prometheus.message_query")
}

func (c *promConfig) checkConfig() {

}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.14
require (
github.com/go-redis/redis/v7 v7.4.0
github.com/prometheus/client_golang v1.9.0
github.com/prometheus/common v0.15.0
github.com/spf13/viper v1.7.1
github.com/stretchr/testify v1.7.0
go.uber.org/zap v1.16.0
Expand Down
Loading

0 comments on commit a50cecf

Please sign in to comment.