Telebot

repository·v4·Indexed 26 days ago

https://github.com/tucnak/telebot

A high-performance, concise Go framework for building Telegram bots. Telebot v4 provides an elegant API for command routing, middleware, and media handling, featuring a transparent File API, support for Reply and Inline Keyboards, and comprehensive chat management tools including member rights, banning, and promotion.

Tokens
27.7K
Snippets
39
Records
217
Agent score
88%

What's inside telebot

  1. Use Reply and Inline Keyboards

    v4

    Telebot supports Telegram's two keyboard types: Reply Keyboards (replacing the user's keyboard) and Inline Keyboards (attached to specific messages). Buttons can be used as endpoints for Handle() to trigger specific logic when pressed.

    Reply Keyboards

    Use tele.ReplyMarkup{ResizeKeyboard: true} to create a menu. You can add buttons using menu.Text(), menu.Contact(), menu.Location(), or menu.Poll().

    Inline Keyboards

    Use tele.ReplyMarkup{} (without ResizeKeyboard) for inline buttons. Common methods include:

    • Data(text, data, ...): Sends a callback to the bot. Ensure the data is unique for routing.
    • URL(text, url): Opens a web link.
    • Query(text, query): Starts an inline query.
    • QueryChat(text, query): Starts an inline query for a specific chat.
    • Login(text, &tele.Login{...}): Initiates Telegram login.

    Buttons can be organized into rows using menu.Row() or selector.Row().

    var (
    	menu     = &tele.ReplyMarkup{ResizeKeyboard: true}
    	selector = &tele.ReplyMarkup{}
    
    	// Reply buttons
    	btnHelp     = menu.Text("ℹ Help")
    	btnSettings = menu.Text("⚙ Settings")
    
    	// Inline buttons
    	btnPrev = selector.Data("⬅", "prev")
    	btnNext = selector.Data("➡", "next")
    )
    
    // Construct the layouts
    menu.Reply(
    	menu.Row(btnHelp),
    	menu.Row(btnSettings),
    )
    selector.Inline(
    	selector.Row(btnPrev, btnNext),
    )
    
    // Handling interactions
    b.Handle("/start", func(c tele.Context) error {
    	return c.Send("Hello!", menu)
    })
    
    // On reply button pressed (message)
    b.Handle(&btnHelp, func(c tele.Context) error {
    	return c.Edit("Here is some help: ...")
    })
    
    // On inline button pressed (callback)
    b.Handle(&btnPrev, func(c tele.Context) error {
    	return c.Respond()
    })
  2. Handle Inline Queries

    v4

    To implement inline mode, register a handler for the tele.OnQuery endpoint. Use the c.Answer() method to return a tele.QueryResponse containing a list of tele.Results.

    Important Requirements:

    • Each result must have a unique string ID. Use result.SetResultID(id) to ensure this.
    • For tele.PhotoResult, the ThumbURL field is required.
    • You can use SwitchPMText and SwitchPMParameter in the QueryResponse to support authentication via deep-linking.
    b.Handle(tele.OnQuery, func(c tele.Context) error {
    	urls := []string{
    		"http://photo.jpg",
    		"http://photo2.jpg",
    	}
    
    	results := make(tele.Results, len(urls))
    	for i, url := range urls {
    		result := &tele.PhotoResult{
    			URL:      url,
    			ThumbURL: url, // required for photos
    		}
    
    		results[i] = result
    		// needed to set a unique string ID for each result
    		results[i].SetResultID(strconv.Itoa(i))
    	}
    
    	return c.Answer(&tele.QueryResponse{
    		Results:   results,
    		CacheTime: 60, // a minute
    	})
    })
  3. Implement Middleware

    v4

    Telebot supports middleware as chained functions that have access to tele.Context. Middleware can be applied globally, to a specific group of handlers, or to a single handler.

    To use built-in middleware, import gopkg.in/telebot.v4/middleware.

    // Global-scoped middleware
    b.Use(middleware.Logger())
    
    // Group-scoped middleware
    adminOnly := b.Group()
    adminOnly.Use(middleware.Whitelist(adminIDs...))
    adminOnly.Handle("/ban", onBan)
    
    // Handler-scoped middleware
    b.Handle(tele.OnText, onText, middleware.IgnoreVia())
  4. Get Started with a minimal Telebot setup

    v4

    To initialize a bot, create a tele.Settings object containing your Token and a Poller (such as tele.LongPoller). Use tele.NewBot(pref) to create the bot instance, define handlers using b.Handle, and call b.Start() to begin processing updates.

    package main
    
    import (
    	"log"
    	"os"
    	"time"
    
    	ele "gopkg.in/telebot.v4"
    )
    
    func main() {
    	pref := tele.Settings{
    		Token:  os.Getenv("TOKEN"),
    		Poller: &tele.LongPoller{Timeout: 10 * time.Second},
    	}
    
    	b, err := tele.NewBot(pref)
    	if err != nil {
    		log.Fatal(err)
    		return
    	}
    
    	b.Handle("/hello", func(c tele.Context) error {
    		return c.Send("Hello!")
    	})
    
    	b.Start()
    }
  5. Initialize a new Bot with Settings

    v4

    Use NewBot to create a new Telegram bot instance. You must provide a Settings struct containing at least the Token.

    Key Settings fields:

    • Token: The secret API key for your bot.
    • Updates: Capacity of the updates channel (defaults to 100).
    • Poller: The provider of updates (defaults to LongPoller).
    • Synchronous: If true, prevents handlers from running in parallel.
    • Verbose: If true, logs all upcoming requests (use for debugging).
    • ParseMode: Default parse mode for all sent messages.
    • OnError: Callback for handler errors.
    • Offline: If true, creates a bot without network connection (useful for testing).
  6. Edit messages using the Editable interface

    v4
    To edit a message, you don't need the full *Message object; you only need a 'message signature' consisting of a messageID and a chatID. Any struct that implements the Editable interface can be used with bot.Edit() or bot.Delete().
  7. Send messages and media with SendOptions

    v4

    The Send() method is used to send messages or media. It accepts a Recipient and a Sendable.

    To control message properties (like disabling web link previews or notifications), you can use:

    • &tele.SendOptions{} for full control.
    • &tele.ReplyMarkup{} for keyboards.
    • Functional flags like tele.Silent or tele.NoPreview.
    // Using full SendOptions
    b.Send(user, "text", &tele.SendOptions{
    	// ...
    })
    
    // Using ReplyMarkup shorthand
    b.Send(user, "text", &tele.ReplyMarkup{
    	// ...
    })
    
    // Using functional flags
    b.Send(user, "text", tele.Silent, tele.NoPreview)
    
    // Sending an Album
    p := &tele.Photo{File: tele.FromDisk("chicken.jpg")}
    v := &tele.Video{File: tele.FromURL("http://video.mp4")}
    msgs, err := b.SendAlbum(user, tele.Album{p, v})
  8. Handle Commands and arguments

    v4

    Telebot supports direct command routing (e.g., /start) and handles both /command and /command@botname syntax.

    • Use c.Message().Payload to extract data from deep-links (e.g., /start <PAYLOAD>).
    • Use c.Args() to get a slice of arguments split by spaces.
  9. Upload and manage Files

    v4

    Telebot provides a transparent File API. You can upload files from disk or URL. When sending a file created via tele.FromDisk, Telebot automatically uploads it. Subsequent sends of the same file will use the FileID instead of re-uploading.

    a := &tele.Audio{File: tele.FromDisk("file.ogg")}
    
    // Uploads the file and sends it
    b.Send(recipient, a)
    
    // Subsequent sends use the cached FileID
    b.Send(otherRecipient, a)
  10. Use Context to handle updates

    v4

    The tele.Context type wraps the Telegram update and provides helpers to access message data. You can use it to get the sender, text, or specific message types (like Photo) and use shorthand methods like c.Send() to respond directly.

    b.Handle(tele.OnText, func(c tele.Context) error {
    	var (
    		user = c.Sender()
    		text = c.Text()
    	)
    
    	// Use context shorthand to respond
    	return c.Send(text)
    })
    
    b.Handle(tele.OnPhoto, func(c tele.Context) error {
    	photo := c.Message().Photo
    	_ = photo
    	return nil
    })
  11. Configure a Webhook poller

    v4

    The Webhook struct configures a poller to receive updates via webhooks instead of long polling. It opens a local listener on the specified Listen address.

    Key configuration options:

    • Listen: The local address to listen on (e.g., :8080). If empty, the user is responsible for adding the webhook to an http.mux.
    • TLS: If provided, the poller opens a secure TLS listener using the specified Key and Cert paths.
    • Endpoint: Use this if you have a load balancer or reverse proxy. Set PublicURL to the address Telegram should call. If using a self-signed certificate at the proxy level, provide the path in Cert so it can be uploaded to Telegram.
    • SecretToken: A security token to validate incoming requests via the X-Telegram-Bot-Api-Secret-Token header.
    • IgnoreSetWebhook: If true, the poller will not automatically call SetWebhook on the Telegram API during Poll().