telegram bot pt1

📅 2023-01-09T21:17:54.492Z
👁️ 188 katselukertaa
🔓 Julkinen


package main

import (
	"fmt"
	"log"
	"net/http"
	"os"

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

func fromEnv(name string, opt ...string) string {
	apiId := os.Getenv(name)
	if apiId == "" && len(opt) == 0 {
		log.Fatalf("%s required but not present in current environment\n", name)
	} else if len(opt) > 0 {
		apiId = opt[0]
	}

	return apiId
}

func initBot(webhookUrl, apiId string) (*tgbotapi.BotAPI, tgbotapi.UpdatesChannel) {
	bot, err := tgbotapi.NewBotAPI(apiId)
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Authenticated as '%s'\n", bot.Self.String())

	webhook, err := tgbotapi.NewWebhook(fmt.Sprintf("%s/%s", webhookUrl, bot.Token))
	if err != nil {
		log.Fatal(err)
	}

	if _, err := bot.Request(webhook); err != nil {
		log.Fatal(err)
	}

	updates := bot.ListenForWebhook("/" + bot.Token)
	return bot, updates
}

func main() {
	// env var options
	webhookUrl := fromEnv("WEBHOOK_URL")
	apiId := fromEnv("TELEGRAM_BOT_ID")
	useDebug := fromEnv("DEBUG", "0") == "1"
	listenAddress := fromEnv("LISTEN_ADDRESS", "127.0.0.1:8080")

	// initialize bot
	bot, whUpdates := initBot(webhookUrl, apiId)
	bot.Debug = useDebug

	// listen for connections in the background
	go func() {
		if err := http.ListenAndServe(listenAddress, nil); err != nil {
			log.Fatal(err)
		}
	}()

	// handle updates
	for update := range whUpdates {
		fmt.Println(update.Message)
	}
}