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

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

@@ -1,3 +1,8 @@
checks:
method-complexity:
config:
threshold: 6 # should be just fine
plugins: plugins:
rubocop: rubocop:
enabled: true enabled: true

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

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

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

@@ -36,6 +36,18 @@ module Telegram
def prepare_async_args(action, body = {}) def prepare_async_args(action, body = {})
[action.to_s, Async.prepare_hash(prepare_body(body))] [action.to_s, Async.prepare_hash(prepare_body(body))]
end 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 end
attr_reader :client, :token, :username, :base_uri attr_reader :client, :token, :username, :base_uri
@@ -48,19 +60,9 @@ module Telegram
end end
def request(action, body = {}) def request(action, body = {})
res = http_request("#{base_uri}#{action}", self.class.prepare_body(body)) response = http_request("#{base_uri}#{action}", self.class.prepare_body(body))
status = res.status raise self.class.error_for_response(response) if response.status >= 300
return JSON.parse(res.body) if status < 300 JSON.parse(response.body)
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}"
end end
# Endpoint for low-level request. For easy host highjacking & instrumentation. # Endpoint for low-level request. For easy host highjacking & instrumentation.

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

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

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

@@ -45,23 +45,31 @@ module Telegram
# other_bot => TelegramAuctionController, # other_bot => TelegramAuctionController,
# admin_chat: TelegramAdminChatController # admin_chat: TelegramAdminChatController
# #
# TODO: Deprecate it in favor of telegram_webhook.
def telegram_webhooks(controllers, bots = nil, **options) def telegram_webhooks(controllers, bots = nil, **options)
unless controllers.is_a?(Hash) unless controllers.is_a?(Hash)
bots = bots ? Array.wrap(bots) : Telegram.bots.values bots = bots ? Array.wrap(bots) : Telegram.bots.values
controllers = Hash[bots.map { |x| [x, controllers] }] controllers = Hash[bots.map { |x| [x, controllers] }]
end end
controllers.each do |bot, controller| controllers.each do |bot, controller|
bot = Client.wrap(bot)
controller, bot_options = controller if controller.is_a?(Array) controller, bot_options = controller if controller.is_a?(Array)
params = { telegram_webhook(controller, bot, options.merge(bot_options || {}))
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?
end end
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 end
end end

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

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

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

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

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

@@ -24,8 +24,8 @@ class TestApplication < Rails::Application
}, },
} }
if Rails.application.respond_to?(:credentials) if respond_to?(:credentials)
Rails.application.credentials.config[:telegram] = telegram_config credentials.config[:telegram] = telegram_config
else else
secrets[:secret_key_base] = 'test' secrets[:secret_key_base] = 'test'
secrets[:telegram] = telegram_config secrets[:telegram] = telegram_config

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

@@ -16,7 +16,7 @@ $LOAD_PATH.unshift GEM_ROOT.join('lib')
require 'telegram/bot' require 'telegram/bot'
require 'telegram/bot/updates_controller/rspec_helpers' require 'telegram/bot/updates_controller/rspec_helpers'
require 'telegram/bot/types' require 'telegram/bot/types'
require 'active_support/core_ext/object/json' require 'active_support/json'
Dir[GEM_ROOT.join('spec/support/**/*.rb')].each { |f| require f } Dir[GEM_ROOT.join('spec/support/**/*.rb')].each { |f| require f }

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

@@ -8,12 +8,32 @@ RSpec.describe Telegram::Bot::UpdatesPoller do
it { should be } it { should be }
end end
describe '#fetch_updates' do describe '#process_updates' do
subject { -> { instance.fetch_updates(&block) } } subject { -> { instance.process_updates(updates) } }
let(:block) { ->(x) { expect(x).to eq expected_results.shift } } let(:block) { ->(x) { expect(x).to eq expected_results.shift } }
let(:results) { [{update_id: 12}, {update_id: 34}] } let(:updates) { [{update_id: 12}, {update_id: 34}].as_json }
let(:expected_results) { results.as_json } let(:processed_updates) { [] }
let(:request_result) { {ok: true, result: results}.as_json } before do
allow(controller).to receive(:dispatch) do |bot, update|
expect(bot).to eq self.bot
processed_updates << update
end
end
it { should change(instance, :offset).to(updates.last['update_id'] + 1) }
it { should change(self, :processed_updates).to(updates) }
context 'with typed response' do
let(:updates) { super().map { |x| Telegram::Bot::Types::Update.new(x) } }
it { should change(instance, :offset).to(updates.last['update_id'] + 1) }
it { should change(self, :processed_updates).to(updates) }
end
end
describe '#fetch_updates' do
subject { instance.fetch_updates }
let(:updates) { [{update_id: 12}, {update_id: 34}] }
let(:request_result) { {ok: true, result: updates}.as_json }
before do before do
allow(bot).to receive(:get_updates) do allow(bot).to receive(:get_updates) do
expect(bot.async).to be_falsy expect(bot.async).to be_falsy
@@ -21,19 +41,17 @@ RSpec.describe Telegram::Bot::UpdatesPoller do
end end
end end
it { should change(instance, :offset).to(results.last[:update_id] + 1) } it { should eq updates.as_json }
it { should change { expected_results }.to([]) }
context 'with typed response' do context 'with typed response' do
let(:request_result) { results.as_json.map { |x| Telegram::Bot::Types::Update.new(x) } } let(:updates) { super().map { |x| Telegram::Bot::Types::Update.new(x.as_json) } }
let(:expected_results) { request_result.dup } let(:request_result) { updates }
it { should change(instance, :offset).to(results.last[:update_id] + 1) } it { should eq updates }
it { should change { expected_results }.to([]) }
end end
context 'when bot is in async mode' do context 'when bot is in async mode' do
let(:bot) { Telegram::Bot::Client.new('token', async: Class.new) } let(:bot) { Telegram::Bot::Client.new('token', async: Class.new) }
it { should change { expected_results }.to([]) } it { should eq updates.as_json }
end end
end end
end end