Skip to content

Instantly share code, notes, and snippets.

@waptik
Last active December 18, 2023 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waptik/c0f38ec1ab2895a21162c9f3b3a5969b to your computer and use it in GitHub Desktop.
Save waptik/c0f38ec1ab2895a21162c9f3b3a5969b to your computer and use it in GitHub Desktop.
a simple pagination handler in grammY using the menu plugin
let pageIndex = 0;
/**
* A function that generates a paginated menu
*
* @param index The index of the page to generate
* @returns A range of the menu
*/
function personalityMenuRange(
userId: number,
index: number,
range: MenuRange<Context>,
) {
pageIndex = index;
const personasPerPage = 5;
const personasKeys = Object.keys(config.personas) as Array<
keyof typeof config.personas
>;
const currentPagePersonasKeys = personasKeys.slice(
pageIndex * personasPerPage,
(pageIndex + 1) * personasPerPage,
);
// Generate a part of the menu dynamically!
for (const personaKey of currentPagePersonasKeys) {
const persona = config.personas[personaKey];
range.text(persona.name, async (ctx) => {
await registerUser(ctx, ctx.chat!.id, ctx.from!);
const user = await db.getUserById(ctx.from!.id);
let current_conversation_id = user.current_conversation_id;
if (user.current_model !== 'artist') {
if (personaKey === 'artist') {
current_conversation_id = undefined;
} else {
current_conversation_id = user.current_conversation_id;
}
} else {
if (personaKey !== 'artist') {
current_conversation_id = undefined;
} else {
current_conversation_id = user.current_conversation_id;
}
}
await db.setUserAttributes(
ctx.from!.id,
{ 'current_chat_mode': personaKey, current_conversation_id },
);
await ctx.editMessageText(persona.welcome_message, {
parse_mode: 'HTML',
});
ctx.menu.close();
}).row();
}
if (personasKeys.length > personasPerPage) {
const isFirstPage = pageIndex === 0;
const isLastPage =
(pageIndex + 1) * personasPerPage >= personasKeys.length;
if (isFirstPage) {
range.submenu(
'👉',
`bot-personas-menu-page`,
() => {
pageIndex++;
},
);
} else if (isLastPage) {
range.submenu(
'👈',
`bot-personas-menu-page`,
() => {
pageIndex--;
},
);
} else {
range
.submenu(
'👈',
`bot-personas-menu-page`,
() => {
pageIndex--;
},
)
.submenu(
'👉',
`bot-personas-menu-page`,
() => {
pageIndex++;
},
);
}
}
return range;
}
export const personasMenu = new Menu<Context>('bot-personas-menu')
.dynamic((ctx, range) => personalityMenuRange(ctx.from!.id, 0, range));
const paginationMenu = new Menu<Context>(
`bot-personas-menu-page`,
).dynamic((ctx, range) => personalityMenuRange(ctx.from!.id, pageIndex, range));
personasMenu.register(paginationMenu);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment