gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/agent/input/telegram/telegram.go (about)

     1  package telegram
     2  
     3  import (
     4  	"errors"
     5  	"strings"
     6  	"sync"
     7  
     8  	"github.com/micro/cli"
     9  	"gitee.com/liuxuezhan/go-micro-v1.18.0/agent/input"
    10  	tgbotapi "gopkg.in/telegram-bot-api.v4"
    11  )
    12  
    13  type telegramInput struct {
    14  	sync.Mutex
    15  
    16  	debug     bool
    17  	token     string
    18  	whitelist []string
    19  
    20  	api *tgbotapi.BotAPI
    21  }
    22  
    23  type ChatType string
    24  
    25  const (
    26  	Private    ChatType = "private"
    27  	Group      ChatType = "group"
    28  	Supergroup ChatType = "supergroup"
    29  )
    30  
    31  func init() {
    32  	input.Inputs["telegram"] = &telegramInput{}
    33  }
    34  
    35  func (ti *telegramInput) Flags() []cli.Flag {
    36  	return []cli.Flag{
    37  		cli.BoolFlag{
    38  			Name:   "telegram_debug",
    39  			EnvVar: "MICRO_TELEGRAM_DEBUG",
    40  			Usage:  "Telegram debug output",
    41  		},
    42  		cli.StringFlag{
    43  			Name:   "telegram_token",
    44  			EnvVar: "MICRO_TELEGRAM_TOKEN",
    45  			Usage:  "Telegram token",
    46  		},
    47  		cli.StringFlag{
    48  			Name:   "telegram_whitelist",
    49  			EnvVar: "MICRO_TELEGRAM_WHITELIST",
    50  			Usage:  "Telegram bot's users (comma-separated values)",
    51  		},
    52  	}
    53  }
    54  
    55  func (ti *telegramInput) Init(ctx *cli.Context) error {
    56  	ti.debug = ctx.Bool("telegram_debug")
    57  	ti.token = ctx.String("telegram_token")
    58  
    59  	whitelist := ctx.String("telegram_whitelist")
    60  
    61  	if whitelist != "" {
    62  		ti.whitelist = strings.Split(whitelist, ",")
    63  	}
    64  
    65  	if len(ti.token) == 0 {
    66  		return errors.New("missing telegram token")
    67  	}
    68  
    69  	return nil
    70  }
    71  
    72  func (ti *telegramInput) Stream() (input.Conn, error) {
    73  	ti.Lock()
    74  	defer ti.Unlock()
    75  
    76  	return newConn(ti)
    77  }
    78  
    79  func (ti *telegramInput) Start() error {
    80  	ti.Lock()
    81  	defer ti.Unlock()
    82  
    83  	api, err := tgbotapi.NewBotAPI(ti.token)
    84  	if err != nil {
    85  		return err
    86  	}
    87  
    88  	ti.api = api
    89  
    90  	api.Debug = ti.debug
    91  
    92  	return nil
    93  }
    94  
    95  func (ti *telegramInput) Stop() error {
    96  	return nil
    97  }
    98  
    99  func (p *telegramInput) String() string {
   100  	return "telegram"
   101  }