Swift Bot with Vapor for Telegram Bot Api

Overview

Telegram Vapor Bot

Please support Swift Telegram Vapor Bot Lib development by giving a ⭐️

Telegram Bot based on Swift Vapor.

Swift Server Side Community - Ukraine / Russian / CIS Telegram Chat

My TG Contact - @nerzh

Example Telegram Bot based on Swift Telegram Vapor Bot - Here

Telegram-bot-example

Usage

create folder with your handlers TGHandlers/DefaultBotHandlers.swift

import Vapor
import telegram_vapor_bot

final class DefaultBotHandlers {

    static func addHandlers(app: Vapor.Application, bot: TGBotPrtcl) {
        defaultHandler(app: app, bot: bot)
        commandPingHandler(app: app, bot: bot)
        commandShowButtonsHandler(app: app, bot: bot)
        buttonsActionHandler(app: app, bot: bot)
    }

    private static func defaultHandler(app: Vapor.Application, bot: TGBotPrtcl) {
        let handler = TGMessageHandler(filters: (.all && !.command.names(["/ping"]))) { update, bot in
            let params: TGSendMessageParams = .init(chatId: .chat(update.message!.chat.id), text: "Success")
            try bot.sendMessage(params: params)
        }
        bot.connection.dispatcher.add(handler)
    }

    private static func commandPingHandler(app: Vapor.Application, bot: TGBotPrtcl) {
        let handler = TGCommandHandler(commands: ["/ping"]) { update, bot in
            try update.message?.reply(text: "pong", bot: bot)
        }
        bot.connection.dispatcher.add(handler)
    }
    
    private static func commandShowButtonsHandler(app: Vapor.Application, bot: TGBotPrtcl) {
        let handler = TGCommandHandler(commands: ["/show_buttons"]) { update, bot in
            guard let userId = update.message?.from.id else { fatalError("user id not found") }
            let buttons: [[TGInlineKeyboardButton]] = [
                [.init(text: "Button 1", callbackData: "press 1"), .init(text: "Button 2", callbackData: "press 2")]
            ]
            let keyboard: TGInlineKeyboardMarkup = .init(inlineKeyboard: buttons)
            let params: TGSendMessageParams = .init(chatId: .chat(userId),
                                                    text: "Keyboard activ",
                                                    replyMarkup: .inlineKeyboardMarkup(keyboard))
            try bot.sendMessage(params: params)
        }
        bot.connection.dispatcher.add(handler)
    }
    
    private static func buttonsActionHandler(app: Vapor.Application, bot: TGBotPrtcl) {
        let handler = TGCallbackQueryHandler(pattern: "press 1") { update, bot in
            try update.message?.reply(text: update.callbackQuery?.data ?? "data not exist", bot: bot)
        }
        
        let handler2 = TGCallbackQueryHandler(pattern: "press 2") { update, bot in
            try update.message?.reply(text: update.callbackQuery?.data ?? "data not exist", bot: bot)
        }
        
        bot.connection.dispatcher.add(handler)
        bot.connection.dispatcher.add(handler2)
    }

}

Use with LongPolling

for longpolling you should only configure vapor configure.swift

import telegram_vapor_bot

let tgApi: String = "XXXXXXXXXX:YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"
let connection: TGConnectionPrtcl = TGLongPollingConnection()
TGBot.configure(connection: connection, botId: tgApi, vaporClient: app.client)
try TGBot.shared.start()

/// set level of debug if you needed 
TGBot.log.logLevel = .error

DefaultBotHandlers.addHandlers(app: app, bot: TGBot.shared)

Use with Webhooks

vapor configure.swift

import telegram_vapor_bot

let tgApi: String = "XXXXXXXXXX:YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"
let connection: TGConnectionPrtcl = TGWebHookConnection(webHookURL: "https://your_domain/some_webhook_route")
TGBot.configure(connection: connection, botId: tgApi, vaporClient: app.client)
try TGBot.shared.start()

/// set level of debug if you needed 
TGBot.log.logLevel = .error

DefaultBotHandlers.addHandlers(app: app, bot: TGBot.shared)

vapor routes.swift

String in do { let update: TGUpdate = try request.content.decode(TGUpdate.self) try TGBot.shared.connection.dispatcher.process([update]) } catch { log.error(error.logMessage) } return "ok" } } ">
import Vapor
import telegram_vapor_bot


func routes(_ app: Application) throws {

    app.post("some_webhook_route") { (request) -> String in
        do {
            let update: TGUpdate = try request.content.decode(TGUpdate.self)
            try TGBot.shared.connection.dispatcher.process([update])
        } catch {
            log.error(error.logMessage)
        }

        return "ok"
    }
}

Add to your Vapor project with Swift Package Manager

add to yor Package.json

// swift-tools-version:5.3

import PackageDescription

let package = Package(
    name: "Telegram-bot-example",
    platforms: [
       .macOS(.v10_15)
    ],
    dependencies: [
        .package(name: "vapor", url: "https://github.com/vapor/vapor.git", .upToNextMajor(from: "4.45.0")),
        .package(name: "telegram-vapor-bot", url: "https://github.com/nerzh/telegram-vapor-bot", .upToNextMajor(from: "1.2.2")),
    ],
    targets: [
        .target(
            name: "Telegram-bot-example",
            dependencies: [
                .product(name: "Vapor", package: "vapor"),
                .product(name: "telegram-vapor-bot", package: "telegram-vapor-bot"),
            ]
        )
    ]
)

Acknowledgments

Inspired by Telegrammer

Comments
  • Thread 76: Fatal error: String index is out of bounds

    Thread 76: Fatal error: String index is out of bounds

    Когда кто-то из пользователей пересылает в чат длинное сообщение, или перепост, бот падает с ошибкой Fatal error: String index is out of bounds со ссылкой на строку 70 в файле CommandHandler

    Снимок экрана 2022-01-12 в 12 04 08

    bug 
    opened by evstarshov 10
  • buttonsActionHandler does not work

    buttonsActionHandler does not work

    When I trying to use buttons callback as it showed in example, I'm facing problem when bot can't reply to user. It seems because bot somehow forgets chat id. Example does not work too, actually.

    documentation 
    opened by Swiftocrat 4
  • Fix regex filter

    Fix regex filter

    If message has emojis, it will not match in regex filter. It happens because range is smaller than all message length. For correct count of symbols need to use UTF16 view of string.

    opened by Higher08 1
  • Фикс загрузки документов

    Фикс загрузки документов

    Долго руки не могли дойти, но как и обещал)

    изображение

    надо проверить бы на стикерах всяких не отломалось ли, но файлы загружаются. Везде бы проверить, где документы так или иначе загружались (если работало конеш)

    качество кода не оч, но мне кажется что с Encodable тут лучше вряд ли получится сделать


    изображение

    ^ вот так файл создавал если вдруг

    bug 
    opened by fwx 1
  • Request support for Concurrency and Web App.

    Request support for Concurrency and Web App.

    Your project is a great library! It has a lot of fun features when combined with Vapor. The combination with Vapor is also great for making Telegram Web App for Bot.

    Request support for these features:

    • async/await makes it easier to read and is now supported by most of the libraries still being updated.
    • Telegram is supporting Web App for Bot this year and we hope to add these features. https://core.telegram.org/bots/webapps
    enhancement 
    opened by JoneWang 3
Releases(1.6.3)
Owner
OleG.
Server Side Swift 🧡
OleG.
SDK for creating Telegram Bots in Swift.

Chat • Changelog • Prerequisites • Getting started • Creating a new bot • Generating Xcode project • API overview • Debugging notes • Examples • Docum

Rapier 349 Dec 20, 2022
A (really) native and powerful macOS Telegram client built using SwiftUI, optimized for moderating large communities and personal use.

Moc A (really) native and powerful macOS Telegram client, optimized for moderating large communities and personal use. This client is currently in dev

GGorAA 84 Jan 2, 2023
Fetch Multiple Rest API using Swift 5.5 Async Await with Task, TaskGroup, Continuation API

Source code for Tutorial on experimenting with Swift Async Await to fetch multiple REST API endpoints and eliminate Pyramid of Doom callback hell to improve code readability and maintanability

Alfian Losari 14 Dec 7, 2022
Swift implementation of Github REST API v3

GitHubAPI Swift implementation of GitHub REST api v3. Library support Swift 4.2. Work is in progress. Currently supported: Issues API. Activity API(Fe

Serhii Londar 77 Jan 7, 2023
Google Directions API helper for iOS, written in Swift

PXGoogleDirections Google Directions API SDK for iOS, entirely written in Swift. ?? Features Supports all features from the Google Directions API as o

Romain L 268 Aug 18, 2022
Swift Reddit API Wrapper

reddift reddift is Swift Reddit API Wrapper framework, and includes a browser is developed using the framework. Supports OAuth2(is not supported on tv

sonson 236 Dec 28, 2022
Instagram API client written in Swift

SwiftInstagram is a wrapper for the Instagram API written in Swift. It allows you to authenticate users and request data from Instagram effortlessly.

Ander Goig 580 Nov 25, 2022
Instagram Private API Swift

SwiftyInsta Please notice SwiftyInsta may not be actively maintained at the moment of you reading this note. Refer to #244 for more info. Instagram of

Mahdi Makhdumi 218 Jan 5, 2023
A Swift client for the OpenAI API.

OpenAI A Swift client for the OpenAI API. Requirements Swift 5.3+ An OpenAI API Key Example Usage Completions import OpenAI

Mattt 161 Dec 26, 2022
Swift library for the Twitter API v1 and v2

Swift library for the Twitter API v1 and v2

mironal 96 Dec 30, 2022
Backport of iOS 15 formatting api

This is a back-port of the .formatted API in Foundation that was introduced at WWDC '21 for iOS 15, macOS 12.0, tvOS 15.0, and watchOS 8.0.

Simon Salomons 9 Jul 22, 2022
Unofficial iOS/macOS SDK for the Notion API.

NotionClient: a Notion SDK for iOS & macOS Unofficial Notion API SDK for iOS & macOS. This is an alpha version and still work in progress. TODO Featur

David De Bels 15 Aug 4, 2022
👤 Framework to Generate Random Users - An Unofficial Swift SDK for randomuser.me

RandomUserSwift is an easy to use Swift framework that provides the ability to generate random users and their accompanying data for your Swift applic

Wilson Ding 95 Sep 9, 2022
Swifter - A Twitter framework for iOS & OS X written in Swift

Getting Started Installation If you're using Xcode 6 and above, Swifter can be installed by simply dragging the Swifter Xcode project into your own pr

Matt Donnelly 2.4k Dec 26, 2022
Swift client for Kubernetes

Table of contents Overview Compatibility Matrix Examples Usage Creating a client Configuring a client Client authentication Client DSL Advanced usage

Swiftkube 94 Dec 14, 2022
Solana + RxSolana This is a open source library on pure swift for Solana protocol

The objective is to create a cross platform, fully functional, highly tested and less depencies as posible. The project is still at initial stage. Lots of changes chan happen to the exposed api.

Arturo Jamaica 138 Dec 15, 2022
QuoteKit is a Swift framework to use the free APIs provided by Quotable created by Luke Peavey.

QuoteKit The QuoteKit is a Swift framework to use the free APIs provided by Quotable created by Luke Peavey.

Rudrank Riyam 17 Jun 23, 2022
Telegram Bot Framework written in Swift 5.1 with SwiftNIO network framework

Telegrammer is open-source framework for Telegram Bots developers. It was built on top of Apple/SwiftNIO

Pataridze Givi 279 Jan 4, 2023
Vapor-telemetrydeck - Vapor client for posting signals to TelemetryDeck, a privacy-conscious analytics service for apps and websites

Vapor-telemetrydeck - Vapor client for posting signals to TelemetryDeck, a privacy-conscious analytics service for apps and websites

Sidetrack 7 Jun 16, 2022
A WIP Swift wrapper for Discord's Bot API.

Quickcord Quickcord is a WIP Swift wrapper for Discord's Bot API. Features (As of right now) Connecting the the gateway and identifying. Literally eve

Ben Sova 4 Aug 7, 2021