Appearance
Context in Telegram Bot Implementation
Overview
Our Telegram bot implementation is built on grammY, a powerful framework for Telegram bots. We leverage grammY's context system and extend it with our own functionality to provide seamless integration with our services.
grammY Context
grammY's Context object is a fundamental part of the framework. It provides access to information about messages and allows performing actions in response.
For comprehensive documentation about the original context implementation, please refer to the official grammY documentation on Context.
The original Context provides: - Access to message information via ctx.message
, ctx.msg
, etc. - Methods to respond to users via ctx.reply
, ctx.replyWithPhoto
, etc. - Access to the Bot API via ctx.api
- And much more...
Our Extended Context
We've extended the grammY Context to integrate with our NestKit ecosystem by incorporating our ServiceMethodContext
. This extension enables:
- User Authentication: Access to the current authenticated user via
ctx.user
- Permission Management: Utilizing
isGranted
andvalidateAccess
methods - Request Tracking: Via
requestId
for logging and debugging
Example Usage
typescript
// In a command handler
async run(ctx: GrammyContext): Promise<void> {
// Access the authenticated user
if (!ctx.isGuest()) {
const fullName = ctx.user.fullName;
await ctx.reply(`Hello, ${fullName}!`);
// Check permissions
if (ctx.isGranted('ugi:core:documents:get')) {
// Perform admin actions
}
} else {
// Handle guest users
await ctx.conversation.enter(OnboardingConversation.name);
}
}
Guest vs Authenticated Users
Our context extension provides the isGuest()
method to easily determine if the current user is authenticated:
typescript
if (ctx.isGuest()) {
// User is not authenticated
await ctx.conversation.enter(OnboardingConversation.name);
} else {
// User is authenticated, we can access ctx.user
await ctx.reply(`Welcome back, ${ctx.user.fullName}!`);
}
Using Context with Services
One of the key benefits of our extended context is the ability to pass it directly to service methods:
typescript
// In a command handler or middleware
await this.userService.update(opts, ctx);
Conclusion
By extending the grammY Context with our ServiceMethodContext
, we've created a seamless bridge between the Telegram bot and our application services. This allows for consistent authentication, permission checking, and logging across both our API and bot interfaces.