60 lines
2.5 KiB
Crystal
60 lines
2.5 KiB
Crystal
require "http"
|
|
|
|
module Telepathy
|
|
class Bot
|
|
def initialize(@api_token : String)
|
|
@request_base = "https://api.telegram.org/bot#{@api_token}"
|
|
@this_user = uninitialized User?
|
|
@this_user = get_me
|
|
@last_update_id = uninitialized Int64?
|
|
@last_update_id = nil
|
|
@command_hooks = {} of String => Update, Array(String) -> Void
|
|
@message_hooks = [] of Update -> Void
|
|
end
|
|
|
|
def get_me
|
|
response = HTTP::Client.get(@request_base + "/getMe",
|
|
headers: HTTP::Headers{"User-agent" => "Telepathy"})
|
|
return Response(User).from_json(response.body).result
|
|
end
|
|
|
|
def get_updates(timeout = 0)
|
|
update_data = {} of String => Int64 | Int32 | String
|
|
update_data["timeout"] = timeout
|
|
@last_update_id.try { |id| update_data["offset"] = id }
|
|
response = HTTP::Client.get(@request_base + "/getUpdates",
|
|
headers: HTTP::Headers{"User-agent" => "Telepathy", "Content-type" => "application/json" },
|
|
body: update_data.to_json)
|
|
updates = Response(Array(Update)).from_json(response.body).result
|
|
updates.last?.try { |update| @last_update_id = update.update_id + 1 }
|
|
return updates
|
|
end
|
|
|
|
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 -> Void)
|
|
@message_hooks.push(block)
|
|
end
|
|
end
|
|
end
|