ptgb

pub package license: MIT

A complete client for the Telegram Bot API. Methods for every endpoint + keyboards, media, webhooks, payments, stickers, business accounts, and etc.

import 'package:ptgb/ptgb.dart';

Future<void> main() async {
  final bot = Bot(); // loads your token from a .env file — see Quick Start
  await for (final update in bot.poll()) {
    if (update.text == '/start') {
      await bot.sendMessage(update.chatId!, 'Hello from ptgb!');
    }
  }
}

Contents

Features

  • Full API coverage — messaging, media, chat & forum administration, inline mode, payments & Telegram Stars, stickers, games, Telegram Business accounts, Stories, and Web Apps.
  • Two update sources — long-polling out of the box (Bot.poll) or your own webhook server (Bot.serveWebhook).
  • Typed helpers, not raw JSON, for keyboards (InlineKeyboardMarkup, ReplyKeyboardMarkup), media (InputMedia*), permissions (ChatPermissions, ChatAdministratorRights), and — optionally, if you want it — incoming User/Chat/Message payloads.
  • Optional rate limiting — pass Bot(rateLimiter: RateLimiter()) to automatically pace outgoing requests instead of handling every 429 yourself.
  • Telegram Mini App support — verify a Web App's signed initData with Bot.verifyWebAppInitData.
  • A low-level escape hatch (Bot.call) for any Bot API method that doesn't have a typed wrapper yet.

Installation

dart pub add ptgb

or add it to pubspec.yaml directly:

dependencies:
  ptgb: ^1.0.0

Getting a bot token

  1. Message @BotFather on Telegram and send /newbot.
  2. Copy the token it gives you (looks like 123456:ABC-your-token-here).
  3. Keep it somewhere safe — never commit it to source control. See Quick Start below for the recommended way to load it.

Quick start

Recommended: put your token in a .env file next to your script and let ptgb load it for you automatically (via the penv package):

TOKEN=123456:ABC-your-token-here
import 'package:ptgb/ptgb.dart';

Future<void> main() async {
  final bot = Bot(); // reads TOKEN from .env

  await for (final update in bot.poll()) {
    if (update.text == '/start') {
      await bot.sendMessage(update.chatId!, 'Hello from ptgb!');
    }
  }
}

Using a different filename or key? Pass dotFileName and/or envKey:

final bot = Bot(dotFileName: 'secrets.env', envKey: 'BOT_TOKEN');

Add .env to your .gitignore so it never gets committed.

Alternative: pass the token directly if you're managing it yourself, e.g. from a secrets manager at deploy time:

final bot = Bot(token: myTokenFromSomewhereElse);

Either way works — just never hard-code a real token as a literal string in code that ends up in version control.

Examples

The example/ folder has a full, numbered set of runnable programs, from a minimal echo bot up to a "god mode" bot exercising keyboards, media, payments, stickers, invite links, and webhooks. Start with example/README.md for the full list and reading order.

Things to keep in mind

  • Treat your token like a password. Anyone who has it can control your bot. Keep it out of version control.
  • poll() and serveWebhook() are mutually exclusive. Telegram only delivers updates through one channel at a time — call setWebhook before using webhooks, and deleteWebhook before switching back to polling.
  • ptgb does not retry or throttle requests for you by default. Every failed call throws a TelegramApiException; wrap your update handling in try/catch so one bad call (blocked user, rate limit, invalid chat_id) doesn't crash your whole process. See example/15_error_handling_and_retries.dart. If you'd rather pace requests proactively, pass Bot(rateLimiter: RateLimiter()) — see example/17_rate_limiting.dart.
  • Inline query results are raw JSON Maps, not typed classes — there are many result types (article, photo, gif, ...) with very different shapes, so this is intentional for now.
  • Incoming User/Chat/Message payloads are raw JSON by default, with optional typed wrappers available. Update's own getters (.message, .chat, .from, ...) still return raw Json for zero-overhead access. Wrap the result in User/Chat/Message (Message(update.message!)) when you want typed getters instead — see example/18_typed_message_helpers.dart. These are common class names, so if another package you're using also exports a User, Chat, or Message, import one of them with a prefix to disambiguate.
  • Requires Dart SDK ^3.5.0.

Contributing

Bug reports, feature requests, and pull requests are welcome on GitHub. If you're filing a bug, a minimal reproduction and the relevant Bot API method name help a lot.

License

MIT — see the LICENSE file for details.

Libraries

ptgb
ptgb — a full, pure-Dart Telegram Bot API client.