From 86ed914867b8e32e716e16f297e0d4d67b3f7118 Mon Sep 17 00:00:00 2001 From: Oleh Hudeichuk Date: Wed, 2 Jun 2021 01:42:32 +0300 Subject: [PATCH] change filters + add readme --- README.md | 65 +++++++++++- .../Bot/Filters/AllFilter.swift | 12 +-- .../Bot/Filters/AudioFilter.swift | 12 +-- .../Bot/Filters/CaptionEntityFilter.swift | 15 +-- .../Bot/Filters/ChatFilter.swift | 15 +-- .../Bot/Filters/CommandFilter.swift | 30 ++++-- .../Bot/Filters/ContactFilter.swift | 12 +-- .../Bot/Filters/DocumentFilter.swift | 12 +-- .../Bot/Filters/EntityFilter.swift | 15 +-- .../Bot/Filters/Filter.swift | 99 ------------------- .../Bot/Filters/ForwarderFilter.swift | 12 +-- .../Bot/Filters/GameFilter.swift | 12 +-- .../Bot/Filters/GroupFilter.swift | 12 +-- .../Bot/Filters/InvoiceFilter.swift | 12 +-- .../Bot/Filters/LanguageFilter.swift | 15 +-- .../Bot/Filters/LocationFilter.swift | 12 +-- .../Bot/Filters/PhotoFilter.swift | 12 +-- .../Bot/Filters/PrivateFilter.swift | 12 +-- .../Bot/Filters/RegexpFilter.swift | 15 +-- .../Bot/Filters/ReplyFilter.swift | 12 +-- .../Bot/Filters/StatusUpdateFilters.swift | 45 +++++---- .../Bot/Filters/StickerFilter.swift | 12 +-- .../Bot/Filters/SuccesfulPaymentFilter.swift | 12 +-- .../Bot/Filters/TGFilter.swift | 57 +++++++++++ .../Bot/Filters/TextFilter.swift | 12 +-- .../Bot/Filters/UserFilter.swift | 41 +++++--- .../Bot/Filters/VenueFilter.swift | 12 +-- .../Bot/Filters/VideoFilter.swift | 12 +-- .../Bot/Filters/VideoNoteFilter.swift | 12 +-- .../Bot/Filters/VoiceFilter.swift | 12 +-- .../Bot/Handlers/CallbackQueryHandler.swift | 4 +- .../Bot/Handlers/CommandHandler.swift | 47 +++++---- .../Bot/Handlers/LoggerHandler.swift | 16 +-- .../Bot/Handlers/MessageHandler.swift | 29 +++--- .../Bot/Handlers/RegexpHandler.swift | 27 +++-- .../Bot/TGDispatcher.swift | 26 +++-- 36 files changed, 421 insertions(+), 368 deletions(-) delete mode 100644 Sources/telegram-vapor-bot-lib/Bot/Filters/Filter.swift create mode 100644 Sources/telegram-vapor-bot-lib/Bot/Filters/TGFilter.swift diff --git a/README.md b/README.md index 4d3ec9c..aef075e 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,66 @@ # telegram-vapor-bot-lib -A description of this package. +### Usage + +vapor **TGHandlers/DefaultBotHandlers.swift** +```swift +import Vapor +import telegram_vapor_bot_lib + +final class DefaultBotHandlers { + + static func addHandlers(app: Vapor.Application, bot: TGBotPrtcl) { + defaultHandler(app: app, bot: bot) + commandPingHandler(app: app, bot: bot) + } + + private static func defaultHandler(app: Vapor.Application, bot: TGBotPrtcl) { + let handler = TGMessageHandler(filters: (.all && !.command.names(["/ping"]))) { update, bot in + try update.message?.reply(text: "Success", bot: bot) + } + 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) + } +} + +``` + +vapor **configure.swift** + +```swift +/// let connection: TGConnectionPrtcl = TGLongPollingConnection() +let connection: TGConnectionPrtcl = TGWebHookConnection(webHookURL: "https://your_domain/some_webhook_route") +TGBot.configure(connection: connection, botId: tgApi, vaporClient: app.client) +try TGBot.shared.start() +DefaultBotHandlers.addHandlers(app: app, bot: TGBot.shared) +``` + +vapor **routes.swift** + +```swift +import Vapor +import telegram_vapor_bot_lib + + +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" + } +} +``` + + diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/AllFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/AllFilter.swift index 0200aa1..89aad53 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/AllFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/AllFilter.swift @@ -1,21 +1,21 @@ // -// AllFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Filter for any update, said "no filter" -public struct AllFilter: Filter { +public class AllFilter: TGFilter { public var name: String = "all" + override public func filter(message: TGMessage) -> Bool { return true } } -public extension Filters { - static var all = Filters(filter: AllFilter()) +public extension TGFilter { + static var all = AllFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/AudioFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/AudioFilter.swift index c65b440..4f702c6 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/AudioFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/AudioFilter.swift @@ -1,21 +1,21 @@ // -// AudioFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages that contain `Audio` -public struct AudioFilter: Filter { +public class AudioFilter: TGFilter { public var name: String = "audio" + override public func filter(message: TGMessage) -> Bool { return message.audio != nil } } -public extension Filters { - static var audio = Filters(filter: AudioFilter()) +public extension TGFilter { + static var audio = AudioFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/CaptionEntityFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/CaptionEntityFilter.swift index 1fb76fd..87f7692 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/CaptionEntityFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/CaptionEntityFilter.swift @@ -1,23 +1,24 @@ // -// CaptionEntity.swift -// Telegrammer // -// Created by Givi Pataridze on 24/06/2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Filters media messages to only allow those which have a `MessageEntity` where their type matches `type`. -public struct CaptionEntityFilter: Filter { +public class CaptionEntityFilter: TGFilter { var entityType: TGMessageEntityType public init(type: TGMessageEntityType) { self.entityType = type + super.init() } public var name: String = "caption_entity" + override public func filter(message: TGMessage) -> Bool { guard let entities = message.entities else { return false } return entities.contains(where: { (entity) -> Bool in @@ -26,8 +27,8 @@ public struct CaptionEntityFilter: Filter { } } -public extension Filters { - static func captionEntity(type: TGMessageEntityType) -> Filters { - return Filters(filter: CaptionEntityFilter(type: type)) +public extension TGFilter { + static func captionEntity(type: TGMessageEntityType) -> TGFilter { + return CaptionEntityFilter(type: type) } } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/ChatFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/ChatFilter.swift index e900b79..60c7a9e 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/ChatFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/ChatFilter.swift @@ -1,14 +1,13 @@ // -// ChatFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Filters messages to allow only those which are from specified chat ID. -public struct ChatFilter: Filter { +public class ChatFilter: TGFilter { var chatId: Int64 var username: String? @@ -16,10 +15,12 @@ public struct ChatFilter: Filter { public init(chatId: Int64, username: String? = nil) { self.chatId = chatId self.username = username + super.init() } public var name: String = "chat" + override public func filter(message: TGMessage) -> Bool { guard message.chat.id == chatId else { return false } guard let desiredUsername = username else { return true } @@ -28,8 +29,8 @@ public struct ChatFilter: Filter { } } -public extension Filters { - static func chat(chatId: Int64, username: String? = nil) -> Filters { - return Filters(filter: ChatFilter(chatId: chatId, username: username)) +public extension TGFilter { + static func chat(chatId: Int64, username: String? = nil) -> TGFilter { + return ChatFilter(chatId: chatId, username: username) } } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/CommandFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/CommandFilter.swift index f73a012..bbfa573 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/CommandFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/CommandFilter.swift @@ -1,23 +1,39 @@ // -// CommandFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages which contains command entity -public struct CommandFilter: Filter { +public class CommandFilter: TGFilter { public var name: String = "command" + private var _names: [String]? = nil + public func names(_ names: [String]) -> Self { + _names = names + return self + } + + override public func filter(message: TGMessage) -> Bool { guard let entity = message.entities else { return false } - return entity.contains(where: { $0.type == .botCommand }) + if let names = _names { + var trigger: Bool = false + for name in names { + if message.contains(command: name) { + trigger = true + } + } + return entity.contains(where: { $0.type == .botCommand }) && trigger + } else { + return entity.contains(where: { $0.type == .botCommand }) + } } } -public extension Filters { - static var command = Filters(filter: CommandFilter()) +public extension TGFilter { + static var command = CommandFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/ContactFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/ContactFilter.swift index b3913bd..e124d68 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/ContactFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/ContactFilter.swift @@ -1,22 +1,22 @@ // -// ContactFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages that contain `Contact` -public struct ContactFilter: Filter { +public class ContactFilter: TGFilter { public var name: String = "contact" + override public func filter(message: TGMessage) -> Bool { return message.contact != nil } } -public extension Filters { - static var contact = Filters(filter: ContactFilter()) +public extension TGFilter { + static var contact = ContactFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/DocumentFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/DocumentFilter.swift index bc9a52a..88fd223 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/DocumentFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/DocumentFilter.swift @@ -1,22 +1,22 @@ // -// DocumentFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages that contain `Document` -public struct DocumentFilter: Filter { +public class DocumentFilter: TGFilter { public var name: String = "document" + override public func filter(message: TGMessage) -> Bool { return message.document != nil } } -public extension Filters { - static var document = Filters(filter: DocumentFilter()) +public extension TGFilter { + static var document = DocumentFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/EntityFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/EntityFilter.swift index 7e212da..a46fd3d 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/EntityFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/EntityFilter.swift @@ -1,23 +1,24 @@ // -// EntityFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Filters messages to only allow those which have a `MessageEntity` where their type matches `type`. -public struct EntityFilter: Filter { +public class EntityFilter: TGFilter { let entityTypes: Set public init(types: [TGMessageEntityType]) { self.entityTypes = Set(types) + super.init() } public var name: String = "entity" + override public func filter(message: TGMessage) -> Bool { guard let entities = message.entities else { return false } let incomingTypes = entities.map { $0.type } @@ -25,8 +26,8 @@ public struct EntityFilter: Filter { } } -public extension Filters { - static func entity(types: [TGMessageEntityType]) -> Filters { - return Filters(filter: EntityFilter(types: types)) +public extension TGFilter { + static func entity(types: [TGMessageEntityType]) -> TGFilter { + return EntityFilter(types: types) } } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/Filter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/Filter.swift deleted file mode 100644 index 5c52a7e..0000000 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/Filter.swift +++ /dev/null @@ -1,99 +0,0 @@ -// -// Filter.swift -// Telegrammer -// -// Created by Givi Pataridze on 21.04.2018. -// - -import Foundation - -///Base protocol for atomic filter -public protocol Filter { - var name: String { get } - func filter(message: TGMessage) -> Bool -} - -/** - Class cluster for all filters. - - Filters may be combined using bitwise operators: - - - And: - ``` - (Filters.text && Filters.entity([.mention])) - ``` - - Or: - ``` - (Filters.audio || Filters.video) - ``` - - Not: - ``` - !Filters.command - ``` - Also works with more than two filters: - ``` - (Filters.text && (Filters.entity([.url, .mention]) || Filters.entity([.command]))) - (Filters.text && !Filters.forwarded) - ``` - If you want to create your own filters create a struct conforming `Filter` protocol and implement a `filter` method that returns a boolean: `true`, if the message should be handled, `false` otherwise. - */ -public class Filters { - - private enum Operation { - case and - case or - case not - } - - private typealias Compound = (lhs: Filters, rhs: Filters, op: Operation) - - private var atomicFilter: Filter? - private var simpleFilters: Filters? - private var compoundFilter: Compound? - - public init(filter: Filter) { - self.atomicFilter = filter - } - - public init(filters: Filters) { - self.simpleFilters = filters - } - - private init(lhs: Filters, rhs: Filters, op: Operation) { - self.compoundFilter = (lhs, rhs, op) - } - - public func check(_ message: TGMessage) -> Bool { - if let filter = atomicFilter { - return filter.filter(message: message) - } - if let filter = simpleFilters { - return filter.check(message) - } - if let filter = compoundFilter { - switch filter.op { - case .and: - return (filter.lhs).check(message) && (filter.rhs).check(message) - case .or: - return (filter.lhs).check(message) || (filter.rhs).check(message) - case .not: - return !(filter.lhs).check(message) - } - } - return true - } -} - -public extension Filters { - static func && (lhs: Filters, rhs: Filters) -> Filters { - return Filters(lhs: lhs, rhs: rhs, op: .and) - } - - static func || (lhs: Filters, rhs: Filters) -> Filters { - return Filters(lhs: lhs, rhs: rhs, op: .or) - } - - static prefix func ! (filter: Filters) -> Filters { - return Filters(lhs: filter, rhs: filter, op: .not) - } -} diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/ForwarderFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/ForwarderFilter.swift index 78df725..46bd22d 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/ForwarderFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/ForwarderFilter.swift @@ -1,17 +1,17 @@ // -// ForwarderFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages that are forwarded. -public struct ForwarderFilter: Filter { +public class ForwarderFilter: TGFilter { public var name: String = "forwarded" + override public func filter(message: TGMessage) -> Bool { return message.forwardDate != nil || message.forwardFrom != nil || @@ -21,6 +21,6 @@ public struct ForwarderFilter: Filter { } } -public extension Filters { - static var forwarded = Filters(filter: ForwarderFilter()) +public extension TGFilter { + static var forwarded = ForwarderFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/GameFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/GameFilter.swift index 4a94c33..524286b 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/GameFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/GameFilter.swift @@ -1,22 +1,22 @@ // -// GameFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages that contain `Game` -public struct GameFilter: Filter { +public class GameFilter: TGFilter { public var name: String = "forwarded" + override public func filter(message: TGMessage) -> Bool { return message.game != nil } } -public extension Filters { - static var game = Filters(filter: GameFilter()) +public extension TGFilter { + static var game = GameFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/GroupFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/GroupFilter.swift index 1980ca7..b0513bf 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/GroupFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/GroupFilter.swift @@ -1,22 +1,22 @@ // -// GroupFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages sent in a group chat -public struct GroupFilter: Filter { +public class GroupFilter: TGFilter { public var name: String = "group" + override public func filter(message: TGMessage) -> Bool { return message.chat.type != .private } } -public extension Filters { - static var group = Filters(filter: GroupFilter()) +public extension TGFilter { + static var group = GroupFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/InvoiceFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/InvoiceFilter.swift index 1806619..c8775fa 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/InvoiceFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/InvoiceFilter.swift @@ -1,22 +1,22 @@ // -// InvoiceFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages that contain `Invoice` -public struct InvoiceFilter: Filter { +public class InvoiceFilter: TGFilter { public var name: String = "invoice" + override public func filter(message: TGMessage) -> Bool { return message.invoice != nil } } -public extension Filters { - static var invoice = Filters(filter: InvoiceFilter()) +public extension TGFilter { + static var invoice = InvoiceFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/LanguageFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/LanguageFilter.swift index c0fbe94..2fd7135 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/LanguageFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/LanguageFilter.swift @@ -1,8 +1,7 @@ // -// LanguageFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation @@ -10,24 +9,26 @@ import Foundation /// Filters messages to only allow those which are from users with a certain language code. /// /// Note: According to telegrams documentation, every single user does not have the language_code attribute. -public struct LanguageFilter: Filter { +public class LanguageFilter: TGFilter { var lang: String public init(lang: String) { self.lang = lang + super.init() } public var name: String = "language" + override public func filter(message: TGMessage) -> Bool { guard let languageCode = message.from?.languageCode else { return true } return languageCode.starts(with: lang) } } -public extension Filters { - static func language(_ lang: String) -> Filters { - return Filters(filter: LanguageFilter(lang: lang)) +public extension TGFilter { + static func language(_ lang: String) -> TGFilter { + return LanguageFilter(lang: lang) } } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/LocationFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/LocationFilter.swift index 22be414..0052d49 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/LocationFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/LocationFilter.swift @@ -1,22 +1,22 @@ // -// LocationFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages that contain `Location` -public struct LocationFilter: Filter { +public class LocationFilter: TGFilter { public var name: String = "location" + override public func filter(message: TGMessage) -> Bool { return message.location != nil } } -public extension Filters { - static var location = Filters(filter: LocationFilter()) +public extension TGFilter { + static var location = LocationFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/PhotoFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/PhotoFilter.swift index 4bc95fe..4419fe7 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/PhotoFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/PhotoFilter.swift @@ -1,23 +1,23 @@ // -// PhotoFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages that contain `[PhotoSize]` -public struct PhotoFilter: Filter { +public class PhotoFilter: TGFilter { public var name: String = "photo" + override public func filter(message: TGMessage) -> Bool { guard let photos = message.photo else { return false } return !photos.isEmpty } } -public extension Filters { - static var photo = Filters(filter: PhotoFilter()) +public extension TGFilter { + static var photo = PhotoFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/PrivateFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/PrivateFilter.swift index 4fb61ec..8b5ca6c 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/PrivateFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/PrivateFilter.swift @@ -1,22 +1,22 @@ // -// PrivateFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages sent in a private chat -public struct PrivateFilter: Filter { +public class PrivateFilter: TGFilter { public var name: String = "private" + override public func filter(message: TGMessage) -> Bool { return message.chat.type == .private } } -public extension Filters { - static var `private` = Filters(filter: PrivateFilter()) +public extension TGFilter { + static var `private` = PrivateFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/RegexpFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/RegexpFilter.swift index c9a4002..06eb4bb 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/RegexpFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/RegexpFilter.swift @@ -1,14 +1,13 @@ // -// RegexpFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Filters updates by searching for an occurence of pattern in the message text. The `NSRegularExpression` is used to determine whether an update should be filtered. Refer to the documentation of the `NSRegularExpression` for more information. -public struct RegexpFilter: Filter { +public class RegexpFilter: TGFilter { let pattern: String let options: NSRegularExpression.Options @@ -16,10 +15,12 @@ public struct RegexpFilter: Filter { public init(pattern: String, options: NSRegularExpression.Options = []) { self.pattern = pattern self.options = options + super.init() } public var name: String = "regexp" + override public func filter(message: TGMessage) -> Bool { guard let text = message.text else { return false } guard let regexp = try? NSRegularExpression(pattern: pattern, options: options) else { return false } @@ -28,8 +29,8 @@ public struct RegexpFilter: Filter { } } -public extension Filters { - static func regexp(pattern: String, options: NSRegularExpression.Options = []) -> Filters { - return Filters(filter: RegexpFilter(pattern: pattern, options: options)) +public extension TGFilter { + static func regexp(pattern: String, options: NSRegularExpression.Options = []) -> TGFilter { + return RegexpFilter(pattern: pattern, options: options) } } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/ReplyFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/ReplyFilter.swift index 87e5dd9..e4b837c 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/ReplyFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/ReplyFilter.swift @@ -1,22 +1,22 @@ // -// ReplyFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages that are a reply to another message -public struct ReplyFilter: Filter { +public class ReplyFilter: TGFilter { public var name: String = "reply" + override public func filter(message: TGMessage) -> Bool { return message.replyToMessage != nil } } -public extension Filters { - static var reply = Filters(filter: ReplyFilter()) +public extension TGFilter { + static var reply = ReplyFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/StatusUpdateFilters.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/StatusUpdateFilters.swift index 58b17db..a7b453a 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/StatusUpdateFilters.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/StatusUpdateFilters.swift @@ -1,8 +1,7 @@ // -// StatusUpdateFilters.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation @@ -14,35 +13,36 @@ import Foundation */ public struct StatusUpdateFilters { /// Messages that contain Message.groupChatCreated, Message.supergroupChatCreated or Message.channelChatCreated - public static var chatCreated: Filters { return Filters(filter: ChatCreatedFilter()) } + public static var chatCreated: TGFilter { return ChatCreatedFilter() } /// Messages that contain Message.deleteChatPhoto - public static var deleteChatPhoto: Filters { return Filters(filter: DeleteChatPhotoFilter()) } + public static var deleteChatPhoto: TGFilter { return DeleteChatPhotoFilter() } /// Messages that contain Message.leftChatMember - public static var leftChatMember: Filters { return Filters(filter: LeftChatMemberFilter()) } + public static var leftChatMember: TGFilter { return LeftChatMemberFilter() } /// Messages that contain Message.migrateFromChatId - public static var migrate: Filters { return Filters(filter: MigrateFilter()) } + public static var migrate: TGFilter { return MigrateFilter() } /// Messages that contain Message.newChatMembers - public static var newChatMembers: Filters { return Filters(filter: NewChatMembersFilter()) } + public static var newChatMembers: TGFilter { return NewChatMembersFilter() } /// Messages that contain Message.newChatPhoto - public static var newChatPhoto: Filters { return Filters(filter: NewChatPhotoFilter()) } + public static var newChatPhoto: TGFilter { return NewChatPhotoFilter() } /// Messages that contain Message.newChatTitle - public static var newChatTitle: Filters { return Filters(filter: NewChatTitleFilter()) } + public static var newChatTitle: TGFilter { return NewChatTitleFilter() } /// Messages that contain Message.pinnedMessage - public static var pinnedMessage: Filters { return Filters(filter: PinnedMessageFilter()) } + public static var pinnedMessage: TGFilter { return PinnedMessageFilter() } } /// Messages that contain Message.groupChatCreated, Message.supergroupChatCreated or Message.channelChatCreated -public struct ChatCreatedFilter: Filter { +public class ChatCreatedFilter: TGFilter { public var name: String = "chat_created" + override public func filter(message: TGMessage) -> Bool { return message.channelChatCreated != nil || message.supergroupChatCreated != nil || @@ -51,30 +51,33 @@ public struct ChatCreatedFilter: Filter { } /// Messages that contain Message.deleteChatPhoto -public struct DeleteChatPhotoFilter: Filter { +public class DeleteChatPhotoFilter: TGFilter { public var name: String = "delete_chat_photo" + override public func filter(message: TGMessage) -> Bool { return message.deleteChatPhoto != nil } } /// Messages that contain Message.leftChatMember -public struct LeftChatMemberFilter: Filter { +public class LeftChatMemberFilter: TGFilter { public var name: String = "left_chat_member" + override public func filter(message: TGMessage) -> Bool { return message.leftChatMember != nil } } /// Messages that contain Message.migrateFromChatId -public struct MigrateFilter: Filter { +public class MigrateFilter: TGFilter { public var name: String = "migrate" + override public func filter(message: TGMessage) -> Bool { return message.migrateFromChatId != nil || message.migrateToChatId != nil @@ -82,20 +85,22 @@ public struct MigrateFilter: Filter { } /// Messages that contain Message.newChatMembers -public struct NewChatMembersFilter: Filter { +public class NewChatMembersFilter: TGFilter { public var name: String = "new_chat_members" + override public func filter(message: TGMessage) -> Bool { return message.newChatMembers != nil } } /// Messages that contain Message.newChatPhoto -public struct NewChatPhotoFilter: Filter { +public class NewChatPhotoFilter: TGFilter { public var name: String = "new_chat_photo" + override public func filter(message: TGMessage) -> Bool { guard let photos = message.newChatPhoto else { return false } return !photos.isEmpty @@ -103,20 +108,22 @@ public struct NewChatPhotoFilter: Filter { } /// Messages that contain Message.newChatTitle -public struct NewChatTitleFilter: Filter { +public class NewChatTitleFilter: TGFilter { public var name: String = "new_chat_title" + override public func filter(message: TGMessage) -> Bool { return message.newChatTitle != nil } } /// Messages that contain Message.pinnedMessage -public struct PinnedMessageFilter: Filter { +public class PinnedMessageFilter: TGFilter { public var name: String = "pinned_message" + override public func filter(message: TGMessage) -> Bool { return message.pinnedMessage != nil } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/StickerFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/StickerFilter.swift index e68df87..5017df2 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/StickerFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/StickerFilter.swift @@ -1,22 +1,22 @@ // -// StickerFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages that contain `Sticker` -public struct StickerFilter: Filter { +public class StickerFilter: TGFilter { public var name: String = "sticker" + override public func filter(message: TGMessage) -> Bool { return message.sticker != nil } } -public extension Filters { - static var sticker = Filters(filter: StickerFilter()) +public extension TGFilter { + static var sticker = StickerFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/SuccesfulPaymentFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/SuccesfulPaymentFilter.swift index df0dc60..bf722d6 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/SuccesfulPaymentFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/SuccesfulPaymentFilter.swift @@ -1,22 +1,22 @@ // -// SuccesfulPaymentFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Filters messages that contains a `SuccessfulPayment`. -public struct SuccesfulPaymentFilter: Filter { +public class SuccesfulPaymentFilter: TGFilter { public var name: String = "successful_payment" + override public func filter(message: TGMessage) -> Bool { return message.successfulPayment != nil } } -public extension Filters { - static var successfulPayment = Filters(filter: SuccesfulPaymentFilter()) +public extension TGFilter { + static var successfulPayment = SuccesfulPaymentFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/TGFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/TGFilter.swift new file mode 100644 index 0000000..cb069e4 --- /dev/null +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/TGFilter.swift @@ -0,0 +1,57 @@ +// +// +// +// Created by Oleh Hudeichuk on 02.06.2021. +// + +import Foundation + +public class TGFilter { + + public enum Operation { + case and + case or + case not + } + + public typealias Compound = (lhs: TGFilter, rhs: TGFilter, op: Operation) + + private var compoundFilter: Compound? = nil + + public init() {} + + init(lhs: TGFilter, rhs: TGFilter, op: Operation) { + compoundFilter = (lhs: lhs, rhs: rhs, op: op) + } + + public func check(_ mess: TGMessage) -> Bool { + if let filter = compoundFilter { + switch filter.op { + case .and: + return (filter.lhs).check(mess) && (filter.rhs).check(mess) + case .or: + return (filter.lhs).check(mess) || (filter.rhs).check(mess) + case .not: + return !(filter.rhs).check(mess) + } + } else { + return self.filter(message: mess) + } + } + + public func filter(message: TGMessage) -> Bool { + return false + } + + public static func &&(lhs: TGFilter, rhs: TGFilter) -> TGFilter { + return TGFilter(lhs: lhs, rhs: rhs, op: .and) + } + + public static func ||(lhs: TGFilter, rhs: TGFilter) -> TGFilter { + return TGFilter(lhs: lhs, rhs: rhs, op: .or) + } + + public static prefix func !(filter: TGFilter) -> TGFilter { + return TGFilter(lhs: filter, rhs: filter, op: .not) + } +} diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/TextFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/TextFilter.swift index 5e60d6f..95dcac6 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/TextFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/TextFilter.swift @@ -1,23 +1,23 @@ // -// TextFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Filters messages to allow only those which contains text -public struct TextFilter: Filter { +public class TextFilter: TGFilter { public var name: String = "text" + override public func filter(message: TGMessage) -> Bool { guard let text = message.text else { return false } return !text.isEmpty } } -public extension Filters { - static var text = Filters(filter: TextFilter()) +public extension TGFilter { + static var text = TextFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/UserFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/UserFilter.swift index e494997..31724d4 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/UserFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/UserFilter.swift @@ -1,14 +1,13 @@ // -// UserFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Filters messages to allow only those which are from specified user ID. -public struct UserFilter: Filter { +public class UserFilter: TGFilter { var userIds: Set? var usernames: Set? @@ -18,6 +17,7 @@ public struct UserFilter: Filter { */ public init(userId: Int64) { self.userIds = Set([userId]) + super.init() } /** @@ -27,6 +27,7 @@ public struct UserFilter: Filter { */ public init(username: String) { self.usernames = Set([username]) + super.init() } /** @@ -34,6 +35,7 @@ public struct UserFilter: Filter { */ public init(userIds: [Int64]) { self.userIds = Set(userIds) + super.init() } /** @@ -43,6 +45,7 @@ public struct UserFilter: Filter { */ public init(usernames: [String]) { self.usernames = Set(usernames) + super.init() } /** @@ -53,10 +56,16 @@ public struct UserFilter: Filter { public init(userIds: [Int64], usernames: [String]) { self.userIds = Set(userIds) self.usernames = Set(usernames) + super.init() } - + +// required init(lhs: TGFilter, rhs: TGFilter, op: Operation) { +// super.init(lhs: lhs, rhs: rhs, op: op) +// } + public var name: String = "user" + override public func filter(message: TGMessage) -> Bool { guard let user = message.from else { return false } @@ -75,24 +84,24 @@ public struct UserFilter: Filter { } } -public extension Filters { - static func user(userId: Int64) -> Filters { - return Filters(filter: UserFilter(userId: userId)) +public extension TGFilter { + static func user(userId: Int64) -> TGFilter { + return UserFilter(userId: userId) } - static func user(username: String) -> Filters { - return Filters(filter: UserFilter(username: username)) + static func user(username: String) -> TGFilter { + return UserFilter(username: username) } - static func user(userIds: [Int64]) -> Filters { - return Filters(filter: UserFilter(userIds: userIds)) + static func user(userIds: [Int64]) -> TGFilter { + return UserFilter(userIds: userIds) } - static func user(usernames: [String]) -> Filters { - return Filters(filter: UserFilter(usernames: usernames)) + static func user(usernames: [String]) -> TGFilter { + return UserFilter(usernames: usernames) } - static func user(userIds: [Int64], usernames: [String]) -> Filters { - return Filters(filter: UserFilter(userIds: userIds, usernames: usernames)) + static func user(userIds: [Int64], usernames: [String]) -> TGFilter { + return UserFilter(userIds: userIds, usernames: usernames) } } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/VenueFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/VenueFilter.swift index 91308a8..4bb2f75 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/VenueFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/VenueFilter.swift @@ -1,22 +1,22 @@ // -// VenueFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages that contain `Vanue` -public struct VenueFilter: Filter { +public class VenueFilter: TGFilter { public var name: String = "venue" + override public func filter(message: TGMessage) -> Bool { return message.venue != nil } } -public extension Filters { - static var venue = Filters(filter: VenueFilter()) +public extension TGFilter { + static var venue = VenueFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/VideoFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/VideoFilter.swift index ffa23f9..9445232 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/VideoFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/VideoFilter.swift @@ -1,22 +1,22 @@ // -// VideoFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages that contain `Video` -public struct VideoFilter: Filter { +public class VideoFilter: TGFilter { public var name: String = "video" + override public func filter(message: TGMessage) -> Bool { return message.video != nil } } -public extension Filters { - static var video = Filters(filter: VideoFilter()) +public extension TGFilter { + static var video = VideoFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/VideoNoteFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/VideoNoteFilter.swift index f8bbf7c..3931594 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/VideoNoteFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/VideoNoteFilter.swift @@ -1,22 +1,22 @@ // -// VideoNoteFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages that contain `VideoNote` -public struct VideoNoteFilter: Filter { +public class VideoNoteFilter: TGFilter { public var name: String = "video_note" + override public func filter(message: TGMessage) -> Bool { return message.videoNote != nil } } -public extension Filters { - static var videoNote = Filters(filter: VideoNoteFilter()) +public extension TGFilter { + static var videoNote = VideoNoteFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Filters/VoiceFilter.swift b/Sources/telegram-vapor-bot-lib/Bot/Filters/VoiceFilter.swift index b61c8ed..0e8346e 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Filters/VoiceFilter.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Filters/VoiceFilter.swift @@ -1,22 +1,22 @@ // -// VoiceFilter.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation /// Messages that contain `Voice` -public struct VoiceFilter: Filter { +public class VoiceFilter: TGFilter { public var name: String = "voice" + override public func filter(message: TGMessage) -> Bool { return message.voice != nil } } -public extension Filters { - static var voice = Filters(filter: VoiceFilter()) +public extension TGFilter { + static var voice = VoiceFilter() } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Handlers/CallbackQueryHandler.swift b/Sources/telegram-vapor-bot-lib/Bot/Handlers/CallbackQueryHandler.swift index c497327..b44151f 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Handlers/CallbackQueryHandler.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Handlers/CallbackQueryHandler.swift @@ -21,7 +21,7 @@ public class TGCallbackQueryHandler: TGHandlerPrtcl { pattern: String, callback: @escaping TGHandlerCallback, name: String = String(describing: TGCallbackQueryHandler.self) - ) { + ) { self.pattern = pattern self.callback = callback self.name = name @@ -30,7 +30,7 @@ public class TGCallbackQueryHandler: TGHandlerPrtcl { public func check(update: TGUpdate) -> Bool { guard let callbackQuery = update.callbackQuery else { return false } if let data = callbackQuery.data, - !data.matchRegexp(pattern: pattern) { + !data.matchRegexp(pattern: pattern) { return false } return true diff --git a/Sources/telegram-vapor-bot-lib/Bot/Handlers/CommandHandler.swift b/Sources/telegram-vapor-bot-lib/Bot/Handlers/CommandHandler.swift index 346fe67..a177d3a 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Handlers/CommandHandler.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Handlers/CommandHandler.swift @@ -1,47 +1,46 @@ // -// CommandHandler.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // /** Handler class to handle Telegram commands. - + Commands are Telegram messages that start with /, optionally followed by an @ and the bot’s name and/or some additional text. - + - Options of this handler - `editedUpdates` Determines whether the handler should also accept edited messages. - + */ public class TGCommandHandler: TGHandlerPrtcl { - + public var id: Int = 0 public var name: String - + public struct Options: OptionSet { public let rawValue: Int - + public init(rawValue: Int) { self.rawValue = rawValue } - + /// Determines Whether the handler should also accept edited messages. Not used by default. public static let editedUpdates = Options(rawValue: 1) } - + let commands: Set let callback: TGHandlerCallback - let filters: Filters + let filters: TGFilter let options: Options let botUsername: String? - + public init( name: String = String(describing: TGCommandHandler.self), commands: [String], - filters: Filters = .all, + filters: TGFilter = .all, options: Options = [], botUsername: String? = nil, callback: @escaping TGHandlerCallback @@ -53,19 +52,19 @@ public class TGCommandHandler: TGHandlerPrtcl { self.botUsername = botUsername self.callback = callback } - + public func check(update: TGUpdate) -> Bool { if options.contains(.editedUpdates), - update.editedMessage != nil || - update.editedChannelPost != nil { + update.editedMessage != nil || + update.editedChannelPost != nil { return true } - + guard let message = update.message, - filters.check(message), - let text = message.text, - let entities = message.entities else { return false } - + filters.check(message), + let text = message.text, + let entities = message.entities else { return false } + let types = entities.compactMap { (entity) -> String? in let start = text.index(text.startIndex, offsetBy: entity.offset) let end = text.index(start, offsetBy: entity.length-1) @@ -75,7 +74,7 @@ public class TGCommandHandler: TGHandlerPrtcl { // check the bot name and then ignore it for further match. let split = command.split(separator: "@") if split.count == 2, - let username = botUsername { + let username = botUsername { let commandWithoutMention = split[0] let specifiedBot = split[1] return specifiedBot == username @@ -86,7 +85,7 @@ public class TGCommandHandler: TGHandlerPrtcl { } return !commands.intersection(types).isEmpty } - + public func handle(update: TGUpdate, bot: TGBotPrtcl) { do { try callback(update, bot) diff --git a/Sources/telegram-vapor-bot-lib/Bot/Handlers/LoggerHandler.swift b/Sources/telegram-vapor-bot-lib/Bot/Handlers/LoggerHandler.swift index 704ce3e..5e2cf6f 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Handlers/LoggerHandler.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Handlers/LoggerHandler.swift @@ -9,19 +9,19 @@ import Foundation import Logging public class TGLoggerHandler: TGHandlerPrtcl { - + public var id: Int = 0 - + let logLevel: Logger.Level - + public init(level: Logger.Level) { self.logLevel = level } - + public func check(update: TGUpdate) -> Bool { return true } - + public func handle(update: TGUpdate, bot: TGBotPrtcl) { log.log(level: logLevel, update.logMessage) } @@ -29,10 +29,10 @@ public class TGLoggerHandler: TGHandlerPrtcl { extension TGUpdate { var description: String { - + //TODO: Improve description algorithm, serialization/deserialization too heavy var resultString = "[]" - + let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted do { @@ -45,7 +45,7 @@ extension TGUpdate { } return resultString } - + var logMessage: Logger.Message { return Logger.Message(stringLiteral: description) } diff --git a/Sources/telegram-vapor-bot-lib/Bot/Handlers/MessageHandler.swift b/Sources/telegram-vapor-bot-lib/Bot/Handlers/MessageHandler.swift index bb81b12..f4c2c6c 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Handlers/MessageHandler.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Handlers/MessageHandler.swift @@ -1,27 +1,26 @@ // -// MessageHandler.swift -// Telegrammer // -// Created by Givi Pataridze on 21.04.2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import AsyncHTTPClient /// Handler for bot messages, can handle normal messages, channel posts, edited messages public class TGMessageHandler: TGHandlerPrtcl { - + public var id: Int = 0 /// Name of particular MessageHandler, needed for determine handlers instances of one class in groups public var name: String - + /// Option Set for `MessageHandler` public struct Options: OptionSet { public let rawValue: Int - + public init(rawValue: Int) { self.rawValue = rawValue } - + ///Should “normal” message updates be handled? public static let messageUpdates = Options(rawValue: 1) ///Should channel posts updates be handled? @@ -29,14 +28,14 @@ public class TGMessageHandler: TGHandlerPrtcl { ///Should “edited” message updates be handled? public static let editedUpdates = Options(rawValue: 4) } - - let filters: Filters + + let filters: TGFilter let callback: TGHandlerCallback let options: Options - + public init( name: String = String(describing: TGMessageHandler.self), - filters: Filters = .all, + filters: TGFilter = .all, options: Options = [.messageUpdates, .channelPostUpdates], callback: @escaping TGHandlerCallback ) { @@ -45,7 +44,7 @@ public class TGMessageHandler: TGHandlerPrtcl { self.options = options self.name = name } - + public func check(update: TGUpdate) -> Bool { if options.contains(.channelPostUpdates) { if update.channelPost != nil { @@ -57,16 +56,16 @@ public class TGMessageHandler: TGHandlerPrtcl { return true } } - + if options.contains(.messageUpdates), let message = update.message, filters.check(message) { return true } - + return false } - + public func handle(update: TGUpdate, bot: TGBotPrtcl) { do { try callback(update, bot) diff --git a/Sources/telegram-vapor-bot-lib/Bot/Handlers/RegexpHandler.swift b/Sources/telegram-vapor-bot-lib/Bot/Handlers/RegexpHandler.swift index cba0231..349dcc5 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/Handlers/RegexpHandler.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/Handlers/RegexpHandler.swift @@ -1,39 +1,38 @@ // -// RegexpHandler.swift -// Telegrammer // -// Created by Givi Pataridze on 11/06/2018. +// +// Created by Oleh Hudeichuk on 02.06.2021. // import Foundation public class TGRegexpHandler: TGHandlerPrtcl { - + public var id: Int = 0 public var name: String - + let regexp: NSRegularExpression let callback: TGHandlerCallback - let filters: Filters - + let filters: TGFilter + public init( name: String = String(describing: TGRegexpHandler.self), regexp: NSRegularExpression, - filters: Filters = .all, + filters: TGFilter = .all, callback: @escaping TGHandlerCallback - ) { + ) { self.name = name self.regexp = regexp self.filters = filters self.callback = callback } - + public convenience init?( name: String = String(describing: TGRegexpHandler.self), pattern: String, - filters: Filters = .all, + filters: TGFilter = .all, callback: @escaping TGHandlerCallback - ) { + ) { guard let regexp = try? NSRegularExpression(pattern: pattern, options: []) else { return nil } @@ -44,13 +43,13 @@ public class TGRegexpHandler: TGHandlerPrtcl { callback: callback ) } - + public func check(update: TGUpdate) -> Bool { guard let text = update.message?.text else { return false } let range = NSRange(location: 0, length: text.count) return regexp.numberOfMatches(in: text, options: [], range: range) > 0 } - + public func handle(update: TGUpdate, bot: TGBotPrtcl) { do { try callback(update, bot) diff --git a/Sources/telegram-vapor-bot-lib/Bot/TGDispatcher.swift b/Sources/telegram-vapor-bot-lib/Bot/TGDispatcher.swift index 581592f..7a54048 100644 --- a/Sources/telegram-vapor-bot-lib/Bot/TGDispatcher.swift +++ b/Sources/telegram-vapor-bot-lib/Bot/TGDispatcher.swift @@ -13,7 +13,8 @@ public protocol TGDispatcherPrtcl { var handlersGroup: [[TGHandlerPrtcl]] { get set } /// The higher level has the highest priority - func add(_ handler: TGHandlerPrtcl, at level: Int?) + func add(_ handler: TGHandlerPrtcl, priority: Int) + func add(_ handler: TGHandlerPrtcl) func remove(_ handler: TGHandlerPrtcl, from level: Int?) func process(_ updates: [TGUpdate]) throws } @@ -42,7 +43,7 @@ public final class TGDispatcher: TGDispatcherPrtcl { private typealias Position = Int private var handlersIndex: [Level: [IndexId: Position]] = .init() - private func add(_ handler: TGHandlerPrtcl, at level: Int) { + public func add(_ handler: TGHandlerPrtcl, priority level: Int) { processQueue.async(flags: .barrier) { [weak self] in guard let self = self else { return } @@ -52,26 +53,23 @@ public final class TGDispatcher: TGDispatcherPrtcl { /// add handler var handlerPosition: Int = 0 - if self.handlersGroup.count > level && level >= 0 { - self.handlersGroup[level].append(handler) - handlerPosition = self.handlersGroup[level].count - 1 + let correctLevel: Int = level >= 0 ? level : 0 + if self.handlersGroup.count > correctLevel { + self.handlersGroup[correctLevel].append(handler) + handlerPosition = self.handlersGroup[correctLevel].count - 1 } else { - if self.handlersGroup.count > 0 { - self.handlersGroup[0].append(handler) - handlerPosition = self.handlersGroup[0].count - 1 - } else { - self.handlersGroup.append([handler]) - handlerPosition = 0 - } + self.handlersGroup.append([handler]) + handlerPosition = self.handlersGroup[self.handlersGroup.count - 1].count - 1 } + /// add handler to index if self.handlersIndex[level] == nil { self.handlersIndex[level] = .init() } self.handlersIndex[level]?[handler.id] = handlerPosition } } - public func add(_ handler: TGHandlerPrtcl, at level: Int?) { - add(handler, at: level ?? 0) + public func add(_ handler: TGHandlerPrtcl) { + add(handler, priority: 0) } public func remove(_ handler: TGHandlerPrtcl, from level: Int?) {