Skip to content

Commit

Permalink
feat: support msg channel
Browse files Browse the repository at this point in the history
  • Loading branch information
xxxsen committed Apr 22, 2023
1 parent 804c1a7 commit 685461e
Show file tree
Hide file tree
Showing 11 changed files with 151 additions and 61 deletions.
27 changes: 24 additions & 3 deletions cmd/main.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
//Package main mainpkg
// Package main mainpkg
package main

import (
"context"
"flag"
"log"
"tgnotify/config"
"tgnotify/sender"
"tgnotify/server"

"github.com/xxxsen/common/logger"
Expand All @@ -22,14 +23,34 @@ func main() {
if err != nil {
log.Panicf("parse config fail, err:%v", err)
}

//init log
logger.Init(c.Log.File, c.Log.Level, int(c.Log.FileCount), int(c.Log.FileSize), int(c.Log.KeepDays), c.Log.Console)
svr, err := server.New(server.WithBind(c.Listen), server.WithBotConfig(c.ChatID, c.Token), server.WithUser(c.User))
mustInitGlobalMessageChannel(c)
opts := []server.Option{
server.WithBind(c.Listen),
server.WithUser(c.User),
}
svr, err := server.New(opts...)
if err != nil {
logutil.GetLogger(context.Background()).With(zap.Error(err)).Fatal("init notify server fail")
}
if err := svr.Run(); err != nil {
logutil.GetLogger(context.Background()).With(zap.Error(err)).Fatal("run notify server fail")
}
}

func mustInitGlobalMessageChannel(c *config.Config) {
ch, err := sender.NewBotMsgSender("default", c.ChatID, c.Token)
if err != nil {
panic(err)
}
chs := make(map[string]sender.IMessageSender)
for name, cfg := range c.Channels {
chitem, err := sender.NewBotMsgSender(name, cfg.ChatID, cfg.Token)
if err != nil {
panic(err)
}
chs[name] = chitem
}
sender.InitGlobalGroupMessageSender(chs, ch)
}
18 changes: 12 additions & 6 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//Package config config parser
// Package config config parser
package config

import (
Expand All @@ -9,12 +9,18 @@ import (
"github.com/xxxsen/common/logger"
)

type Channel struct {
ChatID int64 `json:"chatid"`
Token string `json:"token"`
}

type Config struct {
Listen string `json:"listen"`
ChatID int64 `json:"chatid"`
Token string `json:"token"`
User map[string]string `json:"users"`
Log logger.LogConfig `json:"log"`
Listen string `json:"listen"`
ChatID int64 `json:"chatid"`
Token string `json:"token"`
User map[string]string `json:"users"`
Log logger.LogConfig `json:"log"`
Channels map[string]*Channel `json:"channels"`
}

func Parse(f string) (*Config, error) {
Expand Down
5 changes: 2 additions & 3 deletions constant/constant.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package constant

const (
KeyBot = "keyNotifyBot"
KeyChatID = "keyChatID"
KeyUserList = "keyUserList"
KeyUserList = "keyUserList"
KeyChannelHeader = "channel"
)
1 change: 1 addition & 0 deletions model/model.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package model

type SendMessageRequest struct {
Channel string `json:"channel"`
Message string `json:"message"`
MessageType string `json:"message_type"`
}
38 changes: 38 additions & 0 deletions sender/bot_msg_sender.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package sender

import (
"context"

tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/xxxsen/common/errs"
)

type BotMsgSender struct {
name string
chatid int64
bot *tgbotapi.BotAPI
}

func NewBotMsgSender(name string, chatid int64, token string) (*BotMsgSender, error) {
bot, err := tgbotapi.NewBotAPI(token)
if err != nil {
return nil, errs.Wrap(errs.ErrUnknown, "init bot fail", err)
}
return &BotMsgSender{name, chatid, bot}, nil
}

func (c *BotMsgSender) Name() string {
return c.name
}

func (c *BotMsgSender) SendMessage(ctx context.Context, mode string, message string) error {
msg := tgbotapi.NewMessage(c.chatid, message)
if len(mode) != 0 {
msg.ParseMode = mode
}
_, err := c.bot.Send(msg)
if err != nil {
return errs.Wrap(errs.ErrIO, "send msg fail", err)
}
return nil
}
39 changes: 39 additions & 0 deletions sender/group_msg_sender.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package sender

import (
"context"

"github.com/xxxsen/common/errs"
)

var glgp *GroupMsgSender

func InitGlobalGroupMessageSender(chsm map[string]IMessageSender, def IMessageSender) {
glgp = NewGroupMsgSender(chsm, def)
}

type GroupMsgSender struct {
chs map[string]IMessageSender
def IMessageSender
}

func NewGroupMsgSender(chsm map[string]IMessageSender, def IMessageSender) *GroupMsgSender {
return &GroupMsgSender{
chs: chsm, def: def,
}
}

func (c *GroupMsgSender) SendMessage(ctx context.Context, name string, mode string, message string) error {
s, ok := c.chs[name]
if !ok {
s = c.def
}
if s == nil {
return errs.New(errs.ErrServiceInternal, "no sender found")
}
return s.SendMessage(ctx, mode, message)
}

func SendMessageByChannel(ctx context.Context, name string, mode string, message string) error {
return glgp.SendMessage(ctx, name, mode, message)
}
10 changes: 10 additions & 0 deletions sender/msg_sender.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package sender

import (
"context"
)

type IMessageSender interface {
Name() string
SendMessage(ctx context.Context, mode string, message string) error
}
16 changes: 6 additions & 10 deletions server/config.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package server

type config struct {
addr string
type channel struct {
chatid int64
token string
users map[string]string
}

type config struct {
addr string
users map[string]string
}

type Option func(c *config)
Expand All @@ -15,13 +18,6 @@ func WithBind(addr string) Option {
}
}

func WithBotConfig(chatid int64, token string) Option {
return func(c *config) {
c.chatid = chatid
c.token = token
}
}

func WithUser(m map[string]string) Option {
return func(c *config) {
c.users = m
Expand Down
17 changes: 0 additions & 17 deletions server/getter/getter.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,10 @@ import (
"context"
"tgnotify/constant"

tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/xxxsen/common/errs"
"github.com/xxxsen/common/naivesvr"
)

func MustGetBot(ctx context.Context) *tgbotapi.BotAPI {
v, ok := naivesvr.GetAttachKey(ctx, constant.KeyBot)
if !ok {
panic(errs.New(errs.ErrParam, "bot key not found"))
}
return v.(*tgbotapi.BotAPI)
}

func MustGetChatID(ctx context.Context) int64 {
v, ok := naivesvr.GetAttachKey(ctx, constant.KeyChatID)
if !ok {
panic(errs.New(errs.ErrParam, "chatid key not found"))
}
return v.(int64)
}

func MustGetUserList(ctx context.Context) map[string]string {
v, ok := naivesvr.GetAttachKey(ctx, constant.KeyUserList)
if !ok {
Expand Down
18 changes: 8 additions & 10 deletions server/handler/msg/sendmsg.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package msg

import (
"context"
"io/ioutil"
"net/http"
"strings"
"tgnotify/constant"
"tgnotify/model"
"tgnotify/server/getter"
"tgnotify/sender"

"github.com/gin-gonic/gin"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
Expand Down Expand Up @@ -41,7 +43,9 @@ func SendMessage(c *gin.Context, ireq interface{}) (int, errs.IError, interface{
if err != nil {
return http.StatusOK, errs.Wrap(errs.ErrIO, "read msg fail", err), nil
}
ch := c.GetHeader(constant.KeyChannelHeader)
return SendMessageJson(c, &model.SendMessageRequest{
Channel: ch,
Message: msg,
MessageType: c.GetHeader("mode"),
})
Expand All @@ -53,20 +57,14 @@ func SendMessageJson(c *gin.Context, ireq interface{}) (int, errs.IError, interf
return http.StatusOK, errs.New(errs.ErrParam, "nil message"), nil
}
mode := type2mode(req.MessageType)
bot := getter.MustGetBot(c)
chatid := getter.MustGetChatID(c)
if err := sendMessageInternal(bot, chatid, mode, req.Message); err != nil {
if err := sendMessageInternal(c, req.Channel, mode, req.Message); err != nil {
return http.StatusOK, errs.Wrap(errs.ErrIO, "send internal fail", err), nil
}
return http.StatusOK, errs.ErrOK, nil
}

func sendMessageInternal(bot *tgbotapi.BotAPI, id int64, mode string, message string) error {
msg := tgbotapi.NewMessage(id, message)
if len(mode) != 0 {
msg.ParseMode = mode
}
_, err := bot.Send(msg)
func sendMessageInternal(ctx context.Context, ch string, mode string, message string) error {
err := sender.SendMessageByChannel(ctx, ch, mode, message)
if err != nil {
return errs.Wrap(errs.ErrIO, "send msg fail", err)
}
Expand Down
23 changes: 11 additions & 12 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,38 +12,37 @@ import (
"go.uber.org/zap"
)

type botctx struct {
chatid int64
bot **tgbotapi.BotAPI
}

type NotifyServer struct {
c *config
bot *tgbotapi.BotAPI
c *config
bot *botctx
channelsBotMap map[string]*botctx
}

func New(opts ...Option) (*NotifyServer, error) {
c := &config{}
for _, opt := range opts {
opt(c)
}
if len(c.addr) == 0 || len(c.token) == 0 || c.chatid == 0 {
if len(c.addr) == 0 {
return nil, errs.New(errs.ErrParam, "invalid param")
}
bot, err := tgbotapi.NewBotAPI(c.token)
if err != nil {
return nil, errs.Wrap(errs.ErrUnknown, "init bot fail", err)
}
return &NotifyServer{c: c, bot: bot}, nil
return &NotifyServer{c: c}, nil
}

func (s *NotifyServer) Run() error {
svr, err := naivesvr.NewServer(
naivesvr.WithAddress(s.c.addr),
naivesvr.WithHandlerRegister(handler.OnRegist),
naivesvr.WithAttach(constant.KeyBot, s.bot),
naivesvr.WithAttach(constant.KeyChatID, s.c.chatid),
naivesvr.WithAttach(constant.KeyUserList, s.c.users),
)
if err != nil {
return errs.New(errs.ErrServiceInternal, "bind http server fail", err)
}
logutil.GetLogger(context.Background()).With(zap.String("addr", s.c.addr),
zap.Int64("chatid", s.c.chatid), zap.Int("user_count", len(s.c.users))).Info("start running server")
logutil.GetLogger(context.Background()).With(zap.String("addr", s.c.addr), zap.Int("user_count", len(s.c.users))).Info("start running server")
return svr.Run()
}

0 comments on commit 685461e

Please sign in to comment.