Telegram Bot Framework written in Swift 5.1 with SwiftNIO network framework

Overview

SwiftyBot Banner

Telegrammer

Telegram Bot Framework written in Swift 5.1 with SwiftNIO network framework

Build Version Language Platform License

What does it do

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

Join to our Telegram developers chat Join to our Telegrammer channel on Vapor Discord server

The simplest code of Echo Bot looks like this:


main.swift

import Foundation
import Telegrammer

do {
    let bot = try Bot(token: "BOT_TOKEN_HERE")

    let echoHandler = MessageHandler { (update, _) in
        _ = try? update.message?.reply(text: "Hello \(update.message?.from?.firstName ?? "anonymous")", from: bot)
    }

    let dispatcher = Dispatcher(bot: bot)
    dispatcher.add(handler: echoHandler)

    _ = try Updater(bot: bot, dispatcher: dispatcher).startLongpolling().wait()
} catch {
    exit(1)
}

Documentation

Usage without Vapor

Usage with Vapor

Demo bots

All sample bots

  1. Add Telegram Token in Environment Variables, so, either create an environment variable:
$ export TELEGRAM_BOT_TOKEN='000000000:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
  1. Run Bot executable scheme or
$ swift run

EchoBot sources Starts/stops with command "/echo", then simply responds with your message

HelloBot sources Says "Hello" to new users in group. Responds with "hello" message on command "/greet"

SchedulerBot sources Demonstrate Jobs Queue scheduling mechanism. Command "/start X" starts repeatable job, wich will send you a message each X seconds. Command "/once X" will send you message once after timeout of X seconds. Command "/stop" stops JobsQueue only for you. Other users continues to receive scheduled messages.

SpellCheckerBot sources Demonstrate how works InlineMenus and Callback handlers. Command "/start" will start bot. Send any english text to bot and it will be checked for mistakes. Bot will propose you some fixes in case of found mistake.

Requirements

Contributing

See CONTRIBUTING.md file.

Author

Givi Pataridze

[email protected] @givip

Comments
  • Extra argument 'from' in call

    Extra argument 'from' in call

    Hello!

    First I want to thank you for your amazing library, I find it extremely convenient to work with. Now back to my issue. I can't build my project if I use the function below

    self.dispatcher.remove(handler: handler, from: group)

    I get the error Error:(76, 60) extra argument 'from' in call

    I can't understand what's wrong with it. group variable is correct and has type HandlerGroup. I'm using Swift 4.1. Does your project successfully build using the line like this?

    Thank you!

    opened by ityutin 8
  • swift5.5 concurrency support (async await)

    swift5.5 concurrency support (async await)

    can use async/await in swift5.5(xcode13) Package.swift in Target config.

    swiftSettings: [
                    .unsafeFlags([
                        "-Xfrontend", "-disable-availability-checking", // ignore concurrency api check
                        "-Xfrontend", "-enable-experimental-concurrency",
                    ]),
                ]
    
    opened by hootigger 4
  • Webhook certificate text instead of file path?

    Webhook certificate text instead of file path?

    First of all, great repo BTW. Thanks for this 🎉

    I noticed that the code is expecting the pem certificate's path.

    if let publicCert = bot.settings.webhooksPublicCert {
      guard let fileHandle = FileHandle(forReadingAtPath: publicCert) else {
        let errorDescription = "Public key '\(publicCert)' was specified for HTTPS server, but wasn't found"
        log.error(errorDescription.logMessage)
        throw CoreError(identifier: "FileIO", reason: errorDescription)
      }
    
      cert = InputFile(data: fileHandle.readDataToEndOfFile(), filename: publicCert)
    }
    

    Since I'm deploying the bot with Dokku, I don't have too much control on the file system (everything running on containers). I was thinking about an option of getting the certficate's content on another environment variable. What do you think?

    opened by betzerra 4
  • Fail update dependency

    Fail update dependency

    swift package generate-xcodeproj return error after update to 0.5.4 version.

    Console log:

    error: multiple products named 'Logging' in: Console, swift-log
    error: multiple targets named 'Logging' in: Console, swift-log
    

    Swift version:

    Apple Swift version 5.0 (swiftlang-1001.0.69.5 clang-1001.0.46.3)
    Target: x86_64-apple-darwin18.2.0
    
    opened by ct4h 4
  • Crash on using combined filters (EXC_BAD_ACCESS)

    Crash on using combined filters (EXC_BAD_ACCESS)

    When using a combined filter in a telegrammer-vapor-middleware based app like so (here a 'not'):

            let answerHandler = MessageHandler(filters: !Filters.command,
                                               callback: answerResponse)
            dispatcher.add(handler: answerHandler,to: HandlerGroup.answers)
    
    
    

    it results in the following crash on an incoming update: image

    Not only for the logical not (!), but same result for other logical operations (like and: &&, or: ||) Without logical operations it works like expected.

    opened by on123 1
  • Supporting Swift 5.1 and Vapor 4

    Supporting Swift 5.1 and Vapor 4

    Vapor 4 is in the making (v4.0.0-alpha.3.2) and will leverage new features in Swift 5.1. I think it would be a good idea to start working on a new Vapor template as well as updating the library to use Swift 5.1 and its new features.

    opened by ts95 1
  • Using Telegrammer with Vapor and Fluent (Postgresql)

    Using Telegrammer with Vapor and Fluent (Postgresql)

    I've set up a project with Telegrammer and Vapor. I've installed the postgresql driver and registered FluentPostgreSQLProvider, but I'm not sure how to get a database connection in my bot class.

    If I have a model called User and I want to query all users, I'd write the following code: User.query(on: conn).all(), where conn is an object that conforms to DatabaseConnectable. I'm not sure where/how I can access this object in my bot class.

    opened by ts95 1
  • Add FoundationNetworking imports

    Add FoundationNetworking imports

    Running swift build causes following error on Linux using latest builds:

    error: 'URLSession' is unavailable: This type has moved to the FoundationNetworking module. Import that module to use it.
    

    URLSession and related APIs were moved into a separate module to remove libcurl dependency from Foundation. More details in Release Notes.

    This PR adds now-missing imports.

    opened by nikstar 1
  • Update to Bot API 4.3

    Update to Bot API 4.3

    I've updated generated files with changes in API 4.2 and 4.3.

    Changes:

    • removed line in generator script to fix issue #32
    • Poll, PollOption types, sendPoll and stopPoll, addition to deduce_result_type to fix stopPoll
    • LoginUrl
    • other changes in line with official change log
    opened by nikstar 1
  • Timeout

    Timeout

    After an arbitrary number of incoming connections of the web hook, i get a timeout for get updates. Is there an option to reconnect?

    [2019-01-14T13:17:07.558Z] [INFO] [BotClient.swift:45 respond(endpoint:body:headers:)] Sending request:
    POST https://api.telegram.org:443/bot729517131:AAFH1wdt6_rnVxXFyNmY_jsLLzUmCtJ-P8w/getUpdates HTTP/1.1
    Content-Type: application/json
    content-length: 14
    {"timeout":20}
    [2019-01-14T13:17:07.573Z] [INFO] [BotClient.swift:68 send(request:)] Creating new HTTP Client
    [2019-01-14T13:17:07.574Z] [INFO] [BotClient.swift:78 send(request:)] Sending request to vapor HTTPClient
    [2019-01-14T13:17:27.601Z] [INFO] [BotClient.swift:82 send(request:)] Decoding response from HTTPClient
    [2019-01-14T13:17:27.601Z] [VERBOSE] [Bot.swift:59 wrap] 
    Received response
    Code: 0
    Status OK: true
    Description: Empty
    Result: [
      
    ]
    
    
    opened by Narsail 1
  • HTTPClient crash on second request

    HTTPClient crash on second request

    After first request HTTPClient crashes, because state of parsing body process in not changes. Workaround is on PR now https://github.com/vapor/http/pull/277

    bug 
    opened by givip 1
  • Implement Conversation Handler

    Implement Conversation Handler

    A handler to hold a conversation with a single user by managing four collections of other handlers. Note that neither posts in Telegram Channels, nor group interactions with multiple users are managed by instances of this class.

    enhancement 
    opened by givip 0
  • Implement Message object helpers

    Implement Message object helpers

    • [ ] caption_html
    • [ ] caption_html_urled
    • [ ] caption_markdown
    • [ ] caption_markdown_urled
    • [ ] chat_id
    • [x] delete
    • [ ] edit_caption
    • [ ] edit_reply_markup
    • [x] edit_text
    • [ ] effective_attachment
    • [ ] forward
    • [ ] parse_caption_entities
    • [ ] parse_caption_entity
    • [ ] parse_entities
    • [ ] parse_entity
    • [ ] reply_audio
    • [ ] reply_contact
    • [ ] reply_document
    • [ ] reply_html
    • [ ] reply_location
    • [ ] reply_markdown
    • [ ] reply_media_group
    • [ ] reply_photo
    • [ ] reply_sticker
    • [x] reply_text
    • [ ] reply_venue
    • [ ] reply_video
    • [ ] reply_video_note
    • [ ] reply_voice
    • [ ] text_html
    • [ ] text_html_urled
    • [ ] text_markdown
    • [ ] text_markdown_urled
    enhancement 
    opened by givip 0
Releases(1.0.0-alpha.3.1)
  • 1.0.0-alpha.3.1(Feb 20, 2020)

    In a group chat, Telegram allows specifying the bot to receive commands sent by a user by appending "@botUsername" in the command, while this feature is not working as expected currently in Telegrammer:

    If the user specifies the bot, the CommandHandler considers it a different command with "@" in the command name. We need to manually add a new command "/originalCommand@botUsername" to support it, which could be somehow misleading since most users (at least me) of this package would normally consider this automatically handled.

    Using the workaround in 1. would cause each command to be coded twice, which can be tedious and inelegant in cases where there are many commands in a CommandHandler. Therefore, I added the ability of checking the bot specified to the CommandHandler. This change does not break the existing API but only asks the username of the bot in the initializer optionally, and should then handle things correctly as intended.

    Source code(tar.gz)
    Source code(zip)
  • 1.0.0-alpha.3(Feb 4, 2020)

  • 1.0.0-alpha.2(Dec 30, 2019)

    • Get rid of third party libraries
    • Using only multipart-kit from Vapor
    • Using new AsyncHTTPClient based on NIO 2.0
    • Updated to latest version of Telegram API
    Source code(tar.gz)
    Source code(zip)
  • 0.5.4(Jul 16, 2019)

  • 0.5.1(Mar 18, 2019)

    Added:

    • BasicJobQueue, OnceJob, RepeatedJob, DailyJob
    • SchedulerBot example, which demonstrate JobQueue works
    • SpellCheckerBot example, which demonstrate how to use InlineKeyboardButton and CallbackQueryHandler
    Source code(tar.gz)
    Source code(zip)
  • 0.5.0(Mar 11, 2019)

  • 0.4.3(Mar 6, 2019)

  • 0.4.2(Aug 23, 2018)

  • 0.4.1(Aug 23, 2018)

  • 0.3.0(Jul 27, 2018)

  • 0.2.6(Jun 30, 2018)

  • 0.2.5(Jun 21, 2018)

    Added

    • Documentation for most of public classes

    Changed

    • ruby script which generate Telegram API classes improved and now generate docs for everything

    Removed

    • FoundationClient class
    Source code(tar.gz)
    Source code(zip)
  • 0.2.4(Jun 21, 2018)

    Added

    • ParseMode type for "Markdown" or "HTML" message text
    • Automatic Webhook deletion before starting Longpolling connection
    • Helpers reply, edit, delete for Message type

    Changed

    • Now command settings are settings up with OptionSet
    • Improved HelloBot example message text
    Source code(tar.gz)
    Source code(zip)
  • 0.2.3(Jun 10, 2018)

    Added

    • Convenience Bot.init(token: String) method

    Changed

    • HandlerCallback signature now has Update and BotContext input params
    • Now debugMode parameter in Bot.Settings is set true by default
    • Dispatcher class made safer with special thread-safe HandlersQueue class
    • Enqueue bot updates in special concurrent queue
    • Updated README.md with super simple bot example

    Removed

    • DispatchStatus enum
    Source code(tar.gz)
    Source code(zip)
Owner
Pataridze Givi
Mobile Architect, Senior Developer
Pataridze Givi
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
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
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
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
👤 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
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
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
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
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
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
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
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 library for the Twitter API v1 and v2

Swift library for the Twitter API v1 and v2

mironal 96 Dec 30, 2022
Swift Bot with Vapor for Telegram Bot Api

Telegram Vapor Bot Please support Swift Telegram Vapor Bot Lib development by giving a ⭐️ Telegram Bot based on Swift Vapor. Swift Server Side Communi

OleG. 104 Jan 6, 2023
MQTTNIO - Non-blocking, event-driven Swift client for MQTT build on SwiftNIO

This library has support for WebSocket connections and TLS. It runs on all platforms Swift NIO runs on (e.g. macOS, iOS, Linux, etc.).

Steven Roebert 41 Dec 23, 2022
Swiftbot on slack. Inspired by kishikawakatsumi/swift-compiler-discord-bot

Swiftbot Swiftbot on slack. Inspired by kishikawakatsumi/swift-compiler-discord-bot Usage $ swiftbot --token xoxb-xxxxxxxxxxxx-xxxxxxxxxxxx-xxxxxxxxxx

noppefoxwolf 55 Jan 8, 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
Someone - Someone utilizes GPT-3 to deliver a unique chat bot app experience

Someone - An IOS App Someone utilizes GPT-3 to deliver a unique chat bot app exp

Edward 1 Sep 22, 2022