Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
givip committed Mar 19, 2019
2 parents 74fe374 + e8607c6 commit 3078771
Show file tree
Hide file tree
Showing 32 changed files with 625 additions and 591 deletions.
6 changes: 3 additions & 3 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// swift-tools-version:4.0
// swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription
Expand All @@ -16,12 +16,12 @@ let package = Package(
.package(url: "https://github.com/vapor/http.git", from: "3.0.0"),
.package(url: "https://github.com/vapor/crypto.git", from: "3.1.0"),
.package(url: "https://github.com/vapor/multipart.git", from: "3.0.0"),
.package(url: "https://github.com/IBM-Swift/HeliumLogger.git", from: "1.8.0"),
.package(url: "https://github.com/apple/swift-log.git", .branch("master"))
],
targets: [
.target(
name: "Telegrammer",
dependencies: ["HTTP", "Multipart", "Crypto", "HeliumLogger"]),
dependencies: ["HTTP", "Multipart", "Crypto", "Logging"]),
.target(name: "EchoBot", dependencies: ["Telegrammer"]),
.target(name: "HelloBot", dependencies: ["Telegrammer"]),
.target(name: "SchedulerBot", dependencies: ["Telegrammer"]),
Expand Down
24 changes: 20 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,22 +128,38 @@ $ vapor xcode
Demo bots
---------

#### EchoBot Sample
#### All sample bots
1. Add Telegram Token in [Environment Variables](http://nshipster.com/launch-arguments-and-environment-variables/), so, either create an environment variable:
```
$ export TELEGRAM_BOT_TOKEN='000000000:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
```
2. Run EchoBot executable scheme or
2. Run Bot executable scheme or
```
$ swift run
```
3. Send _**/echo**_ command to bot


[EchoBot sources](https://github.com/givip/Telegrammer/tree/master/Sources/EchoBot)
Starts/stops with command "/echo", then simply responds with your message

[HelloBot sources](https://github.com/givip/Telegrammer/tree/master/Sources/HelloBot)
Says "Hello" to new users in group. Responds with "hello" message on command "/greet"

[SchedulerBot sources](https://github.com/givip/Telegrammer/tree/master/Sources/SchedulerBot)
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](https://github.com/givip/Telegrammer/tree/master/Sources/SpellCheckerBot)
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
---------------

- Ubuntu 14.04 or later with [Swift 4.2 or later](https://swift.org/getting-started/) / macOS with [Xcode 9.3 or later](https://swift.org/download/)
- Ubuntu 14.04 or later with [Swift 5.0 or later](https://swift.org/getting-started/) / macOS with [Xcode 10.2 beta 4 or later](https://swift.org/download/)
- Telegram account and a Telegram App for any platform
- [Swift Package Manager (SPM)](https://github.com/apple/swift-package-manager/blob/master/Documentation/Usage.md) for dependencies
- [Vapor 3](https://vapor.codes) (optionally, for bots with database and other server side stuff)
Expand Down
4 changes: 2 additions & 2 deletions Sources/EchoBot/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func echoModeSwitch(_ update: Update, _ context: BotContext?) throws {
onText = "ON"
userEchoModes[user.id] = true
}

let params = Bot.SendMessageParams(chatId: .chat(message.chat.id), text: "Echo mode turned \(onText)")
try bot.sendMessage(params: params)
}
Expand All @@ -59,7 +59,7 @@ do {
///Creating and adding handler for ordinary text messages
let echoHandler = MessageHandler(filters: Filters.text, callback: echoResponse)
dispatcher.add(handler: echoHandler)
///Longpolling updates
_ = try Updater(bot: bot, dispatcher: dispatcher).startLongpolling().wait()

Expand Down
8 changes: 4 additions & 4 deletions Sources/HelloBot/Handlers/NewMemberHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@ import Foundation
import Telegrammer

class NewMemberHandler: Handler {

typealias NewMemberCallback = (_ update: Update) throws -> Void
var name: String
var name: String
let filters = StatusUpdateFilters.newChatMembers
var callback: NewMemberCallback

init(callback: @escaping NewMemberCallback, name: String = String(describing: CallbackQueryHandler.self)) {
self.callback = callback
self.name = name
self.name = name
}

func check(update: Update) -> Bool {
Expand Down
4 changes: 2 additions & 2 deletions Sources/HelloBot/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,11 @@ do {
let dispatcher = Dispatcher(bot: bot)

///Creating and adding New chat member handler
let newMemberHandler = NewMemberHandler(callback: greetNewMember)
let newMemberHandler = NewMemberHandler(callback: greetNewMember)
dispatcher.add(handler: newMemberHandler)

///Creating and adding Command handler for '/greet'
let commandHandler = CommandHandler(commands: ["/greet"], callback: greeting)
let commandHandler = CommandHandler(commands: ["/greet"], callback: greeting)
dispatcher.add(handler: commandHandler)

///Longpolling updates
Expand Down
10 changes: 5 additions & 5 deletions Sources/SpellCheckerBot/Controllers/SpellCheckerController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,17 @@ class SpellCheckerController {

return InlineKeyboardMarkup(inlineKeyboard: menuButtons)
}

func start(_ update: Update, _ context: BotContext?) throws {
guard let message = update.message else { return }
try respond(to: message, text: "Send text to bot, you want to spellcheck ✅\n\n\(attentionText)")
}

func spellCheck(_ update: Update, _ context: BotContext?) throws {
guard let message = update.message,
let text = message.text,
let user = message.from else { return }

spellChecker.check(text, lang: .en, format: .plain) { [unowned self] (checks) in
guard !checks.isEmpty else {
try self.congrat(message: message)
Expand All @@ -60,7 +60,7 @@ class SpellCheckerController {
flow.start(text, checks: checks)

self.sessions[user.id] = flow

try self.begin(flow, to: message)
}
}
Expand Down Expand Up @@ -126,7 +126,7 @@ private extension SpellCheckerController {
}

func congrat(message: Message) throws {
try message.reply(text: "👏 Congratulate! Your text is without any mistakes!", from: bot)
try message.reply(text: "👏 Congratulate! Your text is without any mistakes!", from: bot)
}

func cancel(message: Message) throws {
Expand Down
36 changes: 18 additions & 18 deletions Sources/SpellCheckerBot/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,23 @@ import Telegrammer
guard let token = Enviroment.get("TELEGRAM_BOT_TOKEN") else { exit(1) }

do {
let bot = try Bot(token: token)
let dispatcher = Dispatcher(bot: bot)
let controller = SpellCheckerController(bot: bot)
let commandHandler = CommandHandler(commands: ["/start"], callback: controller.start)
dispatcher.add(handler: commandHandler)
let textHandler = MessageHandler(filters: .private, callback: controller.spellCheck)
dispatcher.add(handler: textHandler)
let inlineHandler = CallbackQueryHandler(pattern: "\\w+", callback: controller.inline)
dispatcher.add(handler: inlineHandler)
///Longpolling updates
_ = try Updater(bot: bot, dispatcher: dispatcher).startLongpolling().wait()
let bot = try Bot(token: token)
let dispatcher = Dispatcher(bot: bot)
let controller = SpellCheckerController(bot: bot)
let commandHandler = CommandHandler(commands: ["/start"], callback: controller.start)
dispatcher.add(handler: commandHandler)
let textHandler = MessageHandler(filters: .private, callback: controller.spellCheck)
dispatcher.add(handler: textHandler)
let inlineHandler = CallbackQueryHandler(pattern: "\\w+", callback: controller.inline)
dispatcher.add(handler: inlineHandler)
///Longpolling updates
_ = try Updater(bot: bot, dispatcher: dispatcher).startLongpolling().wait()
} catch {
print(error.localizedDescription)
print(error.localizedDescription)
}
27 changes: 14 additions & 13 deletions Sources/Telegrammer/Bot/Telegram/Bot.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@

import Foundation
import HTTP
import HeliumLogger
import LoggerAPI
import Logging

public final class Bot: BotProtocol {

Expand Down Expand Up @@ -43,8 +42,6 @@ public final class Bot: BotProtocol {
}

public init(settings: Settings, numThreads: Int = System.coreCount) throws {
Log.logger = settings.debugMode ? HeliumLogger(.verbose) : HeliumLogger(.error)

self.settings = settings
self.requestWorker = MultiThreadedEventLoopGroup(numberOfThreads: numThreads)
self.client = try BotClient(host: settings.serverHost,
Expand All @@ -56,14 +53,12 @@ public final class Bot: BotProtocol {

func wrap<T: Codable>(_ container: TelegramContainer<T>) throws -> Future<T> {

Log.verbose(logMessage(container))
log.info(logMessage(container))

if let result = container.result {
return Future.map(on: self.requestWorker, { result })
} else {
let error = logError(container)
Log.error(error.localizedDescription)
throw error
throw logError(container)
}
}

Expand Down Expand Up @@ -96,7 +91,7 @@ public final class Bot: BotProtocol {
return HTTPHeaders()
}

func logMessage<T: Codable>(_ container: TelegramContainer<T>) -> String {
func logMessage<T: Codable>(_ container: TelegramContainer<T>) -> Logger.Message {
var resultString = "[]"

if let result = container.result {
Expand All @@ -111,12 +106,12 @@ public final class Bot: BotProtocol {
if let value = container.result as? Bool {
resultString = value.description
} else {
Log.error(error.localizedDescription)
log.error(error.logMessage)
}
}
}

return """
let logString = """
Received response
Code: \(container.errorCode ?? 0)
Expand All @@ -125,10 +120,16 @@ public final class Bot: BotProtocol {
Result: \(resultString)
"""

return Logger.Message(stringLiteral: logString)
}

func logError<T: Codable>(_ container: TelegramContainer<T>) -> Error {
return CoreError(identifier: "DecodingErrors",
reason: container.description ?? "Response error")
let error = CoreError(
identifier: "DecodingErrors",
reason: container.description ?? "Response error"
)
log.error(error.logMessage)
return error
}
}
4 changes: 1 addition & 3 deletions Sources/Telegrammer/Bot/Telegram/Jobs/BasicJobQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
//

import Foundation
import HeliumLogger
import LoggerAPI
import HTTP

public class BasicJobQueue<C>: JobQueue {
Expand All @@ -25,7 +23,7 @@ public class BasicJobQueue<C>: JobQueue {
public func shutdownQueue() {
worker.shutdownGracefully { (error) in
if let error = error {
Log.error(error.localizedDescription)
log.error(error.logMessage)
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions Sources/Telegrammer/Bot/Telegram/TelegramBot.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,6 @@
//

import Foundation
import Logging

let log = Logger(label: "com.gp-apps.telegrammer")
Loading

0 comments on commit 3078771

Please sign in to comment.