Untitled

mail@pastecode.io avatar
unknown
golang
a year ago
1.1 kB
5
Indexable
Never
func startTaskBot(ctx context.Context) error {
	bot, err := tgbotapi.NewBotAPI(BotToken)
	if err != nil {
		log.Fatalf("NewBotAPI failed: %s", err)
	}
	log.Printf("Авторизация на аккаунте %s", bot.Self.UserName)
	bot.Debug = true

	wh, err := tgbotapi.NewWebhook(WebhookURL)
	if err != nil {
		log.Fatalf("NewWebhook failed: %s", err)
	}

	_, err = bot.Request(wh)
	if err != nil {
		log.Fatalf("SetWebhook failed: %s", err)
	}

	updates := bot.ListenForWebhook("/")

	http.HandleFunc("/state", func(w http.ResponseWriter, r *http.Request) {
		_, err := w.Write([]byte("all is working"))
		if err != nil {
			return
		}
	})

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	go func() {
		log.Fatalln("http err:", http.ListenAndServe(":"+port, nil))
	}()
	fmt.Println("start listen :" + port)

	for {
		select {
		case update := <-updates:
			log.Printf("upd: %#v\n", update)
			if update.Message == nil {
				continue
			}
			handleCommands(update, bot)
		case <-ctx.Done():
			log.Println("Bot was stopped by context")
			return ctx.Err()
		}
	}
}