telegram-bot 0.3.0 → 0.14.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +5 -5
- data/.codeclimate.yml +8 -0
- data/.gitignore +3 -0
- data/.rubocop.yml +35 -7
- data/.travis.yml +26 -1
- data/Appraisals +31 -0
- data/CHANGELOG.md +161 -0
- data/Gemfile +8 -3
- data/README.md +463 -73
- data/bin/fetch-telegram-methods +41 -0
- data/bin/setup +1 -0
- data/gemfiles/rails_42.gemfile +21 -0
- data/gemfiles/rails_50.gemfile +21 -0
- data/gemfiles/rails_51.gemfile +21 -0
- data/gemfiles/rails_52.gemfile +21 -0
- data/gemfiles/rails_60.gemfile +21 -0
- data/gemfiles/rails_61.gemfile +23 -0
- data/lib/tasks/telegram-bot.rake +13 -7
- data/lib/telegram/bot/async.rb +157 -0
- data/lib/telegram/bot/client/api_helper.rb +31 -0
- data/lib/telegram/bot/client/api_methods.txt +75 -0
- data/lib/telegram/bot/client/typed_response.rb +26 -0
- data/lib/telegram/bot/client.rb +79 -0
- data/lib/telegram/bot/client_stub.rb +52 -0
- data/lib/telegram/bot/config_methods.rb +72 -0
- data/lib/telegram/bot/debug_client.rb +23 -0
- data/lib/telegram/bot/initializers.rb +21 -0
- data/lib/telegram/bot/middleware.rb +7 -5
- data/lib/telegram/bot/railtie.rb +4 -2
- data/lib/telegram/bot/routes_helper.rb +24 -33
- data/lib/telegram/bot/rspec/callback_query_helpers.rb +39 -0
- data/lib/telegram/bot/rspec/client_matchers.rb +151 -0
- data/lib/telegram/bot/rspec/integration/poller.rb +14 -0
- data/lib/telegram/bot/rspec/integration/rack.rb +24 -0
- data/lib/telegram/bot/rspec/integration/rails.rb +28 -0
- data/lib/telegram/bot/rspec/integration/shared.rb +14 -0
- data/lib/telegram/bot/rspec/integration.rb +10 -0
- data/lib/telegram/bot/rspec/message_helpers.rb +26 -0
- data/lib/telegram/bot/rspec.rb +16 -0
- data/lib/telegram/bot/updates_controller/callback_query_context.rb +37 -0
- data/lib/telegram/bot/updates_controller/commands.rb +44 -0
- data/lib/telegram/bot/updates_controller/instrumentation.rb +15 -8
- data/lib/telegram/bot/updates_controller/log_subscriber.rb +4 -4
- data/lib/telegram/bot/updates_controller/message_context.rb +78 -0
- data/lib/telegram/bot/updates_controller/reply_helpers.rb +74 -0
- data/lib/telegram/bot/updates_controller/rescue.rb +20 -0
- data/lib/telegram/bot/updates_controller/rspec_helpers.rb +41 -0
- data/lib/telegram/bot/updates_controller/session.rb +99 -0
- data/lib/telegram/bot/updates_controller/testing.rb +35 -0
- data/lib/telegram/bot/updates_controller/translation.rb +47 -0
- data/lib/telegram/bot/updates_controller/typed_update.rb +14 -0
- data/lib/telegram/bot/updates_controller.rb +179 -60
- data/lib/telegram/bot/updates_poller.rb +57 -27
- data/lib/telegram/bot/version.rb +2 -2
- data/lib/telegram/bot.rb +22 -84
- data/telegram-bot.gemspec +8 -5
- metadata +65 -17
- data/lib/telegram/bottable.rb +0 -41
data/README.md
CHANGED
|
@@ -1,21 +1,35 @@
|
|
|
1
1
|
# Telegram::Bot
|
|
2
2
|
|
|
3
3
|
[](http://badge.fury.io/rb/telegram-bot)
|
|
4
|
-
[](https://codeclimate.com/github/telegram-bot-rb/telegram-bot)
|
|
5
|
+
[](https://travis-ci.org/telegram-bot-rb/telegram-bot)
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
7
|
+
__Breaking changes in v0.14!__ See [upgrade guide](https://github.com/telegram-bot-rb/telegram-bot/wiki/Upgrading-to-0.14).
|
|
8
|
+
|
|
9
|
+
Tools for developing Telegram bots. Best used with Rails, but can be used in
|
|
10
|
+
[standalone app](https://github.com/telegram-bot-rb/telegram-bot/wiki/Not-rails-application).
|
|
11
|
+
Supposed to be used in webhook-mode in production, and poller-mode
|
|
9
12
|
in development, but you can use poller in production if you want.
|
|
10
13
|
|
|
11
14
|
Package contains:
|
|
12
15
|
|
|
13
|
-
-
|
|
14
|
-
[httpclient](https://github.com/nahi/httpclient)
|
|
15
|
-
- Controller with message parser
|
|
16
|
+
- Lightweight client for bot API (with fast and thread-safe
|
|
17
|
+
[httpclient](https://github.com/nahi/httpclient) under the hood).
|
|
18
|
+
- Controller with message parser: define methods for commands, not `case` branches.
|
|
16
19
|
- Middleware and routes helpers for production env.
|
|
17
20
|
- Poller with automatic source-reloader for development env.
|
|
18
21
|
- Rake tasks to update webhook urls.
|
|
22
|
+
- __[Async mode](#async-mode)__.
|
|
23
|
+
Let the queue adapter handle network errors!
|
|
24
|
+
|
|
25
|
+
Here is sample [telegram_bot_app](https://github.com/telegram-bot-rb/telegram_bot_app)
|
|
26
|
+
with session, keyboards and inline queries.
|
|
27
|
+
Run it on your local machine in 1 minute!
|
|
28
|
+
|
|
29
|
+
And here is [app template](https://github.com/telegram-bot-rb/rails_template)
|
|
30
|
+
to generate clean app in seconds.
|
|
31
|
+
|
|
32
|
+
Examples and cookbook in [wiki](https://github.com/telegram-bot-rb/telegram-bot/wiki).
|
|
19
33
|
|
|
20
34
|
## Installation
|
|
21
35
|
|
|
@@ -33,54 +47,131 @@ Or install it yourself as:
|
|
|
33
47
|
|
|
34
48
|
$ gem install telegram-bot
|
|
35
49
|
|
|
50
|
+
Require if necessary:
|
|
51
|
+
|
|
52
|
+
```ruby
|
|
53
|
+
require 'telegram/bot'
|
|
54
|
+
```
|
|
55
|
+
|
|
36
56
|
## Usage
|
|
37
57
|
|
|
38
58
|
### Configuration
|
|
39
59
|
|
|
40
|
-
|
|
60
|
+
While clients can be instantiated explicitly, there is `Telegram.bots_config=` method
|
|
61
|
+
to configure app-wide clients, which are accessible via `Telegram.bots`.
|
|
62
|
+
It accepts hash of `{bot_id: bot_config}`, and there is special id `:default`
|
|
63
|
+
which is used for `Telegram.bot`.
|
|
64
|
+
|
|
65
|
+
```ruby
|
|
66
|
+
Telegram.bots_config = {
|
|
67
|
+
default: DEFAULT_BOT_TOKEN,
|
|
68
|
+
chat: {token: CHAT_BOT_TOKEN, username: 'chatbot'},
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
Telegram.bot.get_updates
|
|
72
|
+
Telegram.bot == Telegram.bots[:default] # true
|
|
73
|
+
Telegram.bots[:chat].send_message(...)
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Configuration in Rails app
|
|
77
|
+
|
|
78
|
+
In Rails app `Telegram.bots_config` is read from `secrets.yml` automatically
|
|
79
|
+
from `telegram` section:
|
|
41
80
|
|
|
42
81
|
```yml
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
#
|
|
46
|
-
|
|
47
|
-
# or
|
|
48
|
-
|
|
49
|
-
token:
|
|
50
|
-
username:
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
82
|
+
development:
|
|
83
|
+
telegram:
|
|
84
|
+
# Single bot can be specified like this
|
|
85
|
+
bot: TOKEN
|
|
86
|
+
# or
|
|
87
|
+
bot:
|
|
88
|
+
token: TOKEN
|
|
89
|
+
username: SomeBot
|
|
90
|
+
|
|
91
|
+
# For multiple bots in single app use hash of `internal_bot_id => settings`
|
|
92
|
+
bots:
|
|
93
|
+
# just set the bot token
|
|
94
|
+
chat: TOKEN_1
|
|
95
|
+
# or add username to support commands with mentions (/help@ChatBot)
|
|
96
|
+
auction:
|
|
97
|
+
token: TOKEN_2
|
|
98
|
+
username: ChatBot
|
|
58
99
|
```
|
|
59
100
|
|
|
60
|
-
|
|
101
|
+
For Rails >= 5.2 `Telegram::Bot` searches for config first in credentials and then in secrets.
|
|
102
|
+
To use credentials as config store, add telegram section to credentials instead of secrets using
|
|
103
|
+
`rails credentials:edit`. In this case be aware of that [Rails < 6.0 may not load
|
|
104
|
+
credentials in dev environment by default](https://github.com/telegram-bot-rb/telegram-bot/issues/74#issuecomment-384205609).
|
|
105
|
+
In Rails >= 6.0 run `rails credentials:edit --environment development` to configure bot
|
|
106
|
+
in each environment.
|
|
107
|
+
|
|
108
|
+
I suggest not using Rails 5.2 credentials because it can lead to leakage of sensitive data
|
|
109
|
+
and it's more difficult to use in multiple environments. See
|
|
110
|
+
[secure_credentials](https://github.com/printercu/secure_credentials) gem for better option.
|
|
61
111
|
|
|
62
112
|
From now clients will be accessible with `Telegram.bots[:chat]` or `Telegram.bots[:auction]`.
|
|
63
113
|
Single bot can be accessed with `Telegram.bot` or `Telegram.bots[:default]`.
|
|
64
114
|
|
|
65
|
-
|
|
115
|
+
### Client
|
|
116
|
+
|
|
117
|
+
Client is instantiated with `Telegram::Bot::Client.new(token, username)`.
|
|
66
118
|
Username is optional and used only to parse commands with mentions.
|
|
67
119
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
120
|
+
There is `request(path_suffix, body)` method to perform any query.
|
|
121
|
+
And there are shortcuts for all available requests in underscored style
|
|
122
|
+
(`answer_inline_query(params)` instead of `answerInlineQuery`).
|
|
71
123
|
|
|
72
124
|
```ruby
|
|
73
|
-
bot.
|
|
125
|
+
bot.request(:getMe) or bot.get_me
|
|
126
|
+
bot.request(:getupdates, offset: 1) or bot.get_updates(offset: 1)
|
|
127
|
+
bot.send_message(chat_id: chat_id, text: 'Test')
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
There is no magic, they just pass params as is and set `path_suffix`.
|
|
131
|
+
See [`Client`](https://github.com/telegram-bot-rb/telegram-bot/blob/master/lib/telegram/bot/client.rb)
|
|
132
|
+
class for list of available methods. Please open PR or issue if it misses methods from
|
|
133
|
+
new API versions.
|
|
134
|
+
|
|
135
|
+
Any API request error will raise `Telegram::Bot::Error` with description in its message.
|
|
136
|
+
Special `Telegram::Bot::Forbidden` is raised when bot can't post messages to the chat anymore.
|
|
137
|
+
|
|
138
|
+
#### Typed responses
|
|
139
|
+
|
|
140
|
+
By default client will return parsed json responses. You can enable
|
|
141
|
+
response typecasting to virtus models using
|
|
142
|
+
[`telegram-bot-types`](https://github.com/telegram-bot-rb/telegram-bot-types) gem:
|
|
143
|
+
|
|
144
|
+
```ruby
|
|
145
|
+
# Add to your gemfile:
|
|
146
|
+
gem 'telegram-bot-types', '~> x.x.x'
|
|
147
|
+
# Enable typecasting:
|
|
148
|
+
Telegram::Bot::Client.typed_response!
|
|
149
|
+
# or for single instance:
|
|
150
|
+
bot.extend Telegram::Bot::Client::TypedResponse
|
|
151
|
+
|
|
152
|
+
bot.get_me.class # => Telegram::Bot::Types::User
|
|
74
153
|
```
|
|
75
154
|
|
|
76
155
|
### Controller
|
|
77
156
|
|
|
157
|
+
Controller makes it easy to keep bot's code readable.
|
|
158
|
+
It does nothing more than finding out action name for update and invoking it.
|
|
159
|
+
So there is almost no overhead comparing to large `switch`, while you
|
|
160
|
+
can represent actions as separate methods keeping source much more readable and supportable.
|
|
161
|
+
|
|
162
|
+
New instance of controller is instantiated for each update.
|
|
163
|
+
This way every update is processed in isolation from others.
|
|
164
|
+
|
|
165
|
+
Bot controllers like usual rails controllers provides features like callbacks,
|
|
166
|
+
`rescue_from` and instrumentation.
|
|
167
|
+
|
|
78
168
|
```ruby
|
|
79
169
|
class Telegram::WebhookController < Telegram::Bot::UpdatesController
|
|
80
170
|
# use callbacks like in any other controllers
|
|
81
|
-
around_action :
|
|
171
|
+
around_action :with_locale
|
|
82
172
|
|
|
83
|
-
# Every update can have one of: message, inline_query
|
|
173
|
+
# Every update can have one of: message, inline_query, chosen_inline_result,
|
|
174
|
+
# callback_query, etc.
|
|
84
175
|
# Define method with same name to respond to this updates.
|
|
85
176
|
def message(message)
|
|
86
177
|
# message can be also accessed via instance method
|
|
@@ -88,26 +179,32 @@ class Telegram::WebhookController < Telegram::Bot::UpdatesController
|
|
|
88
179
|
# store_message(message['text'])
|
|
89
180
|
end
|
|
90
181
|
|
|
91
|
-
#
|
|
182
|
+
# This basic methods receives commonly used params:
|
|
183
|
+
#
|
|
184
|
+
# message(payload)
|
|
185
|
+
# inline_query(query, offset)
|
|
186
|
+
# chosen_inline_result(result_id, query)
|
|
187
|
+
# callback_query(data)
|
|
188
|
+
|
|
189
|
+
# Define public methods ending with `!` to handle commands.
|
|
92
190
|
# Command arguments will be parsed and passed to the method.
|
|
93
191
|
# Be sure to use splat args and default values to not get errors when
|
|
94
192
|
# someone passed more or less arguments in the message.
|
|
95
|
-
|
|
96
|
-
# For some commands like /message or /123 method names should start with
|
|
97
|
-
# `on_` to avoid conflicts.
|
|
98
|
-
def start(data = nil, *)
|
|
193
|
+
def start!(data = nil, *)
|
|
99
194
|
# do_smth_with(data)
|
|
100
195
|
|
|
101
196
|
# There are `chat` & `from` shortcut methods.
|
|
197
|
+
# For callback queries `chat` if taken from `message` when it's available.
|
|
102
198
|
response = from ? "Hello #{from['username']}!" : 'Hi there!'
|
|
103
|
-
# There is `
|
|
104
|
-
|
|
105
|
-
reply_with
|
|
199
|
+
# There is `respond_with` helper to set `chat_id` from received message:
|
|
200
|
+
respond_with :message, text: response
|
|
201
|
+
# `reply_with` also sets `reply_to_message_id`:
|
|
202
|
+
reply_with :photo, photo: File.open('party.jpg')
|
|
106
203
|
end
|
|
107
204
|
|
|
108
205
|
private
|
|
109
206
|
|
|
110
|
-
def
|
|
207
|
+
def with_locale(&block)
|
|
111
208
|
I18n.with_locale(locale_for_update, &block)
|
|
112
209
|
end
|
|
113
210
|
|
|
@@ -121,57 +218,348 @@ class Telegram::WebhookController < Telegram::Bot::UpdatesController
|
|
|
121
218
|
end
|
|
122
219
|
```
|
|
123
220
|
|
|
124
|
-
|
|
221
|
+
#### Reply helpers
|
|
222
|
+
|
|
223
|
+
There are helpers to respond for basic actions. They just set chat/message/query
|
|
224
|
+
identifiers from update. See
|
|
225
|
+
[`ReplyHelpers`](https://github.com/telegram-bot-rb/telegram-bot/blob/master/lib/telegram/bot/updates_controller/reply_helpers.rb)
|
|
226
|
+
module for more information. Here are this methods signatures:
|
|
227
|
+
|
|
228
|
+
```ruby
|
|
229
|
+
def respond_with(type, params); end
|
|
230
|
+
def reply_with(type, params); end
|
|
231
|
+
def answer_inline_query(results, params = {}); end
|
|
232
|
+
def answer_callback_query(text, params = {}); end
|
|
233
|
+
def edit_message(type, params = {}); end
|
|
234
|
+
def answer_pre_checkout_query(ok, params = {}); end
|
|
235
|
+
def answer_shipping_query(ok, params = {}); end
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
#### Optional typecasting
|
|
239
|
+
|
|
240
|
+
You can enable typecasting of `update` with `telegram-bot-types` by including
|
|
241
|
+
`Telegram::Bot::UpdatesController::TypedUpdate`:
|
|
242
|
+
|
|
243
|
+
```ruby
|
|
244
|
+
class Telegram::WebhookController < Telegram::Bot::UpdatesController
|
|
245
|
+
include Telegram::Bot::UpdatesController::TypedUpdate
|
|
246
|
+
|
|
247
|
+
def message(message)
|
|
248
|
+
message.class # => Telegram::Bot::Types::Message
|
|
249
|
+
end
|
|
250
|
+
end
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
#### Session
|
|
254
|
+
|
|
255
|
+
This API is very close to ActiveController's session API, but works different
|
|
256
|
+
under the hood. Cookies can not be used to store session id or
|
|
257
|
+
whole session (like CookieStore does). So it uses key-value store and `session_key`
|
|
258
|
+
method to build identifier from update.
|
|
125
259
|
|
|
126
|
-
|
|
127
|
-
|
|
260
|
+
Store can be one of numerous `ActiveSupport::Cache` stores.
|
|
261
|
+
While `:file_store` is suitable for development and single-server deployments
|
|
262
|
+
without heavy load, it doesn't scale well. Key-value databases with persistance
|
|
263
|
+
like Redis are more appropriate for production use.
|
|
128
264
|
|
|
129
265
|
```ruby
|
|
130
|
-
#
|
|
131
|
-
|
|
266
|
+
# In rails app store can be configured in env files:
|
|
267
|
+
config.telegram_updates_controller.session_store = :redis_store, {expires_in: 1.month}
|
|
132
268
|
|
|
133
|
-
#
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
269
|
+
# In other app it can be done for all controllers with:
|
|
270
|
+
Telegram::Bot::UpdatesController.session_store = :redis_store, {expires_in: 1.month}
|
|
271
|
+
# or for specific one:
|
|
272
|
+
OneOfUpdatesController.session_store = :redis_store, {expires_in: 1.month}
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
Default session id is made from bot's username and `(from || chat)['id']`.
|
|
276
|
+
It means that session will be the same for updates from user in every chat,
|
|
277
|
+
and different for every user in the same group chat.
|
|
278
|
+
To change this behavior you can override `session_key` method, or even
|
|
279
|
+
define [multiple sessions](https://github.com/telegram-bot-rb/telegram-bot/wiki/Multiple-session-objects)
|
|
280
|
+
in single controller. For details see `Session` module.
|
|
281
|
+
|
|
282
|
+
```ruby
|
|
283
|
+
class Telegram::WebhookController < Telegram::Bot::UpdatesController
|
|
284
|
+
include Telegram::Bot::UpdatesController::Session
|
|
285
|
+
# or just shortcut:
|
|
286
|
+
use_session!
|
|
287
|
+
|
|
288
|
+
# You can override global config for this controller.
|
|
289
|
+
self.session_store = :file_store
|
|
290
|
+
|
|
291
|
+
def write!(text = nil, *)
|
|
292
|
+
session[:text] = text
|
|
293
|
+
end
|
|
294
|
+
|
|
295
|
+
def read!(*)
|
|
296
|
+
respond_with :message, text: session[:text]
|
|
297
|
+
end
|
|
298
|
+
|
|
299
|
+
private
|
|
300
|
+
|
|
301
|
+
# In this case session will persist for user only in specific chat.
|
|
302
|
+
# Same user in other chat will have different session.
|
|
303
|
+
def session_key
|
|
304
|
+
"#{bot.username}:#{chat['id']}:#{from['id']}" if chat && from
|
|
305
|
+
end
|
|
306
|
+
end
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
#### Message context
|
|
310
|
+
|
|
311
|
+
It's usual to support chain of messages like BotFather: after receiving command
|
|
312
|
+
it asks you for additional argument. There is `MessageContext` for this:
|
|
313
|
+
|
|
314
|
+
```ruby
|
|
315
|
+
class Telegram::WebhookController < Telegram::Bot::UpdatesController
|
|
316
|
+
include Telegram::Bot::UpdatesController::MessageContext
|
|
317
|
+
|
|
318
|
+
def rename!(*)
|
|
319
|
+
# set context for the next message
|
|
320
|
+
save_context :rename_from_message
|
|
321
|
+
respond_with :message, text: 'What name do you like?'
|
|
322
|
+
end
|
|
323
|
+
|
|
324
|
+
# register context handlers to handle this context
|
|
325
|
+
def rename_from_message(*words)
|
|
326
|
+
update_name words[0]
|
|
327
|
+
respond_with :message, text: 'Renamed!'
|
|
328
|
+
end
|
|
329
|
+
|
|
330
|
+
# You can use same action name as context name:
|
|
331
|
+
def rename!(name = nil, *)
|
|
332
|
+
if name
|
|
333
|
+
update_name name
|
|
334
|
+
respond_with :message, text: 'Renamed!'
|
|
335
|
+
else
|
|
336
|
+
save_context :rename!
|
|
337
|
+
respond_with :message, text: 'What name do you like?'
|
|
338
|
+
end
|
|
339
|
+
end
|
|
340
|
+
end
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
#### Callback queries
|
|
344
|
+
|
|
345
|
+
You can include `CallbackQueryContext` module to split `#callback_query` into
|
|
346
|
+
several methods. It doesn't require session support, and takes context from
|
|
347
|
+
data: if data has a prefix with colon like this `my_ctx:smth...` it invokes
|
|
348
|
+
`my_ctx_callback_query('smth...')` when such action method is defined. Otherwise
|
|
349
|
+
it invokes `callback_query('my_ctx:smth...')` as usual.
|
|
350
|
+
Callback queries without prefix stay untouched.
|
|
351
|
+
|
|
352
|
+
```ruby
|
|
353
|
+
# This one handles `set_value:%{something}`.
|
|
354
|
+
def set_value_callback_query(new_value = nil, *)
|
|
355
|
+
save_this(value)
|
|
356
|
+
answer_callback_query('Saved!')
|
|
357
|
+
end
|
|
358
|
+
|
|
359
|
+
# And this one is for `make_cool:%{something}`
|
|
360
|
+
def make_cool_callback_query(thing = nil, *)
|
|
361
|
+
do_it(thing)
|
|
362
|
+
answer_callback_query("#{thing} is cool now! Like a callback query context.")
|
|
363
|
+
end
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
### Routes in Rails app
|
|
367
|
+
|
|
368
|
+
There is `telegram_webhook` helper for rails app to define routes for webhooks.
|
|
369
|
+
It defines routes at `telegram/#{bot.token}` and connects bots with controller.
|
|
370
|
+
|
|
371
|
+
```ruby
|
|
372
|
+
# Most off apps would require
|
|
373
|
+
telegram_webhook TelegramController
|
|
374
|
+
# which is same as
|
|
375
|
+
telegram_webhook TelegramController, :default
|
|
138
376
|
|
|
139
377
|
# Use different controllers for each bot:
|
|
140
|
-
|
|
141
|
-
|
|
378
|
+
telegram_webhook TelegramChatController, :chat
|
|
379
|
+
telegram_webhook TelegramAuctionController, :auction
|
|
142
380
|
|
|
143
|
-
#
|
|
144
|
-
#
|
|
145
|
-
#
|
|
146
|
-
# When there are it will use bot's key in the `Telegram.bots` as prefix
|
|
381
|
+
# Defined route is named and its name depends on `Telegram.bots`.
|
|
382
|
+
# For single bot it will use 'telegram_webhook',
|
|
383
|
+
# for multiple bots it uses bot's key in the `Telegram.bots` as prefix
|
|
147
384
|
# (eg. `chat_telegram_webhook`).
|
|
148
|
-
# You can override this
|
|
149
|
-
|
|
150
|
-
telegram_webhooks bot => [TelegramChatController, as: :chat_webhook],
|
|
151
|
-
other_bot => [TelegramAuctionController,
|
|
385
|
+
# You can override this with `as` option:
|
|
386
|
+
telegram_webhook TelegramController, as: :custom_telegram_webhook
|
|
152
387
|
```
|
|
153
388
|
|
|
154
|
-
|
|
155
|
-
|
|
389
|
+
#### Processesing updates
|
|
390
|
+
|
|
391
|
+
To process update with controller call `.dispatch(bot, update)` on it.
|
|
392
|
+
There are several options to run it automatically:
|
|
393
|
+
|
|
394
|
+
- Use webhooks with routes helper (described above).
|
|
395
|
+
- Use `Telegram::Bot::Middleware` with rack ([example in wiki](https://github.com/telegram-bot-rb/telegram-bot/wiki/Not-rails-application)).
|
|
396
|
+
- Use poller (described in the next section).
|
|
397
|
+
|
|
398
|
+
To run action without update (ex., send notifications from jobs),
|
|
399
|
+
you can call `#process` directly. In this case controller can be initialized
|
|
400
|
+
with `:from` and/or `:chat` options instead of `update` object:
|
|
401
|
+
|
|
402
|
+
```ruby
|
|
403
|
+
controller = ControllerClass.new(bot, from: telegram_user, chat: telegram_chat)
|
|
404
|
+
controller.process(:welcome, *args)
|
|
405
|
+
```
|
|
156
406
|
|
|
157
407
|
### Development & Debugging
|
|
158
408
|
|
|
159
|
-
Use `rake telegram:bot:poller
|
|
160
|
-
changes without restart in development env.
|
|
161
|
-
`
|
|
409
|
+
Use `rake telegram:bot:poller` to run poller in rails app. It automatically loads
|
|
410
|
+
changes without restart in development env.
|
|
411
|
+
Optionally pass bot id in `BOT` envvar (`BOT=chat`) to specify bot to run poller for.
|
|
412
|
+
|
|
413
|
+
This task requires `telegram_webhook` helper to be used as it connects bots with controller.
|
|
414
|
+
To run poller in other cases use:
|
|
415
|
+
|
|
416
|
+
```ruby
|
|
417
|
+
Telegram::Bot::UpdatesPoller.start(bot, controller_class)
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
### Testing
|
|
421
|
+
|
|
422
|
+
There is a `Telegram::Bot::ClientStub` class to stub client for tests.
|
|
423
|
+
Instead of performing API requests it stores them in a `requests` hash.
|
|
424
|
+
|
|
425
|
+
To stub all possible clients use `Telegram::Bot::ClientStub.stub_all!` before
|
|
426
|
+
initializing clients. Here is a template for RSpec:
|
|
427
|
+
|
|
428
|
+
```ruby
|
|
429
|
+
# environments/test.rb
|
|
430
|
+
# Make sure to run it before defining routes or accessing any bot in the app!
|
|
431
|
+
Telegram.reset_bots
|
|
432
|
+
Telegram::Bot::ClientStub.stub_all!
|
|
433
|
+
|
|
434
|
+
# rails_helper.rb
|
|
435
|
+
RSpec.configure do |config|
|
|
436
|
+
# ...
|
|
437
|
+
config.after { Telegram.bot.reset }
|
|
438
|
+
# or for multiple bots:
|
|
439
|
+
config.after { Telegram.bots.each_value(&:reset) }
|
|
440
|
+
# ...
|
|
441
|
+
end
|
|
442
|
+
```
|
|
162
443
|
|
|
163
|
-
|
|
164
|
-
`
|
|
444
|
+
RSpec contexts and helpers are included automatically for groups and examples with matching
|
|
445
|
+
tags. In RSpec < 3.4 it's required to use `include_context` explicitly.
|
|
446
|
+
See [list of available helpers](https://github.com/telegram-bot-rb/telegram-bot/tree/master/lib/telegram/bot/rspec)
|
|
447
|
+
for details.
|
|
165
448
|
|
|
166
|
-
|
|
449
|
+
There are 3 types of integration tests:
|
|
167
450
|
|
|
168
|
-
|
|
169
|
-
|
|
451
|
+
- `:rails` - for testing bot in webhooks-mode in Rails application.
|
|
452
|
+
It simulates webhook requests POSTing data to controller's endpoint.
|
|
453
|
+
It works on the top of requests specs, so `rspec-rails` gem is required.
|
|
454
|
+
- `:rack` - For testing bot in webhooks-mode in non-Rails application.
|
|
455
|
+
It uses `rack-test` gem to POST requests to bot's endpoint.
|
|
456
|
+
- `:poller` - Calls `.dispatch` directly on controller class.
|
|
457
|
+
|
|
458
|
+
Pick the appropriate one, then require `telegram/bot/rspec/integration/#{type}`
|
|
459
|
+
and mark spec group with tag `telegram_bot: type`. See configuration options
|
|
460
|
+
for each type in
|
|
461
|
+
[telegram/bot/rspec/integration/](https://github.com/telegram-bot-rb/telegram-bot/tree/master/lib/telegram/bot/rspec/integration).
|
|
462
|
+
|
|
463
|
+
Here is an example test for a Rails app:
|
|
464
|
+
|
|
465
|
+
```ruby
|
|
466
|
+
# spec/requests/telegram_webhooks_spec.rb
|
|
467
|
+
require 'telegram/bot/rspec/integration/rails'
|
|
468
|
+
|
|
469
|
+
RSpec.describe TelegramWebhooksController, telegram_bot: :rails do
|
|
470
|
+
# for old RSpec:
|
|
471
|
+
# include_context 'telegram/bot/integration/rails'
|
|
472
|
+
|
|
473
|
+
# Main method is #dispatch(update). Some helpers are:
|
|
474
|
+
# dispatch_message(text, options = {})
|
|
475
|
+
# dispatch_command(cmd, *args)
|
|
476
|
+
|
|
477
|
+
# Available matchers can be found in Telegram::Bot::RSpec::ClientMatchers.
|
|
478
|
+
it 'shows usage of basic matchers'
|
|
479
|
+
# The most basic one is #make_telegram_request(bot, endpoint, params_matcher)
|
|
480
|
+
expect { dispatch_command(:start) }.
|
|
481
|
+
to make_telegram_request(bot, :sendMessage, hash_including(text: 'msg text'))
|
|
482
|
+
|
|
483
|
+
# There are some shortcuts for dispatching basic updates and testing responses.
|
|
484
|
+
expect { dispatch_message('Hi') }.to send_telegram_message(bot, /msg regexp/, some: :option)
|
|
485
|
+
end
|
|
486
|
+
|
|
487
|
+
describe '#start!' do
|
|
488
|
+
subject { -> { dispatch_command :start } }
|
|
489
|
+
# Using built in matcher for `respond_to`:
|
|
490
|
+
it { should respond_with_message 'Hi there!' }
|
|
491
|
+
end
|
|
492
|
+
|
|
493
|
+
# There is context for callback queries with related matchers,
|
|
494
|
+
# use :callback_query tag to include it.
|
|
495
|
+
describe '#hey_callback_query', :callback_query do
|
|
496
|
+
let(:data) { "hey:#{name}" }
|
|
497
|
+
let(:name) { 'Joe' }
|
|
498
|
+
it { should answer_callback_query('Hey Joe') }
|
|
499
|
+
it { should edit_current_message :text, text: 'Done' }
|
|
500
|
+
end
|
|
501
|
+
end
|
|
502
|
+
```
|
|
503
|
+
|
|
504
|
+
There is a context for testing bot controller in the way similar to Rails controller tests.
|
|
505
|
+
It's supposed to be a low-level alternative for integration tests. Among the differences is
|
|
506
|
+
that controller tests use a single controller instance for all dispatches in specific exaple,
|
|
507
|
+
session is stubbed (does not use configured store engine), and update is not serialized
|
|
508
|
+
so it also supports mocks. This can be useful for unit testing, but should not be used as
|
|
509
|
+
the default way to test the bot.
|
|
510
|
+
|
|
511
|
+
```ruby
|
|
512
|
+
require 'telegram/bot/updates_controller/rspec_helpers'
|
|
513
|
+
RSpec.describe TelegramWebhooksController, type: :telegram_bot_controller do
|
|
514
|
+
# for old RSpec:
|
|
515
|
+
# include_context 'telegram/bot/updates_controller'
|
|
516
|
+
|
|
517
|
+
# Same helpers and matchers like dispatch_command, answer_callback_query are available here.
|
|
518
|
+
end
|
|
519
|
+
```
|
|
520
|
+
|
|
521
|
+
See sample app for more examples.
|
|
522
|
+
|
|
523
|
+
### Deployment
|
|
524
|
+
|
|
525
|
+
While webhooks-mode is prefered, poller still can be used in production.
|
|
526
|
+
See [comparison and examples](https://github.com/telegram-bot-rb/telegram-bot/wiki/Deployment)
|
|
527
|
+
for details.
|
|
528
|
+
|
|
529
|
+
### Async mode
|
|
530
|
+
|
|
531
|
+
There is built in support for async requests using ActiveJob. Without Rails
|
|
532
|
+
you can implement your own worker class to handle such requests. This allows:
|
|
533
|
+
|
|
534
|
+
- Process updates very fast, without waiting for telegram responses.
|
|
535
|
+
- Handle and retry network and other errors with queue adapter.
|
|
536
|
+
- ???
|
|
537
|
+
|
|
538
|
+
Instead of performing request instantly client serializes it, pushes to queue,
|
|
539
|
+
and immediately return control back. The job is then fetched with a worker
|
|
540
|
+
and real API request is performed. And this all is absolutely transparent for the app.
|
|
541
|
+
|
|
542
|
+
To enable this mode add `async: true` to bot's config.
|
|
543
|
+
For more information and custom configuration check out
|
|
544
|
+
[docs](http://www.rubydoc.info/github/telegram-bot-rb/telegram-bot/master/Telegram/Bot/Async) or
|
|
545
|
+
[source](https://github.com/telegram-bot-rb/telegram-bot/blob/master/lib/telegram/bot/async.rb).
|
|
546
|
+
|
|
547
|
+
If you want async mode, but don't want to setup queue, know that Rails 5 are shipped
|
|
548
|
+
with Async adapter by default, and there is
|
|
549
|
+
[Sucker Punch](https://github.com/brandonhilkert/sucker_punch) for Rails 4.
|
|
550
|
+
|
|
551
|
+
To disable async mode for the block of code use `bot.async(false) { bot.send_photo }`.
|
|
552
|
+
Yes, it's threadsafe too.
|
|
553
|
+
|
|
554
|
+
#### Limitations
|
|
555
|
+
|
|
556
|
+
- Client will not return API response.
|
|
557
|
+
- Sending files is not available in async mode, because they can not be serialized.
|
|
170
558
|
|
|
171
559
|
## Development
|
|
172
560
|
|
|
173
|
-
After checking out the repo, run `bin/setup` to install dependencies.
|
|
174
|
-
Then, run `rake spec` to run the tests.
|
|
561
|
+
After checking out the repo, run `bin/setup` to install dependencies and git hooks.
|
|
562
|
+
Then, run `appraisal rake spec` to run the tests.
|
|
175
563
|
You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
|
176
564
|
|
|
177
565
|
To install this gem onto your local machine, run `bundle exec rake install`.
|
|
@@ -179,6 +567,8 @@ To release a new version, update the version number in `version.rb`,
|
|
|
179
567
|
and then run `bundle exec rake release`, which will create a git tag for the version,
|
|
180
568
|
push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
|
181
569
|
|
|
570
|
+
Use `bin/fetch-telegram-methods` to update API methods list from Telegram website.
|
|
571
|
+
|
|
182
572
|
## Contributing
|
|
183
573
|
|
|
184
|
-
Bug reports and pull requests are welcome on GitHub at https://github.com/
|
|
574
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/telegram-bot-rb/telegram-bot.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
#!/usr/bin/env ruby
|
|
2
|
+
#
|
|
3
|
+
# Fetch list of methods from Telegram docs.
|
|
4
|
+
# Use it to update client.rb.
|
|
5
|
+
|
|
6
|
+
require 'net/http'
|
|
7
|
+
require 'nokogiri'
|
|
8
|
+
|
|
9
|
+
DOCS_URL = 'https://core.telegram.org/bots/api'.freeze
|
|
10
|
+
|
|
11
|
+
page_html = Net::HTTP.get(URI(DOCS_URL))
|
|
12
|
+
doc = Nokogiri::HTML(page_html)
|
|
13
|
+
|
|
14
|
+
# Select `h4`s, but use `h3`s to group them.
|
|
15
|
+
headers = doc.css('h3, h4').
|
|
16
|
+
chunk_while { |_, x| x.name == 'h4' }.
|
|
17
|
+
map { |g| g.select { |x| x.name == 'h4' } }.
|
|
18
|
+
map { |g| g.map(&:text) }
|
|
19
|
+
|
|
20
|
+
# Method starts with lowercase and does not have spaces.
|
|
21
|
+
NOT_METHOD_REGEXP = /(\A[^a-z])|\s/
|
|
22
|
+
|
|
23
|
+
# Filter method names.
|
|
24
|
+
method_list = headers.
|
|
25
|
+
map { |g| g.reject { |x| x.match?(NOT_METHOD_REGEXP) } }.
|
|
26
|
+
reject(&:empty?)
|
|
27
|
+
|
|
28
|
+
api_version = doc.text.match(/^(Bot API ([\d\.]+))\.?$/)
|
|
29
|
+
|
|
30
|
+
result = ['# Generated with bin/fetch-telegram-methods']
|
|
31
|
+
result << "# #{api_version[1]}" if api_version
|
|
32
|
+
result << ''
|
|
33
|
+
result << method_list.map { |g| g.join("\n") }.join("\n\n")
|
|
34
|
+
result << ''
|
|
35
|
+
result_txt = result.join("\n")
|
|
36
|
+
|
|
37
|
+
puts result_txt
|
|
38
|
+
|
|
39
|
+
API_METHODS_FILE = File.expand_path('../lib/telegram/bot/client/api_methods.txt', __dir__).freeze
|
|
40
|
+
File.write(API_METHODS_FILE, result_txt)
|
|
41
|
+
puts '', "Updated #{API_METHODS_FILE}"
|