github.com/hungdoo/bot@v0.0.0-20240325145135-dd1f386f7b81/src/packages/telegram/client.go (about)

     1  package telegram
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  	"strings"
     7  	"time"
     8  
     9  	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
    10  	"github.com/hungdoo/bot/src/packages/dotenv"
    11  )
    12  
    13  var _bot *tgbotapi.BotAPI
    14  var _updates tgbotapi.UpdatesChannel
    15  var WHITELISTED = make(map[string]bool)
    16  
    17  func loadWhitelist() {
    18  	whitelists := strings.Split(dotenv.GetEnv("WHITELISTS"), ",")
    19  	for _, wl := range whitelists {
    20  		if len(wl) != 0 {
    21  			WHITELISTED[wl] = true
    22  		}
    23  	}
    24  }
    25  func IsWhitelisted(userName string) bool {
    26  	_, allowed := WHITELISTED[userName]
    27  	return allowed
    28  }
    29  
    30  func GetReportChatId() (int64, error) {
    31  	reportChatId := dotenv.GetEnv("REPORT_CHAT_ID")
    32  	return strconv.ParseInt(reportChatId, 10, 64)
    33  }
    34  func ReportInvalidAccess(fromUser string) {
    35  	chatId, err := GetReportChatId()
    36  	if err != nil {
    37  		return
    38  	}
    39  	msg := tgbotapi.NewMessage(chatId, fmt.Sprintf("[!!]Access from invalid user [%s]", fromUser))
    40  
    41  	GetBot().Send(msg)
    42  	time.Sleep(time.Millisecond * 500)
    43  }
    44  
    45  func GetBot() *tgbotapi.BotAPI {
    46  	if _bot == nil {
    47  		bot, err := tgbotapi.NewBotAPI(dotenv.BotEnvs["BOT_TELEGRAM_TOKEN"])
    48  		if err != nil {
    49  			fmt.Printf("%v\n", err.Error())
    50  			return nil
    51  		}
    52  		loadWhitelist()
    53  		_bot = bot
    54  	}
    55  	return _bot
    56  }
    57  
    58  func GetUpdates() (tgbotapi.UpdatesChannel, error) {
    59  	bot := GetBot()
    60  	if _updates == nil {
    61  		u := tgbotapi.NewUpdate(0)
    62  		u.Timeout = 60
    63  
    64  		updates, err := bot.GetUpdatesChan(u)
    65  		if err != nil {
    66  			return nil, fmt.Errorf("%v", err.Error())
    67  		}
    68  
    69  		time.Sleep(time.Millisecond * 500)
    70  		updates.Clear()
    71  		_updates = updates
    72  	}
    73  
    74  	return _updates, nil
    75  }