### Initializing and Managing a Televerse Bot in Dart Source: https://github.com/xooniverse/televerse/blob/main/example/README.md This snippet demonstrates the full lifecycle of a Televerse bot, from initialization with an environment token to handling various types of incoming updates. It covers setting up command listeners, regular expression matching for message content, creating custom reply keyboards, implementing advanced message filtering based on message properties, extracting specific message entities, and managing interactive keyboard menus. ```Dart import 'dart:io'; import 'package:televerse/televerse.dart'; // This is a general example of how to use the Televerse library. void main() async { // Get the bot token from the environment final String token = Platform.environment["BOT_TOKEN"]!; // Create a new bot instance final bot = Bot(token); // Listen to commands bot.command("hello", (ctx) async => await ctx.reply("Hello!")); // Setup the /start command handler bot.command('start', (ctx) async => await ctx.reply("Hello!")); // Sets up the /settings command listener bot.settings((ctx) async => await ctx.reply("Settings")); // Sets up the /help command listener bot.help((ctx) async => await ctx.reply("Help")); // The [bot.hears] method allows you to listen to messages that match a regular expression. // You can use the `Context.matches` getter to access the matches of the regular expression. bot.hears(RegExp(r'Hello, (.*)!'), (ctx) async { RegExpMatch match = ctx.matches![0]; final name = match.group(1); await ctx.reply('$name must be doing great!'); }); // Usage of Keyboard // Televerse provided a handy way to create keyboards and inline keyboards. final keyboard = Keyboard() .addText("Hello") .addText("World") .row() .requestLocation("Send Location") .oneTime() .resized(); // Now you can simply send the keyboard as the replyMarkup for sendMessage or other methods in RawAPI bot.command("keyboard", (ctx) async { await ctx.reply("Here is the keyboard!", replyMarkup: keyboard); }); // Let's go a little bit advanced mode now. Televerse has a handy Bot.filter method // to add your own filtering process to cherry pick the updates you want to process. // // For example, let's create a method that accepts `Context` and returns true if // the incoming message is a photo and the photo's size is larger than 1 MB. bool myAdvancedFilter(Context ctx) { return ctx.message?.photo?.any((photo) { return photo.fileSize! > 1 * 1000 * 1024; }) ?? false; } // Now you can use the filter method in the Bot.filter and specifically listen for // Photo messages with size greater than 1 MB. bot.filter(myAdvancedFilter, (ctx) async { // This will only be executed if the filter returns true // That is if the photo is bigger than 1MB await ctx.reply("Oh wow, this is a big photo!"); }); // You can also listen for particular message entities. bot.entity(MessageEntityType.mention, (ctx) async { // And use the `Message.geteEntityText` method to extract the value. await ctx.reply( "${ctx.message?.getEntityText(MessageEntityType.mention)} was mentioned!", ); }); // Menu Example final menu = KeyboardMenu(); menu.text('Hello', (ctx) async { await ctx.reply('World!'); }); // Add a button labeled 'Roses', which will make the bot reply with 'are red' when pressed menu.text('Roses', (ctx) async { await ctx.reply('are red'); }); // Important: Attach the menu to the bot bot.attachMenu(menu); // Present the menu to the user bot.command('menu', (ctx) async { await ctx.reply('Here is a Keyboard Menu:', replyMarkup: menu); }); // Finally start the bot await bot.start(); } ``` -------------------------------- ### Creating and Sending a Custom Keyboard (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This example shows how to create a custom reply keyboard using Televerse's `Keyboard` utility class and send it in response to a `/keyboard` command. It defines buttons for 'Account', 'Referral', and 'Settings', arranging them into rows and resizing the keyboard. ```Dart bot.command('keyboard', (ctx) async { final keyboard = Keyboard() .text("Account") .text("Referral") .row() .text("Settings") .resized(); await ctx.reply( "Choose an option:", replyMarkup: keyboard, ); }); ``` -------------------------------- ### Starting Televerse Bot Polling (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This Dart snippet initiates the bot's polling mechanism, enabling it to start receiving updates such as messages and commands from the Telegram servers. It is crucial to `await` this call to ensure proper bot initialization and to fetch details like its username. ```dart await bot.start(); ``` -------------------------------- ### Attaching a Keyboard Menu with Handlers (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This example demonstrates how to create and attach a `KeyboardMenu` to a Televerse bot, binding specific handler methods to menu buttons. It defines 'Account', 'Referral', and 'Settings' buttons, each triggering a distinct asynchronous function when tapped, and then attaches this menu to the bot for use with a `/start` command. ```Dart // Define handler methods Future accountHandler(Context ctx) async { await ctx.replyWithPhoto(InputFile.fromFile(File("hello.png"))); await ctx.reply("Here's your account details..."); } // Define menu options final menu = KeyboardMenu() .text("Account", accountHandler) .text("Referral", referralHandler) .text("Settings", settingsHandler) .resized(); // Attach menu to bot bot.attachMenu(menu); // Start bot bot.command('start', (ctx) async { await ctx.reply( "Hello, I am ${ctx.me.firstName}. Let's start.", replyMarkup: menu, ); }); ``` -------------------------------- ### Implementing Global Error Handling (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This example demonstrates how to set up a global error handler using `Bot.onError` to catch uncaught exceptions from any bot handlers. It logs the error details, including the error object and stack trace, using Dart's `log` function for debugging. ```Dart import 'dart:developer'; // ... bot.onError((err) { log( "Something went wrong: $err", error: err.error, stackTrace: err.stackTrace, ); }); ``` -------------------------------- ### Creating an Auto-Reply Transformer in Televerse (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This example shows how to implement a transformer to automatically add a `ForceReply` markup to outgoing messages. It checks if the API method is a 'send' method (excluding `sendChatAction`) and then modifies the payload to include the reply markup before the request is sent to the Telegram API. ```Dart class AutoReplyEnforcer implements Transformer { @override Future> transform( APICaller call, APIMethod method, [ Payload? payload, ]) async { final isSendMethod = APIMethod.sendMethods.contains(method); final isNotChatAction = method != APIMethod.sendChatAction; if (isSendMethod && isNotChatAction) { payload!.params["reply_markup"] = ForceReply().toJson(); } return await call(method, payload); } } // Usage bot.use(AutoReplyEnforcer()); ``` -------------------------------- ### Handling Telegram /start Command (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This Dart snippet demonstrates how to register a command handler for the `/start` command using `bot.command`. When a user sends `/start` to the bot, the provided asynchronous callback function will be executed, sending 'Hello, World!' back to the user. ```dart bot.command('start', (ctx) async { await ctx.reply('Hello, World!'); }); ``` -------------------------------- ### Listening for Custom Command (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This Dart snippet demonstrates how to set up a listener for a custom command, in this case, `/hello`. When a user sends `/hello` to the bot, the provided asynchronous callback function will be executed, allowing the bot to reply with 'Hello World 👋' and perform other actions. ```dart bot.command("hello", (ctx) async { await ctx.reply("Hello World 👋"); // ... }); ``` -------------------------------- ### Initializing Televerse Bot Instance (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This Dart snippet initializes a new `Bot` instance by providing your unique Telegram bot token. This `Bot` instance serves as the primary entry point for interacting with the Telegram Bot API and managing all bot-related operations. ```dart Bot bot = Bot('YOUR_BOT_TOKEN'); ``` -------------------------------- ### Initializing Bot with Local API Server (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This Dart snippet demonstrates how to initialize a Televerse bot instance to connect to a local Telegram Bot API server. It uses the `Bot.local` constructor, allowing you to specify a custom `baseURL` for your self-hosted API server instead of the default Telegram servers. ```dart final Bot bot = Bot.local( "YOUR_BOT_TOKEN", baseURL: "mybotapi.com", ); ``` -------------------------------- ### Implementing a Conversation Flow (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This snippet shows how to use Televerse's `Conversation` API to manage multi-step interactions with users. It initiates a conversation on the `/start` command, asks for the user's name, and then waits for a text message reply to continue the conversation. ```Dart // Create your bot instance final bot = Bot( "YOUR_BOT_TOKEN", ); // Create the Conversation API instance final conv = Conversation(bot); bot.command('start', (ctx) async { await ctx.reply("Hello, I am ${ctx.me.firstName}. What should I call you?"); // Now wait you can wait for the user's reply message. Easy, right? final nameCtx = await conv.waitForTextMessage(chatId: ctx.id); await nameCtx?.reply("Good to meet you, ${ctx.message?.text}"); }); ``` -------------------------------- ### Initializing Bot with Network Interceptor Options (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This snippet demonstrates how to initialize a Televerse `Bot` instance with custom `LoggerOptions`. It enables logging of request bodies, request headers, and response bodies for specific API methods like `sendMessage` and `sendPhoto`, providing detailed network interception capabilities. ```Dart final bot = Bot( "YOUR_BOT_TOKEN", loggerOptions: LoggerOptions( requestBody: true, requestHeader: true, responseBody: true, methods: [ APIMethod.sendMessage, APIMethod.sendPhoto, ], ), ); ``` -------------------------------- ### Adding Televerse Dependency (YAML) Source: https://github.com/xooniverse/televerse/blob/main/README.md This YAML snippet shows how to add the Televerse package as a dependency to your Dart project's `pubspec.yaml` file. Replace `` with the desired version of the Televerse package to ensure you're using the most up-to-date features. ```yaml dependencies: televerse: ``` -------------------------------- ### Importing Televerse Package (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This Dart snippet demonstrates how to import the Televerse package into your Dart code. Importing the package makes all its classes, functions, and utilities available for use in your bot application, allowing you to build Telegram bots. ```dart import 'package:televerse/televerse.dart'; ``` -------------------------------- ### Handling Updates in Serverless Environment (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This Dart snippet illustrates how to manually handle updates in a serverless environment, such as Cloud Functions or Lambda. It decodes the incoming JSON event body into an `Update` object and then passes it to `bot.handleUpdate` for processing by the bot's configured listeners. ```dart final json = jsonDecode(event.body); final update = Update.fromJson(json); bot.handleUpdate(update); ``` -------------------------------- ### Implementing Logging Middleware in Televerse (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This snippet demonstrates how to create a logging middleware in Televerse. It implements the `Middleware` interface to intercept updates, print the received update context, and then pass control to the next function in the chain. It's useful for debugging or monitoring incoming messages. ```Dart class LoggingMiddleware implements Middleware { @override Future handle( Context ctx, NextFunction next, ) async { print('Received update: ${ctx.update}'); await next(); } } // Usage bot.use(LoggingMiddleware()); ``` -------------------------------- ### Chaining Scope-Level Middlewares for Commands in Televerse (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This snippet illustrates how to apply a chain of middlewares to a specific command using `ScopeOptions.chain`. It defines an `adminCheck` middleware to restrict access to a command based on user ID and then applies it to the '/admin' command, ensuring only authorized users can execute it. ```Dart // Define middleware functions final admins = [12345, 67890]; MiddlewareFunction adminCheck = (ctx, next) async { if (!admins.contains(ctx.id.id)) return; return next(); }; // Apply middleware chain to specific commands bot.command( 'admin', (ctx) async { await ctx.reply("Hello Admin!"); }, options: ScopeOptions.chain([adminCheck]), ); ``` -------------------------------- ### Filtering Updates by Photo Size (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This Dart snippet illustrates how to create a custom filter to process specific updates based on criteria. It listens for messages that contain a photo with a file size greater than 1MB and replies with a specific message if the condition is met, demonstrating advanced update handling. ```dart bot.filter((ctx) { return (ctx.message.photo?.last.fileSize ?? 0) > 1000000; }, (ctx) { ctx.reply('Wow, that\'s a big photo!'); }); ``` -------------------------------- ### Creating a Custom Listener Filter (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This snippet illustrates how to define a custom listener method using `Bot.filter` to process messages based on a specific condition. It filters for photo messages where the last photo's file size exceeds 1MB and then replies with a congratulatory message. ```Dart bot.filter((ctx) { return (ctx.message.photo?.last.fileSize ?? 0) > 1000000; }, (ctx) async { ctx.reply('Wow, that\'s a big photo!'); }); ``` -------------------------------- ### Sending Message via Context API (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This Dart snippet shows how to send a message to a specific chat from within a callback function using the `ctx.api` property. This provides convenient access to Telegram Bot API methods, allowing you to respond directly within the context of an update. ```dart ctx.api.sendMessage(ChatID(123456), "Hello, World!"); ``` -------------------------------- ### Sending Message via Bot API (Dart) Source: https://github.com/xooniverse/televerse/blob/main/README.md This Dart snippet illustrates how to send a message to a specific chat using the `bot.api` getter, which provides direct access to the Telegram Bot API methods. It requires a `ChatID` object for the target chat and the message text as parameters. ```dart bot.api.sendMessage(ChatID(123456), "Hello, World!"); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.