feat(bot): implement conversation flow for start command

add conversation handler for start command with name input and welcome message
update locales for new conversation flow
add @grammyjs/conversations dependency
This commit is contained in:
Yuu Ottosoka
2025-07-12 17:15:32 +03:00
parent df8bfa049f
commit 0ceba57012
10 changed files with 57 additions and 4 deletions

View File

@@ -0,0 +1,3 @@
export enum ConversationSlug {
START = 'start',
}

View File

@@ -0,0 +1,2 @@
export * from './consts';
export * from './start.conversation';

View File

@@ -0,0 +1,23 @@
import { Conversation, createConversation } from '@grammyjs/conversations';
import { BotContext } from '../types';
import { ConversationSlug } from './consts';
async function enterConversation(conversation: Conversation, ctx: BotContext) {
const askNameText = await conversation.external((ctx: BotContext) =>
ctx.t('start-ask-name')
);
await ctx.reply(askNameText);
const { message } = await conversation.waitFor('message:text');
const welcomeText = await conversation.external((ctx: BotContext) =>
ctx.t('start-welcome', { user: message.text })
);
await ctx.reply(welcomeText);
}
export const startConversation = createConversation(
enterConversation,
ConversationSlug.START
);

View File

@@ -8,6 +8,8 @@ import { BotContext } from './types';
import { upsertUser } from './middlewares/upsert-user';
import { onError } from './middlewares/on-error';
import { I18n } from '@grammyjs/i18n';
import { conversations } from '@grammyjs/conversations';
import { ConversationSlug, startConversation } from './conversations';
const bot = new Bot<BotContext>(config.BOT_TOKEN);
const storage = new PrismaStorageAdapter();
@@ -20,6 +22,7 @@ const i18n = new I18n<BotContext>({
defaultLocale: 'ru',
useSession: true, // whether to store user language in session
directory: 'locales', // Load all translation files from locales/.
fluentBundleOptions: { useIsolating: false },
localeNegotiator: async (ctx) => {
const session = await ctx.session;
return session.__language_code ?? ctx.from?.language_code ?? 'ru';
@@ -27,9 +30,11 @@ const i18n = new I18n<BotContext>({
});
bot.use(i18n);
bot.use(conversations());
bot.use(startConversation);
bot.command('start', async (ctx) => {
await ctx.reply(ctx.t('start'));
await ctx.conversation.enter(ConversationSlug.START);
});
if (config.MODE === 'webhook') {

View File

@@ -1,6 +1,9 @@
import { ConversationFlavor } from '@grammyjs/conversations';
import { I18nFlavor } from '@grammyjs/i18n';
import { Context, LazySessionFlavor } from 'grammy';
// config your session data
export type SessionData = { __language_code?: string };
export type BotContext = Context & LazySessionFlavor<SessionData> & I18nFlavor;
export type BotContext = ConversationFlavor<
Context & LazySessionFlavor<SessionData> & I18nFlavor
>;