{"id":30907357,"url":"https://github.com/nerzh/swift-telegram-bot","last_synced_at":"2025-12-11T22:54:30.738Z","repository":{"id":43536865,"uuid":"371458616","full_name":"nerzh/swift-telegram-bot","owner":"nerzh","description":"🤖 The wrapper for the Telegram Bot API written in Swift. It's not a framework. There is no special syntax here. This is a library that implements all Telegram Bot API methods, which is available to you to work with Vapor, Smoke, Hummingbird, FlyingFox. https://core.telegram.org/bots/api","archived":false,"fork":false,"pushed_at":"2025-09-21T11:48:49.000Z","size":1448,"stargazers_count":255,"open_issues_count":1,"forks_count":36,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-11-28T06:44:51.518Z","etag":null,"topics":["bot","mini-app","server-side-swift","swift","telegram","telegram-bot","telegram-bot-api","telegram-mini-app-bot","vapor"],"latest_commit_sha":null,"homepage":"https://core.telegram.org/bots/samples","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nerzh.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2021-05-27T17:49:55.000Z","updated_at":"2025-11-16T00:14:42.000Z","dependencies_parsed_at":"2024-04-22T02:48:54.073Z","dependency_job_id":"49e5a77b-8eae-4402-be49-0007e8d9c8a4","html_url":"https://github.com/nerzh/swift-telegram-bot","commit_stats":{"total_commits":104,"total_committers":4,"mean_commits":26.0,"dds":0.08653846153846156,"last_synced_commit":"256e24a1cd6a4db2ff97c2a3365f44fb383c2a1a"},"previous_names":["nerzh/swift-telegram-sdk","nerzh/telegram-vapor-bot","nerzh/swift-telegram-bot"],"tags_count":104,"template":false,"template_full_name":null,"purl":"pkg:github/nerzh/swift-telegram-bot","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nerzh%2Fswift-telegram-bot","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nerzh%2Fswift-telegram-bot/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nerzh%2Fswift-telegram-bot/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nerzh%2Fswift-telegram-bot/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nerzh","download_url":"https://codeload.github.com/nerzh/swift-telegram-bot/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nerzh%2Fswift-telegram-bot/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":27574521,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-12-07T02:00:07.896Z","response_time":53,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bot","mini-app","server-side-swift","swift","telegram","telegram-bot","telegram-bot-api","telegram-mini-app-bot","vapor"],"created_at":"2025-09-09T13:01:49.062Z","updated_at":"2025-12-11T22:54:30.730Z","avatar_url":"https://github.com/nerzh.png","language":"Swift","funding_links":[],"categories":["Telegram Libraries"],"sub_categories":["Swift"],"readme":"# Swift Telegram Bot for Telegram Bot Api (SDK for creating Telegram Bots in Swift)\n\n### Please, support with ⭐️\n\n🤖 The wrapper for the Telegram Bot API written in Swift. It's not a framework. There is no special syntax here. This is a library that implements all [Telegram Bot API methods](https://core.telegram.org/bots/api#available-methods), which is available to you to work with Vapor, Smoke, FlyingFox.\n\n#### Swift Server Side Community\n[Swift Server Side Community - Ukraine / Russian / CIS Telegram Chat](https://t.me/server_side_swift)\n\n# ⚠️ SWIFT 6\n\nFor now with swift 6 please use 4.0.0 and above\n\n# Usage\n- Clone one of [examples](https://github.com/nerzh/swift-telegram-sdk/tree/master/Examples)\n  ```shell\n  git clone https://github.com/nerzh/swift-telegram-bot\n  ```\n  ```\n  cd swift-telegram-bot/Examples/Vapor-Telegram-Bot\n  ```\n- Add your telegram bot id to [configure.swift](https://github.com/nerzh/swift-telegram-bot/blob/master/Examples/Vapor-Telegram-Bot/Sources/Vapor-Telegram-Bot/configure.swift)\n  ```swift\n  let botId: String = \"XXXXXXXXXX:YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY\"\n  ```\n- Run in Xcode or build and run binary file\n- check commands in your telegram bots\n  - /ping\n  - /show_buttons\n# Examples\n- [Vapor Telegram Bot](https://github.com/nerzh/swift-telegram-bot/tree/master/Examples/Vapor-Telegram-Bot)\n- [Hummingbird Telegram Bot (AsyncHttpClient)](https://github.com/nerzh/swift-telegram-bot/tree/master/Examples/Hummingbird-AsyncHttpClient-Telegram-Bot)\n- [Hummingbird Telegram Bot (URLSession)](https://github.com/nerzh/swift-telegram-bot/tree/master/Examples/Hummingbird-URLSession-Telegram-Bot)\n- [Smoke Telegram Bot (AsyncHttpClient)](https://github.com/nerzh/swift-telegram-bot/tree/master/Examples/Smoke-AsyncHttpClient-Telegram-Bot)\n- [FlyingFox Telegram Bot (AsyncHttpClient)](https://github.com/nerzh/swift-telegram-bot/tree/master/Examples/FlyingFox-AsyncHttpClient-Telegram-Bot)\n\n## Bot configuration.\n### Define bot ID\n```swift\nimport SwiftTelegramBot\nimport Logging\n\nlet tgApi: String = \"XXXXXXXXXX:YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY\"\nvar logger: Logger = .init(label: \"swift_telegram_bot\")\nlogger.logLevel = .error\n```\n### Define connection type\n##### LongPolling\n```swift\nlet connectionType: TGConnectionType = .longpolling()\n```\n##### WebHook\n```swift\nlet connectionType: TGConnectionType = .webhook(webHookURL: URL(string: \"\\(TG_WEBHOOK_DOMAIN!)/\\(TGWebHookRouteName)\")!)\n```\n```swift\n/// Add route for webhook. For example Vapor:\n\n/// routes.swift\nfunc routes(_ app: Application) throws {\n    try app.register(collection: TelegramController())\n}\n\n\n/// TelegramController.swift\nfinal class TelegramController: RouteCollection {\n    func boot(routes: Vapor.RoutesBuilder) throws {\n        routes.post(TGWebHookRouteName, use: telegramWebHook)\n    }\n\n    func telegramWebHook(_ req: Request) async throws -\u003e Bool {\n        let update: TGUpdate = try req.content.decode(TGUpdate.self)\n        Task { await bot.processing(updates: [update]) }\n        return true\n    }\n}\n```\n### Start bot with added handlers\n```swift\nlet bot: TGBot = try await .init(connectionType: connectionType,\n                                 tgClient: TGClientDefault(),\n                                 tgURI: TGBot.standardTGURL,\n                                 botId: botId,\n                                 log: logger)\n\n/// add dispatcher with some bot logic\ntry await bot.add(dispatcher: TestDispatcher(bot: bot, logger: logger))\n/// try await bot.add(dispatcher: SecondDispatcher(bot: bot, logger: logger))\n/// etc\n\ntry await bot.start()\n```\n\n### TestDispatcher code example\n```swift\nimport SwiftTelegramBot\n\nclass TestDispatcher: TGDefaultDispatcher, @unchecked Sendable {\n        \n    override\n    func handle() async {\n        /// defaultBaseHandler example\n        await add(TGBaseHandler({ update in\n            guard let message = update.message else { return }\n            let params: TGSendMessageParams = .init(chatId: .chat(message.chat.id), text: \"TGBaseHandler\")\n            try await self.bot.sendMessage(params: params)\n        }))\n\n        /// commandPingHandler example\n        await add(TGCommandHandler(commands: [\"/ping\"]) { update in\n            try await update.message?.reply(text: \"pong\", bot: self.bot)\n        })\n\n        /// commandShowButtonsHandler example\n        await add(TGCommandHandler(commands: [\"/show_buttons\"]) { update in\n            guard let userId = update.message?.from?.id else { fatalError(\"user id not found\") }\n            let buttons: [[TGInlineKeyboardButton]] = [\n                [.init(text: \"Button 1\", callbackData: \"press 1\"), .init(text: \"Button 2\", callbackData: \"press 2\")]\n            ]\n            let keyboard: TGInlineKeyboardMarkup = .init(inlineKeyboard: buttons)\n            let params: TGSendMessageParams = .init(chatId: .chat(userId),\n                                                    text: \"Keyboard active\",\n                                                    replyMarkup: .inlineKeyboardMarkup(keyboard))\n            try await self.bot.sendMessage(params: params)\n        })\n\n        /// buttonsActionHandler 1 example\n        await add(TGCallbackQueryHandler(pattern: \"press 1\") { update in\n            await self.bot.log.info(\"press 1\")\n            guard let userId = update.callbackQuery?.from.id else { fatalError(\"user id not found\") }\n            let params: TGAnswerCallbackQueryParams = .init(callbackQueryId: update.callbackQuery?.id ?? \"0\",\n                                                            text: update.callbackQuery?.data  ?? \"data not exist\",\n                                                            showAlert: nil,\n                                                            url: nil,\n                                                            cacheTime: nil)\n            try await self.bot.answerCallbackQuery(params: params)\n            try await self.bot.sendMessage(params: .init(chatId: .chat(userId), text: \"press 1\"))\n        })\n\n        /// buttonsActionHandler 2 example\n        await add(TGCallbackQueryHandler(pattern: \"press 2\") { update in\n            await self.bot.log.info(\"press 2\")\n            guard let userId = update.callbackQuery?.from.id else { fatalError(\"user id not found\") }\n            let params: TGAnswerCallbackQueryParams = .init(callbackQueryId: update.callbackQuery?.id ?? \"0\",\n                                                            text: update.callbackQuery?.data  ?? \"data not exist\",\n                                                            showAlert: nil,\n                                                            url: nil,\n                                                            cacheTime: nil)\n            try await self.bot.answerCallbackQuery(params: params)\n            try await self.bot.sendMessage(params: .init(chatId: .chat(userId), text: \"press 2\"))\n        })\n    }\n}\n```\n\n# Advanced Example Usage\n## You should to implement TGClientPrtcl protocol\nTo configure and run a bot with or without any framework, you need to use TGClientDefault or implement a simple TGClient protocol to send requests to the network with Content-Type: multipart/form-data.\nYou can see an example here: [TGClientDefault](https://github.com/nerzh/swift-telegram-bot/blob/master/Sources/SwiftTelegramBot/Bot/Helpers/TGClientDefault.swift)\n\n```swift\npublic protocol TGClientPrtcl {\n    \n    @discardableResult\n    func post\u003cParams: Encodable, Response: Decodable\u003e(_ url: URL, params: Params?, as mediaType: HTTPMediaType?) async throws -\u003e Response\n    \n    @discardableResult\n    func post\u003cResponse: Decodable\u003e(_ url: URL) async throws -\u003e Response\n}\n```\n\n### Add to your Vapor project with Swift Package Manager\nadd to yor Package.json\n\n```swift\n// swift-tools-version:6.0\n\nimport PackageDescription\n\nvar packageDependencies: [Package.Dependency] = [\n    .package(url: \"https://github.com/vapor/vapor.git\", .upToNextMajor(from: \"4.57.0\")),\n]\n\npackageDependencies.append(.package(url: \"https://github.com/nerzh/swift-telegram-bot\", .upToNextMajor(from: \"4.2.0\")))\n\n\nlet package = Package(\n    name: \"Telegram-bot-example\",\n    platforms: [\n        .macOS(.v12)\n    ],\n    dependencies: packageDependencies,\n    targets: [\n        .executableTarget(\n            name: \"Telegram-bot-example\",\n            dependencies: [\n                .product(name: \"Vapor\", package: \"vapor\"),\n                .product(name: \"SwiftTelegramBot\", package: \"swift-telegram-bot\"),\n            ]\n        )\n    ]\n)\n\n\n\n```\n# Acknowledgments\n\nInspired by [Telegrammer](https://github.com/givip/Telegrammer)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnerzh%2Fswift-telegram-bot","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnerzh%2Fswift-telegram-bot","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnerzh%2Fswift-telegram-bot/lists"}