{"id":18418089,"url":"https://github.com/nerzh/swift-telegram-sdk","last_synced_at":"2025-04-07T13:31:07.576Z","repository":{"id":43536865,"uuid":"371458616","full_name":"nerzh/swift-telegram-sdk","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.","archived":false,"fork":false,"pushed_at":"2024-08-06T20:32:40.000Z","size":927,"stargazers_count":195,"open_issues_count":0,"forks_count":31,"subscribers_count":6,"default_branch":"master","last_synced_at":"2024-08-10T09:42:45.245Z","etag":null,"topics":["async","await","await-async","bot","server-side-swift","swift","telegram","telegram-bot","telegram-bot-api","vapor"],"latest_commit_sha":null,"homepage":"https://core.telegram.org/bots/api#available-methods","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}},"created_at":"2021-05-27T17:49:55.000Z","updated_at":"2024-08-14T15:17:02.724Z","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-sdk","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"],"tags_count":83,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nerzh%2Fswift-telegram-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nerzh%2Fswift-telegram-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nerzh%2Fswift-telegram-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nerzh%2Fswift-telegram-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nerzh","download_url":"https://codeload.github.com/nerzh/swift-telegram-sdk/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247661596,"owners_count":20975082,"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","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":["async","await","await-async","bot","server-side-swift","swift","telegram","telegram-bot","telegram-bot-api","vapor"],"created_at":"2024-11-06T04:12:32.408Z","updated_at":"2025-04-07T13:31:07.549Z","avatar_url":"https://github.com/nerzh.png","language":"Swift","funding_links":[],"categories":["Telegram Libraries"],"sub_categories":["Swift"],"readme":"# Swift Telegram Sdk 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\nNow for use in Swift 6, to avoid many compiler errors, please use the import as indicated below. In the future I plan to release a version with support for the new parallelism paradigm from Swift 6\n\n```swift\n@preconcurrency import SwiftTelegramSdk\n```\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-sdk\n  ```\n  ```\n  cd swift-telegram-sdk/Examples/Vapor-Telegram-Bot\n  ```\n- Add your telegram bot id to [configure.swift](https://github.com/nerzh/swift-telegram-sdk/blob/master/Examples/Vapor-Telegram-Bot/Sources/Vapor-Telegram-Bot/configure.swift)\n  ```swift\n  let tgApi: 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-sdk/tree/master/Examples/Vapor-Telegram-Bot)\n- [Hummingbird Telegram Bot (AsyncHttpClient)](https://github.com/nerzh/swift-telegram-sdk/tree/master/Examples/Hummingbird-AsyncHttpClient-Telegram-Bot)\n- [Hummingbird Telegram Bot (URLSession)](https://github.com/nerzh/swift-telegram-sdk/tree/master/Examples/Hummingbird-URLSession-Telegram-Bot)\n- [Smoke Telegram Bot (AsyncHttpClient)](https://github.com/nerzh/swift-telegram-sdk/tree/master/Examples/Smoke-AsyncHttpClient-Telegram-Bot)\n- [FlyingFox Telegram Bot (AsyncHttpClient)](https://github.com/nerzh/swift-telegram-sdk/tree/master/Examples/FlyingFox-AsyncHttpClient-Telegram-Bot)\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 implement a simple TGClient protocol to send requests to the network with Content-Type: multipart/form-data.\nYou can see an example here: [VaporTGClient](https://github.com/nerzh/swift-telegram-sdk/blob/master/Examples/Vapor-Telegram-Bot/Sources/Vapor-Telegram-Bot/TGBot/VaporTGClient.swift)\n\n```swift\nimport Logging\n\npublic protocol TGClientPrtcl {\n    \n    var log: Logger { get set }\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## Bot configuration.\n### Define bot ID\n```swift\nlet tgApi: String = \"XXXXXXXXXX:YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY\"\n```\n### Define connection type\n##### LongPolling\n```swift\nvar connectionType: TGConnectionType = .longpolling(limit: nil,\n                                                    timeout: nil,\n                                                    allowedUpdates: nil)\n```\n##### WebHook\n```swift\nvar 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 botActor.bot.dispatcher.process([update]) }\n        return true\n    }\n}\n```\n### Start bot with added handlers\n```swift\nlet bot: TGBot = try await .init(connectionType: connectionType,\n                                 dispatcher: nil,\n                                 tgClient: VaporTGClient(client: app.client),\n                                 tgURI: TGBot.standardTGURL,\n                                 botId: botId,\n                                 log: app.logger)\ntry await DefaultBotHandlers.addHandlers(bot: bot)\ntry await botActor.bot.start()\n```\n\n### DefaultBotHandlers code example\n```swift\nimport SwiftTelegramSdk\n\nfinal class DefaultBotHandlers {\n\n    static func addHandlers(bot: TGBot) async {\n        await defaultBaseHandler(bot: bot)\n        await messageHandler(bot: bot)\n        await commandPingHandler(bot: bot)\n        await commandShowButtonsHandler(bot: bot)\n        await buttonsActionHandler(bot: bot)\n    }\n    \n    private static func defaultBaseHandler(bot: TGBot) async {\n        await bot.dispatcher.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 bot.sendMessage(params: params)\n        }))\n    }\n\n    private static func messageHandler(bot: TGBot) async {\n        await bot.dispatcher.add(TGMessageHandler(filters: (.all \u0026\u0026 !.command.names([\"/ping\", \"/show_buttons\"]))) { update in\n            let params: TGSendMessageParams = .init(chatId: .chat(update.message!.chat.id), text: \"Success\")\n            try await bot.sendMessage(params: params)\n        })\n    }\n\n    private static func commandPingHandler(bot: TGBot) async {\n        await bot.dispatcher.add(TGCommandHandler(commands: [\"/ping\"]) { update in\n            try await update.message?.reply(text: \"pong\", bot: bot)\n        })\n    }\n\n    private static func commandShowButtonsHandler(bot: TGBot) async {\n        await bot.dispatcher.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 bot.sendMessage(params: params)\n        })\n    }\n\n    private static func buttonsActionHandler(bot: TGBot) async {\n        await bot.dispatcher.add(TGCallbackQueryHandler(pattern: \"press 1\") { update in\n            TGBot.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 bot.answerCallbackQuery(params: params)\n            try await bot.sendMessage(params: .init(chatId: .chat(userId), text: \"press 1\"))\n        })\n        \n        await bot.dispatcher.add(TGCallbackQueryHandler(pattern: \"press 2\") { update in\n            TGBot.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 bot.answerCallbackQuery(params: params)\n            try await bot.sendMessage(params: .init(chatId: .chat(userId), text: \"press 2\"))\n        })\n    }\n}\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:5.8\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-sdk\", .upToNextMajor(from: \"3.0.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: \"SwiftTelegramSdk\", package: \"swift-telegram-sdk\"),\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-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnerzh%2Fswift-telegram-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnerzh%2Fswift-telegram-sdk/lists"}