1
0
зеркало из https://github.com/glebtv/telegram-bot.git synced 2026-08-28 15:26:18 +03:00

Сравнить коммиты

...

5 Коммитов

Автор SHA1 Сообщение Дата
Max Melentiev
17260cb5a9 v0.11.0 2017-02-10 09:34:15 +03:00
Max Melentiev
817af95369 Remove Bot::StaleChat in favor of Bot::Forbidden 2017-02-10 09:33:41 +03:00
Max Melentiev
99fbe41b16 Fixed support for *channel_post updates 2016-12-09 13:33:55 +03:00
Max Melentiev
88178113d7 Support (edited_)channel_post updates, add api methods from 2.3, 2.3.1 2016-12-09 13:23:58 +03:00
printercu
1a2ac0dd83 Update README.md 2016-11-16 21:31:02 +03:00
12 изменённых файлов: 126 добавлений и 93 удалений

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

@@ -1,3 +1,14 @@
# 0.11.0
- Remove Bot::StaleChat in favor of Bot::Forbidden, as Telegram adds more
and more new descriptions.
Please open an issue if you face a problem.
# 0.10.2
- Support `(edited_)channel_post` updates.
- New methods from 2.3, 2.3.1 API updates.
# 0.10.0
- Integration helpers for RSpec.

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

@@ -13,7 +13,7 @@ group :development do
gem 'pry', '~> 0.10.1'
gem 'pry-byebug', '~> 3.2.0'
gem 'telegram-bot-types', '~> 0.2.0'
gem 'telegram-bot-types', '~> 0.3.0'
gem 'rspec', '~> 3.5.0'
gem 'rspec-its', '~> 1.1.0'

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

@@ -24,6 +24,9 @@ Here is sample [telegram_bot_app](https://github.com/telegram-bot-rb/telegram_bo
with session, keyboards and inline queries.
Run it on your local machine in 1 minute!
And here is [app teamplate](https://github.com/telegram-bot-rb/rails_template)
to generate clean app in seconds.
## Installation
Add this line to your application's Gemfile:
@@ -97,7 +100,7 @@ bot.get_me.class # => Telegram::Bot::Types::User
```
Any API request error will raise `Telegram::Bot::Error` with description in its message.
Special `Telegram::Bot::StaleChat` is raised when bot can't post messages to the chat anymore.
Special `Telegram::Bot::Forbidden` is raised when bot can't post messages to the chat anymore.
### Controller

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

@@ -6,26 +6,7 @@ module Telegram
module Bot
class Error < StandardError; end
class NotFound < Error; end
# Error class for events when chat is not available anymore for bot.
# While Telegram has same error codes for different messages and there is no
# official docs for this error codes it uses `description` to
# check response.
class StaleChat < Error
DESCRIPTIONS = [
'Bot was blocked',
'bot was kicked',
"can't write to",
'group chat is deactivated',
].freeze
class << self
def match_response?(response)
description = response['description'].to_s
DESCRIPTIONS.any? { |x| description[x] }
end
end
end
class Forbidden < Error; end
autoload :Async, 'telegram/bot/async'
autoload :Botan, 'telegram/bot/botan'

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

@@ -46,44 +46,44 @@ module Telegram
@base_uri = format URL_TEMPLATE, self.token
end
def request(action, body = {}) # rubocop:disable PerceivedComplexity
def request(action, body = {})
res = http_request("#{base_uri}#{action}", self.class.prepare_body(body))
status = res.status
return JSON.parse(res.body) if 300 > status
result = JSON.parse(res.body) rescue nil # rubocop:disable RescueModifier
err_msg = "#{res.reason}: #{result && result['description'] || '-'}"
err_msg = result && result['description'] || '-'
if result
# NotFound is raised only for valid responses from Telegram
raise NotFound, err_msg if 404 == status
raise StaleChat, err_msg if StaleChat.match_response?(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, err_msg
raise Error, "#{res.reason}: #{err_msg}"
end
# Splited to the sections similar to API docs.
%w(
deleteWebhook
getUpdates
getWebhookInfo
setWebhook
answerCallbackQuery
answerInlineQuery
editMessageCaption
editMessageReplyMarkup
editMessageText
forwardMessage
getChat
getChatAdministrators
getChatMember
getChatMembersCount
getFile
getGameHighScores
getMe
getUpdates
getUserProfilePhotos
getWebhookInfo
kickChatMember
leaveChat
sendAudio
sendChatAction
sendContact
sendDocument
sendGame
sendLocation
sendMessage
sendPhoto
@@ -91,9 +91,17 @@ module Telegram
sendVenue
sendVideo
sendVoice
setGameScore
setWebhook
unbanChatMember
editMessageCaption
editMessageReplyMarkup
editMessageText
answerInlineQuery
getGameHighScores
sendGame
setGameScore
).each do |method|
define_method(method.underscore) { |*args| request(method, *args) }
end

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

@@ -139,9 +139,9 @@ module Telegram
# Helper for asserting message is sent. Note that options are checked
# with `hash_including`. For strict checks use #make_telegram_request.
def send_telegram_message(bot, text = nil, options = {})
description = "send telegram message #{text.inspect}"
text = a_string_matching(text) if text.is_a?(Regexp)
options = options.merge(text: text) if text
description = "send telegram message #{text.inspect}"
MakeTelegramRequest.new(bot, :sendMessage, description: description).
with(hash_including(options))
end

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

@@ -50,7 +50,7 @@ module Telegram
# ControllerClass.new(bot, from: telegram_user, chat: telegram_chat).
# process(:help, *args)
#
class UpdatesController < AbstractController::Base
class UpdatesController < AbstractController::Base # rubocop:disable ClassLength
abstract!
require 'telegram/bot/updates_controller/session'
@@ -80,10 +80,12 @@ module Telegram
PAYLOAD_TYPES = %w(
message
edited_message
channel_post
edited_channel_post
inline_query
chosen_inline_result
callback_query
edited_message
).freeze
CMD_REGEX = %r{\A/([a-z\d_]{,31})(@(\S+))?(\s|$)}i
CONFLICT_CMD_REGEX = Regexp.new("^(#{PAYLOAD_TYPES.join('|')}|\\d)")
@@ -181,11 +183,13 @@ module Telegram
cmd &&= self.class.action_for_command(cmd)
[true, cmd, args] if cmd
end
alias_method :action_for_channel_post, :action_for_message
# It doesn't extract commands from edited messages. Just process
# them as usual ones.
def action_for_edited_message
end
alias_method :action_for_edited_channel_post, :action_for_edited_message
def action_for_inline_query
[false, payload_type, [payload['query'], payload['offset']]]

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

@@ -1,6 +1,6 @@
module Telegram
module Bot
VERSION = '0.10.0'.freeze
VERSION = '0.11.0'.freeze
def self.gem_version
Gem::Version.new VERSION

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

@@ -3,7 +3,7 @@ RSpec.describe Telegram::Bot::Botan do
let(:token) { 'token' }
include_examples 'initializers', :botans
include_examples 'async', request_args: -> { [double(:method), double(:url)] }
it_behaves_like 'async', request_args: -> { [double(:method), double(:url)] }
describe '.new' do
subject { described_class.new(*args) }

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

@@ -4,7 +4,7 @@ RSpec.describe Telegram::Bot::Client do
let(:botan_token) { double(:botan_token) }
include_examples 'initializers'
include_examples 'async', request_args: -> { [double(:action), {body: :content}] }
it_behaves_like 'async', request_args: -> { [double(:action), {body: :content}] }
describe '.prepare_body' do
subject { described_class.prepare_body(input) }
@@ -48,4 +48,49 @@ RSpec.describe Telegram::Bot::Client do
its(:base_uri) { should include args[0][:token] }
end
end
describe '#request' do
subject { -> { instance.request(action, request_body) } }
let(:action) { :some_action }
let(:url) { "#{format described_class::URL_TEMPLATE, token}#{action}" }
let(:request_body) { double(:body) }
let(:prepared_body) { double(:prepared_body) }
let(:response) { HTTP::Message.new_response(body).tap { |x| x.status = status } }
let(:status) { 200 }
let(:body) { body_json.to_json }
let(:body_json) { {'param' => 'val', 'description' => 'some description'} }
before do
expect(described_class).to receive(:prepare_body).with(request_body) { prepared_body }
expect(instance).to receive(:http_request).with(url, prepared_body) { response }
end
around { |ex| Telegram::Bot::ClientStub.stub_all!(false) { ex.run } }
shared_examples 'invalid body' do |error = Telegram::Bot::Error|
context 'when body is not json' do
let(:body) { '{' }
it { should raise_error error }
end
end
its(:call) { should eq body_json }
include_examples 'invalid body', JSON::ParserError
context 'when status is 403' do
let(:status) { 403 }
it { should raise_error Telegram::Bot::Forbidden, body_json['description'] }
include_examples 'invalid body'
end
context 'when status is 404' do
let(:status) { 404 }
it { should raise_error Telegram::Bot::NotFound, body_json['description'] }
include_examples 'invalid body'
end
context 'when status is other' do
let(:status) { 500 }
it { should raise_error Telegram::Bot::Error, /#{body_json['description']}/ }
end
end
end

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

@@ -102,42 +102,44 @@ RSpec.describe Telegram::Bot::UpdatesController do
it { should eq [false, payload_type, payload.values_at(:data)] }
end
context 'when payload is edited_message' do
let(:payload_type) { 'edited_message' }
it { should eq [false, payload_type, [payload]] }
end
context 'when payload is not supported' do
let(:payload_type) { '_unsupported_' }
it { should eq [false, :unsupported_payload_type, []] }
end
context 'when payload is message' do
let(:payload_type) { 'message' }
let(:payload) { {'text' => text} }
let(:text) { 'test' }
it { should eq [false, payload_type, [payload]] }
context 'with command' do
let(:text) { "/test#{"@#{mention}" if mention} arg 1 2" }
let(:mention) {}
it { should eq [true, 'test', %w(arg 1 2)] }
context 'with mention' do
let(:mention) { bot.username }
it { should eq [true, 'test', %w(arg 1 2)] }
end
context 'with mention for other bot' do
let(:mention) { other_bot_name }
it { should eq [false, 'message', [payload]] }
end
%w(message channel_post).each do |type|
context 'when payload is edited_message' do
let(:payload_type) { "edited_#{type}" }
it { should eq [false, payload_type, [payload]] }
end
context 'without text' do
let(:payload) { {'audio' => {'file_id' => 123}} }
context 'when payload is message' do
let(:payload_type) { type }
let(:payload) { {'text' => text} }
let(:text) { 'test' }
it { should eq [false, payload_type, [payload]] }
context 'with command' do
let(:text) { "/test#{"@#{mention}" if mention} arg 1 2" }
let(:mention) {}
it { should eq [true, 'test', %w(arg 1 2)] }
context 'with mention' do
let(:mention) { bot.username }
it { should eq [true, 'test', %w(arg 1 2)] }
end
context 'with mention for other bot' do
let(:mention) { other_bot_name }
it { should eq [false, payload_type, [payload]] }
end
end
context 'without text' do
let(:payload) { {'audio' => {'file_id' => 123}} }
it { should eq [false, payload_type, [payload]] }
end
end
end
end

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

@@ -2,25 +2,4 @@ RSpec.describe Telegram::Bot do
it 'has a version number' do
expect(described_class::VERSION).not_to be nil
end
describe described_class::StaleChat do
describe '.match_response?' do
subject { ->(val) { described_class.match_response?(val) } }
it 'returns true for specific errors' do
expect(subject.call({})).to eq false
expect(subject.call('description' => 'test')).to eq false
expect(subject.call('description' => 'Error: bot was kicked from')).to eq true
expect(subject.call(
'description' => "Forbidden: can't write to private chat with deleted user"
)).to eq true
expect(subject.call(
'description' => 'Bad request: group chat is deactivated'
)).to eq true
expect(subject.call(
'description' => 'Forbidden: Bot was blocked by the user'
)).to eq true
end
end
end
end