Conversation Plugin
Create multi-step interactions and wizards easily.
The Conversation Plugin makes it easy to build multi-step interactions where your bot needs to wait for user input. Instead of managing complex state machines manually, you can write linear, readable code that "pauses" execution until the user replies.
Installation
Import the plugin from the main package.
import 'package:televerse/plugins/conversation.dart';Basic Usage
Conversations are defined as functions that take a Conversation object and a Context.
1. Define the Conversation
Future<void> welcomeConversation(
Conversation<Context> conversation,
Context ctx
) async {
await ctx.reply("Welcome! What is your name?");
// Wait for the next text message
final nameCtx = await conversation.wait();
await nameCtx.reply("Nice to meet you, ${nameCtx.text}! Now, how old are you?");
// Wait again...
final ageCtx = await conversation.wait();
await ageCtx.reply("Got it! You are ${ageCtx.text} years old.");
}2. Register and Trigger
void main() {
final bot = Bot("TOKEN");
// 1. Install the plugin
bot.plugin(ConversationPlugin());
// 2. Register usage of the conversation
bot.use(createConversation("welcome", welcomeConversation));
// 3. Trigger it
bot.command("start", (ctx) async {
await ctx.conversation.enter("welcome");
});
bot.start();
}Waiting for Specific Input
Often you don't just want any update, but specific input (like a photo, or text matching a regex). The conversation handle provides methods for this.
waitFor(predicate)
Wait until an update matches a specific condition.
// Wait until we receive a photo
final photoCtx = await conversation.waitFor(
(ctx) => ctx.msg?.photo != null
);waitUntil(predicate, otherwise)
Like waitFor, but allows you to give feedback if the user sends the wrong thing.
final numberCtx = await conversation.waitUntil(
(ctx) => int.tryParse(ctx.text ?? '') != null,
otherwise: (ctx) async {
await ctx.reply("That's not a number! Please try again.");
},
);Handling Timeouts
Conversations shouldn't stall forever. You can define timeouts to stop waiting if the user disappears.
try {
await ctx.reply("Quick! Type 'yes' in 10 seconds!");
final response = await conversation.wait(
timeout: Duration(seconds: 10),
);
await response.reply("You made it!");
} on ConversationTimeoutException {
await ctx.reply("Too slow! 🐢");
}You can also set a default timeout when installing the plugin:
bot.plugin(ConversationPlugin(
defaultTimeout: Duration(minutes: 5),
));Persistence and Storage
Like sessions, conversations need to be stored, especially if your bot restarts. The ConversationPluginsupports custom storage backends just like the Session Plugin.
By default, it uses memory storage. For production, pass a persistent storage implementation to thestorage parameter of the plugin constructor.