ktgbotapi-patterns
Telegram bot architecture patterns (ktgbotapi 33.x) — project structure, modular handlers, DI via Metro (standalone) or Spring (embedded in backend), callback models, keyboards, utils. Always use the versions listed below; never regress to ktgbotapi 31.x. Koin is no longer recommended — use Metro for compile-time safety.
What this skill does
# KTgBotAPI Architecture Patterns
Patterns for organizing Telegram bot projects with ktgbotapi.
## Current Versions (use these — do not downgrade)
| Component | Version | Notes |
|---|---|---|
| ktgbotapi | **33.1.0** | See `ktgbotapi` skill for v32→v33 breaking changes (BotToken value class, Unit return types, Poll API). |
| Metro | **1.0.0** | Default DI for standalone bots — compile-time graph, no runtime crashes. See `metro-di-mobile` skill. |
| Spring Boot | **3.4.x** | Use Spring DI when bot lives inside a full backend (sharing services, DB, observability). See `kotlin-spring-boot` skill. |
| Ktor client | **3.4.3** | See `ktor-client` skill for client patterns. |
| Kotlin | **2.3.21** | |
> **Koin is intentionally not in this skill anymore.** Earlier revisions documented Koin 4.x as the default. We removed it because: (1) compile-time DI catches missing bindings before deploy — Telegram bots can run for weeks without hitting a code path, so a runtime DI miss is found by users, not CI; (2) for monostack setups (mobile + bot + backend on Metro), one DI framework everywhere wins over two; (3) when the bot is part of a Spring backend, Spring DI is already there. If a project genuinely needs Koin (KMP bot sharing modules with a Koin-driven mobile app, or hot-reload module swapping), apply Koin manually — but don't take it from this skill.
## Project Structure
```
src/main/kotlin/com/example/bot/
├── Application.kt # Entry point
├── di/
│ ├── BotGraph.kt # Metro @DependencyGraph (standalone)
│ └── BotPlatformModule.kt # @BindingContainer with @Provides for HttpClient, Json, env config
├── config/
│ └── BotConfig.kt # Bot configuration value class
├── handlers/
│ ├── CommandHandlers.kt # /start, /help, etc.
│ ├── MessageHandlers.kt # Text message handlers
│ ├── CallbackHandlers.kt # Inline button callbacks
│ └── MediaHandlers.kt # Photo, document, etc.
├── keyboards/
│ ├── InlineKeyboards.kt # Inline keyboard builders
│ └── ReplyKeyboards.kt # Reply keyboard builders
├── fsm/
│ ├── States.kt # FSM state definitions
│ └── StateHandlers.kt # State transition handlers
├── api/
│ ├── BackendApiService.kt # HTTP calls to backend (see ktor-client skill)
│ └── ApiModels.kt # Request/Response DTOs
├── services/
│ ├── UserService.kt # Business logic
│ └── NotificationService.kt
├── models/
│ ├── User.kt # Domain models
│ └── CallbackData.kt # Callback payload models
└── utils/
├── Extensions.kt # Useful extensions
└── Formatters.kt # Text formatting helpers
```
> **Note:** For backend API communication patterns, see the `ktor-client` skill. Embedded-in-Spring deployment uses Spring's project structure (`@Service`, `@Configuration`) instead of `di/` — see "DI: Spring Boot variant" below.
## Modular Handler Pattern
### Application Entry Point
```kotlin
// Application.kt — standalone bot with Metro
suspend fun main() {
val graph = createGraph<BotGraph>()
val bot = graph.telegramBot
bot.buildBehaviourWithLongPolling(
defaultExceptionsHandler = { logger.error("Bot error", it) }
) {
with(graph.commandHandlers) { register() }
with(graph.messageHandlers) { register() }
with(graph.callbackHandlers) { register() }
with(graph.mediaHandlers) { register() }
}.join()
}
```
Each handler class exposes `suspend fun BehaviourContext.register()` as an extension on its enclosing class — see "Modular Handler Pattern" below.
### Handler Modules
Handlers are classes with constructor-injected dependencies. They expose `register()` as an extension on `BehaviourContext`, which keeps the DSL receiver while still letting the handler hold injected services.
```kotlin
// handlers/CommandHandlers.kt
@Inject
class CommandHandlers(
private val userService: UserService,
) {
suspend fun BehaviourContext.register() {
onCommand("start") { message ->
reply(message, "Welcome!", replyMarkup = ReplyKeyboards.main())
}
onCommand("help") { message ->
reply(message, HelpTexts.commands())
}
onCommand("profile") { message ->
val user = userService.findByChatId(message.chat.id.chatId)
reply(message, user?.let { "Name: ${it.name}" } ?: "Not registered")
}
onDeepLink { message, deepLink -> handleDeepLink(message, deepLink) }
}
}
// handlers/MessageHandlers.kt
@Inject
class MessageHandlers {
suspend fun BehaviourContext.register() {
onText(initialFilter = { it.content.text == "📋 Menu" }) { showMenu(it) }
onText(initialFilter = { it.content.text == "⚙️ Settings" }) { showSettings(it) }
}
}
// handlers/CallbackHandlers.kt
@Inject
class CallbackHandlers(
private val api: BackendApiService,
) {
suspend fun BehaviourContext.register() {
onDataCallbackQuery(Regex("menu:.*")) { handleMenuCallback(it) }
onDataCallbackQuery(Regex("item:.*")) { handleItemCallback(it, api) }
onDataCallbackQuery(Regex("page:.*")) { handlePaginationCallback(it) }
}
}
```
> **Why extension on `BehaviourContext` inside a class?** ktgbotapi's DSL (`onCommand`, `onText`, ...) requires `BehaviourContext` as receiver. Free-standing extension functions can't carry constructor state, so we put the extension *inside* the class — `register()` is a member extension, the class holds dependencies, and the DSL receiver flows in at the call site (`with(graph.commandHandlers) { register() }`).
## Callback Data Models
Type-safe callback data parsing:
```kotlin
// models/CallbackData.kt
sealed class CallbackData {
abstract fun encode(): String
// Menu actions
data class Menu(val action: String) : CallbackData() {
override fun encode() = "m:$action"
}
// Item operations
data class Item(val action: String, val id: String) : CallbackData() {
override fun encode() = "i:$action:$id"
}
// Pagination
data class Page(val list: String, val page: Int) : CallbackData() {
override fun encode() = "p:$list:$page"
}
// Confirmation
data class Confirm(val action: String, val id: String) : CallbackData() {
override fun encode() = "c:$action:$id"
}
companion object {
fun parse(data: String): CallbackData? {
val parts = data.split(":")
return when (parts.getOrNull(0)) {
"m" -> Menu(parts[1])
"i" -> Item(parts[1], parts[2])
"p" -> Page(parts[1], parts[2].toInt())
"c" -> Confirm(parts[1], parts[2])
else -> null
}
}
}
}
// Usage in handlers
suspend fun BehaviourContext.setupCallbackHandlers() {
onDataCallbackQuery { query ->
when (val cb = CallbackData.parse(query.data)) {
is CallbackData.Menu -> handleMenu(query, cb.action)
is CallbackData.Item -> handleItem(query, cb.action, cb.id)
is CallbackData.Page -> handlePage(query, cb.list, cb.page)
is CallbackData.Confirm -> handleConfirm(query, cb.action, cb.id)
null -> answer(query, "Unknown action")
}
}
}
// Usage in keyboard builders
fun itemKeyboard(itemId: String) = inlineKeyboard {
row {
dataButton("✏️ Edit", CallbackData.Item("edit", itemId).encode())
dataButton("🗑 Delete", CallbackData.Item("delete", itemId).encode())
}
}
```
## Keyboard Builders
### Inline Keyboards Object
```kotlin
// keyboards/InlineKeyboards.kt
object InlineKeyboards {
fun mainMenu() = inlineKeyboard {
row { dataButton("📊 Statistics", "m:stats") }
row {
dataButton("👤 Profile", "m:profile")
dataButton("⚙️ Settings", "m:settings")
}
row { urlButton("📖 Help", "https://example.com/help") }
}
fRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.