go-telegram / bot

Telegram Bot API Go framework
MIT License
674 stars 60 forks source link

Ability to create local context #118

Closed Pelfox closed 1 week ago

Pelfox commented 1 week ago

My idea is to add some kind of local context to the bot.Bot struct, so handlers can access for example database instance without using DI. As a great example - you can look at Locals implementation in Fiber.

negasus commented 1 week ago

I think, more right way use handlers as part of struct

For example:

type Application struct {
    db any // some DB connection
}

func main() {
    ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
    defer cancel()

    app := &Application{
        db: "my_db_connection",
    }

    opts := []bot.Option{
        bot.WithDefaultHandler(app.handler),
    }

    b, _ := bot.New(os.Getenv("EXAMPLE_TELEGRAM_BOT_TOKEN"), opts...)

    b.Start(ctx)
}

func (app *Application) handler(ctx context.Context, b *bot.Bot, update *models.Update) {
    // access to app.db
}
Pelfox commented 1 week ago

Yep, great idea, thanks. I think it's a great example to add.