From d02b25d0265875822afe3b64f945283e92453670 Mon Sep 17 00:00:00 2001 From: Danila Fedorin Date: Fri, 12 Jan 2018 20:56:04 -0800 Subject: [PATCH] Implement method to process updates. --- src/telepathy/bot.cr | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/src/telepathy/bot.cr b/src/telepathy/bot.cr index f066be0..141cb0e 100644 --- a/src/telepathy/bot.cr +++ b/src/telepathy/bot.cr @@ -8,8 +8,8 @@ module Telepathy @this_user = get_me @last_update_id = uninitialized Int64? @last_update_id = nil - @command_hooks = {} of String => Update, Array(String) -> String - @message_hooks = [] of Update -> String + @command_hooks = {} of String => Update, Array(String) -> Void + @message_hooks = [] of Update -> Void end def get_me @@ -29,11 +29,29 @@ module Telepathy return updates end - def command(command_name, &block: Update, Array(String) -> String) + def process_updates(updates) + updates.each do |update| + if message = update.message + @message_hooks.each &.call(update) + if entity = message.entities.try { |it| it.first? } + text = message.text.as String + if entity.offset == 0 && entity.type == "bot_command" + divider_index = (text.index /\s|@/) || text.size + command = text[1...divider_index] + remaining = text[divider_index..text.size] + params = remaining.empty? ? ([] of String) : (remaining[1...remaining.size].split ' ') + @command_hooks[command]?.try { |command| command.call(update, params) } + end + end + end + end + end + + def command(command_name, &block: Update, Array(String) -> Void) @command_hooks[command_name] = block end - def message(&block: Update -> String) + def message(&block: Update -> Void) @message_hooks.push(block) end end