|
| 1 | +# grammY stream |
| 2 | + |
| 3 | +Stream long text messages to Telegram. |
| 4 | +Make LLM output appear as animated message drafts before sending the message. |
| 5 | +Automatically split long text across several messages. |
| 6 | + |
| 7 | +## Quickstart |
| 8 | + |
| 9 | +Run `npm i grammy @grammyjs/stream @grammyjs/auto-retry` and paste the following code: |
| 10 | + |
| 11 | +```ts |
| 12 | +import { Bot, type Context } from "grammy"; |
| 13 | +import { autoRetry } from "@grammyjs/auto-retry"; |
| 14 | +import { stream, type StreamFlavor } from "@grammyjs/stream"; |
| 15 | + |
| 16 | +type MyContext = StreamFlavor<Context>; |
| 17 | + |
| 18 | +const bot = new Bot<MyContext>(""); |
| 19 | + |
| 20 | +bot.api.config.use(autoRetry()); |
| 21 | +bot.use(stream()); |
| 22 | + |
| 23 | +async function* slowText() { |
| 24 | + // emulate slow text generation |
| 25 | + yield "This i"; |
| 26 | + await new Promise((r) => setTimeout(r, 1000)); |
| 27 | + yield "s some sl"; |
| 28 | + await new Promise((r) => setTimeout(r, 1000)); |
| 29 | + yield "owly gene"; |
| 30 | + await new Promise((r) => setTimeout(r, 1000)); |
| 31 | + yield "rated text"; |
| 32 | +} |
| 33 | + |
| 34 | +bot.command("stream", async (ctx) => { |
| 35 | + await ctx.replyWithStream(slowText()); |
| 36 | +}); |
| 37 | + |
| 38 | +bot.command("start", (ctx) => ctx.reply("Hi! Send /stream")); |
| 39 | +bot.use((ctx) => ctx.reply("What a nice update.")); |
| 40 | + |
| 41 | +bot.start(); |
| 42 | +``` |
| 43 | + |
| 44 | +For example, if you use the [AI SDK](https://ai-sdk.dev), your AI setup could look like this: |
| 45 | + |
| 46 | +```ts |
| 47 | +import { streamText } from "ai"; |
| 48 | +import { google } from "npm:@ai-sdk/google"; |
| 49 | + |
| 50 | +bot.command("credits", async (ctx) => { |
| 51 | + // Send prompt to LLM: |
| 52 | + const { textStream } = streamText({ |
| 53 | + model: google("gemini-2.5-flash"), |
| 54 | + prompt: "How cool are grammY bots?", |
| 55 | + }); |
| 56 | + |
| 57 | + // Automatically stream response with grammY: |
| 58 | + await ctx.replyWithStream(textStream); |
| 59 | +}); |
| 60 | +``` |
0 commit comments