Skip to content

Instantly share code, notes, and snippets.

@QuynhVir
Created April 23, 2024 15:33
Show Gist options
  • Save QuynhVir/c479e5bb78a3c78d075179b428bc9b77 to your computer and use it in GitHub Desktop.
Save QuynhVir/c479e5bb78a3c78d075179b428bc9b77 to your computer and use it in GitHub Desktop.
A simple example Telegram echo-bot on Google Cloud Functions
package telegrambot
import (
"context"
"fmt"
"os"
"github.com/GoogleCloudPlatform/functions-framework-go/functions"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
)
func init() {
token := os.Getenv("TELEGRAM_BOT_TOKEN")
webhookURL := fmt.Sprintf("https://%s-%s.cloudfunctions.net/%s",
os.Getenv("FUNCTION_REGION"), // e.g. "us-central1"
os.Getenv("GCP_PROJECT"), // e.g. "my-project"
os.Getenv("FUNCTION_NAME"), // e.g. "my-function"
)
// Define the bot's default handler
opts := []bot.Option{
bot.WithDefaultHandler(handler),
}
// Create a new bot with the default handler
tgbot, err := bot.New(token, opts...)
if err != nil {
panic(err)
}
// Set the Webhook for the bot
_, err = tgbot.SetWebhook(context.Background(), &bot.SetWebhookParams{
URL: webhookURL,
})
if err != nil {
panic(err)
}
// Register the bot's WebhookHandler with the Functions Framework
functions.HTTP("bot", tgbot.WebhookHandler())
// Start the bot with the Webhook
go tgbot.StartWebhook(context.Background())
}
func handler(ctx context.Context, b *bot.Bot, update *models.Update) {
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: update.Message.Text,
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment