1
0
зеркало из https://github.com/glebtv/telegram-bot.git synced 2026-09-03 17:55:52 +03:00
Этот коммит содержится в:
Max Melentiev
2018-01-16 10:56:06 +03:00
родитель 3a876a42df
Коммит 88ae24b7e8
10 изменённых файлов: 108 добавлений и 62 удалений

Просмотреть файл

@@ -5,9 +5,13 @@ module Telegram
module Bot
class Error < StandardError; end
class NotFound < Error; end
# Raised for valid telegram response with 403 status code.
class Forbidden < Error; end
# Raised for valid telegram response with 404 status code.
class NotFound < Error; end
autoload :Async, 'telegram/bot/async'
autoload :Botan, 'telegram/bot/botan'
autoload :Client, 'telegram/bot/client'

Просмотреть файл

@@ -36,6 +36,18 @@ module Telegram
def prepare_async_args(action, body = {})
[action.to_s, Async.prepare_hash(prepare_body(body))]
end
def error_for_response(response)
result = JSON.parse(response.body) rescue nil # rubocop:disable RescueModifier
return Error.new(response.reason) unless result
message = result['description'] || '-'
# This errors are raised only for valid responses from Telegram
case response.status
when 403 then Forbidden.new(message)
when 404 then NotFound.new(message)
else Error.new("#{response.reason}: #{message}")
end
end
end
attr_reader :client, :token, :username, :base_uri
@@ -48,19 +60,9 @@ module Telegram
end
def request(action, body = {})
res = http_request("#{base_uri}#{action}", self.class.prepare_body(body))
status = res.status
return JSON.parse(res.body) if status < 300
result = JSON.parse(res.body) rescue nil # rubocop:disable RescueModifier
err_msg = result && result['description'] || '-'
if result
# This errors are raised only for valid responses from Telegram
case status
when 403 then raise Forbidden, err_msg
when 404 then raise NotFound, err_msg
end
end
raise Error, "#{res.reason}: #{err_msg}"
response = http_request("#{base_uri}#{action}", self.class.prepare_body(body))
raise self.class.error_for_response(response) if response.status >= 300
JSON.parse(response.body)
end
# Endpoint for low-level request. For easy host highjacking & instrumentation.

Просмотреть файл

@@ -54,8 +54,8 @@ module Telegram
@bots_config ||=
if defined?(Rails.application)
app = Rails.application
secrets = (app.respond_to?(:credentials) ? app.credentials : app.secrets).
fetch(:telegram, {}).with_indifferent_access
store = app.respond_to?(:credentials) ? app.credentials : app.secrets
secrets = store.fetch(:telegram, {}).with_indifferent_access
secrets.fetch(:bots, {}).symbolize_keys.tap do |config|
default = secrets[:bot]
config[:default] = default if default

Просмотреть файл

@@ -45,23 +45,31 @@ module Telegram
# other_bot => TelegramAuctionController,
# admin_chat: TelegramAdminChatController
#
# TODO: Deprecate it in favor of telegram_webhook.
def telegram_webhooks(controllers, bots = nil, **options)
unless controllers.is_a?(Hash)
bots = bots ? Array.wrap(bots) : Telegram.bots.values
controllers = Hash[bots.map { |x| [x, controllers] }]
end
controllers.each do |bot, controller|
bot = Client.wrap(bot)
controller, bot_options = controller if controller.is_a?(Array)
params = {
to: Middleware.new(bot, controller),
as: RoutesHelper.route_name_for_bot(bot),
format: false,
}.merge!(options).merge!(bot_options || {})
post("telegram/#{RoutesHelper.escape_token bot.token}", params)
UpdatesPoller.add(bot, controller) if Telegram.bot_poller_mode?
telegram_webhook(controller, bot, options.merge(bot_options || {}))
end
end
# Define route which processes requests using given controller and bot.
#
# See telegram_webhooks for examples.
def telegram_webhook(controller, bot, **options)
bot = Client.wrap(bot)
params = {
to: Middleware.new(bot, controller),
as: RoutesHelper.route_name_for_bot(bot),
format: false,
}.merge!(options)
post("telegram/#{RoutesHelper.escape_token bot.token}", params)
UpdatesPoller.add(bot, controller) if Telegram.bot_poller_mode?
end
end
end
end

Просмотреть файл

@@ -120,10 +120,17 @@ module Telegram
# any commands.
def command_from_text(text, username = nil)
return unless text
match = text.match CMD_REGEX
match = text.match(CMD_REGEX)
return unless match
return if match[3] && username != true && match[3] != username
[match[1], text.split.drop(1)]
mention = match[3]
[match[1], text.split.drop(1)] if username == true || !mention || mention == username
end
def payload_from_update(update)
update && PAYLOAD_TYPES.find do |type|
item = update[type]
return [item, type] if item
end
end
end
@@ -142,13 +149,7 @@ module Telegram
@_update = update
@_bot = bot
@_chat, @_from = options && options.values_at(:chat, :from)
payload_data = nil
update && PAYLOAD_TYPES.find do |type|
item = update[type]
payload_data = [item, type] if item
end
@_payload, @_payload_type = payload_data
@_payload, @_payload_type = self.class.payload_from_update(update)
end
# Accessor to `'chat'` field of payload. Also tries `'chat'` in `'message'`

Просмотреть файл

@@ -45,36 +45,44 @@ module Telegram
log { 'Started bot poller.' }
while running
begin
fetch_updates do |update|
controller.dispatch(bot, update)
end
updates = fetch_updates
process_updates(updates) if updates && updates.any?
rescue Interrupt
@running = false
rescue StandardError => e
logger.error { ([e.message] + e.backtrace).join("\n") } if logger
end
end
log { 'Stop polling bot updates.' }
log { 'Stoped polling bot updates.' }
end
# Method to stop poller from other thread.
def stop
return unless running
log { 'Killing polling thread.' }
log { 'Stopping polling bot updates.' }
@running = false
end
def fetch_updates
def fetch_updates(offset = self.offset)
response = bot.async(false) { bot.get_updates(offset: offset, timeout: timeout) }
updates = response.is_a?(Array) ? response : response['result']
return unless updates && updates.any?
response.is_a?(Array) ? response : response['result']
rescue Timeout::Error
log { 'Fetch timeout' }
nil
end
def process_updates(updates)
reload! do
updates.each do |update|
@offset = update['update_id'] + 1
yield update
process_update(update)
end
end
rescue Timeout::Error
log { 'Fetch timeout' }
rescue StandardError => e
logger.error { ([e.message] + e.backtrace).join("\n") } if logger
end
# Override this method to setup custom error collector.
def process_update(update)
controller.dispatch(bot, update)
end
def reload!