Ruby gem for building Telegram Bot with optional Rails integration
Ruby gem for building Telegram Bot with optional Rails integration
Tools for developing Telegram bots. Best used with Rails, but can be used in standalone app. Supposed to be used in webhook-mode in production, and poller-mode in development, but you can use poller in production if you want.
Package contains:
case branches.Here is sample telegram_bot_app with session, keyboards and inline queries. Run it on your local machine in 1 minute!
And here is app template to generate new rails app in seconds.
See examples and cookbook in the wiki.
Add this line to your application's Gemfile:
gem 'telegram-bot'And then execute:
bundleOr install it yourself as:
gem install telegram-botRequire if necessary:
require 'telegram/bot'While clients can be instantiated explicitly, there is Telegram.bots_config= method
to configure app-wide clients, which are accessible via Telegram.bots.
It accepts hash of {bot_id: bot_config}, and there is special id :default
which is used for Telegram.bot.
Telegram.bots_config = {
default: DEFAULT_BOT_TOKEN,
chat: {
token: CHAT_BOT_TOKEN,
username: 'ChatBot', # to support commands with mentions (/help@ChatBot)
server: 'http://local.bot.api.server', # for Local Bot API Server
},
}
Telegram.bot.get_updates
Telegram.bot == Telegram.bots[:default] # true
Telegram.bots[:chat].send_message(...)In Rails app Telegram.bots_config is read from secrets.yml automatically
from telegram section:
development:
telegram:
# Single bot can be specified like this
bot: TOKEN
# or
bot:
token: TOKEN
username: SomeBot
server: http://local.bot.api.server
# For multiple bots in single app use hash of `internal_bot_id => settings`
bots:
# just set the bot token
chat: TOKEN_1
# or add username to support commands with mentions (/help@ChatBot)
auction:
token: TOKEN_2
username: ChatBotFor Rails >= 5.2 Telegram::Bot searches for config first in credentials and then in secrets.
To use credentials as config store, add telegram section to credentials instead of secrets using
rails credentials:edit. In this case be aware of that [Rails = 6.0 run rails credentials:edit --environment development to configure bot
in each environment.
I suggest not using Rails 5.2 credentials because it can lead to leakage of sensitive data and it's more difficult to use in multiple environments. See secure_credentials gem for better option.
From now clients will be accessible with Telegram.bots[:chat] or Telegram.bots[:auction].
Single bot can be accessed with Telegram.bot or Telegram.bots[:default].
Client is instantiated with Telegram::Bot::Client.new(token, username).
Username is optional and used only to parse commands with mentions.
There is request(path_suffix, body) method to perform any query.
And there are shortcuts for all available requests in underscored style
(answer_inline_query(params) instead of answerInlineQuery).
bot.request(:getMe) or bot.get_me
bot.request(:getupdates, offset: 1) or bot.get_updates(offset: 1)
bot.send_message(chat_id: chat_id, text: 'Test')There is no magic, they just pass params as is and set path_suffix.
See list of available methods
fetched from API docs.
Please open PR or issue if it misses methods from new API versions.
Any API request error will raise Telegram::Bot::Error with description in its message.
Special Telegram::Bot::Forbidden is raised when bot can't post messages to the chat anymore.
By default client will return parsed json responses. You can enable
response typecasting to virtus models using
telegram-bot-types gem:
# Add to your gemfile:
gem 'telegram-bot-types', '~> x.x.x'
# Enable typecasting:
Telegram::Bot::Client.typed_response!
# or for single instance:
bot.extend Telegram::Bot::Client::TypedResponse
bot.get_me.class # => Telegram::Bot::Types::UserController makes it easy to keep bot's code readable.
It does nothing more than finding out action name for update and invoking it.
So there is almost no overhead comparing to large switch, while you
can represent actions as separate methods keeping source much more readable and supportable.
New instance of controller is instantiated for each update. This way every update is processed in isolation from others.
Bot controllers like usual rails controllers provides features like callbacks,
rescue_from and instrumentation.
class Telegram::WebhookController Telegram::Bot::Types::Message
end
endThis API is very close to ActiveController's session API, but works different
under the hood. Cookies can not be used to store session id or
whole session (like CookieStore does). So it uses key-value store and session_key
method to build identifier from update.
Store can be one of numerous ActiveSupport::Cache stores.
While :file_store is suitable for development and single-server deployments
without heavy load, it doesn't scale well. Key-value databases with persistance
like Redis are more appropriate for production use.
# In rails app store can be configured in env files:
config.telegram_updates_controller.session_store = :redis_store, {expires_in: 1.month}
# In other app it can be done for all controllers with:
Telegram::Bot::UpdatesController.session_store = :redis_store, {expires_in: 1.month}
# or for specific one:
OneOfUpdatesController.session_store = :redis_store, {expires_in: 1.month}Default session id is made from bot's username and (from || chat)['id'].
It means that session will be the same for updates from user in every chat,
and different for every user in the same group chat.
To change this behavior you can override session_key method, or even
define multiple sessions
in single controller. For details see Session module.
class Telegram::WebhookController { dispatch_command :start } }
# Using built in matcher for `respond_to`:
it { should respond_with_message 'Hi there!' }
end
# There is context for callback queries with related matchers,
# use :callback_query tag to include it.
describe '#hey_callback_query', :callback_query do
let(:data) { "hey:#{name}" }
let(:name) { 'Joe' }
it { should answer_callback_query('Hey Joe') }
it { should edit_current_message :text, text: 'Done' }
end
endThere is a context for testing bot controller in the way similar to Rails controller tests. It's supposed to be a low-level alternative for integration tests. Among the differences is that controller tests use a single controller instance for all dispatches in specific example, session is stubbed (does not use configured store engine), and update is not serialized so it also supports mocks. This can be useful for unit testing, but should not be used as the default way to test the bot.
require 'telegram/bot/updates_controller/rspec_helpers'
RSpec.describe TelegramWebhooksController, type: :telegram_bot_controller do
# for old RSpec:
# include_context 'telegram/bot/updates_controller'
# Same helpers and matchers like dispatch_command, answer_callback_query are available here.
endSee sample app for more examples.
While webhooks-mode is prefered, poller still can be used in production. See comparison and examples for details.
There is built in support for async requests using ActiveJob. Without Rails you can implement your own worker class to handle such requests. This allows:
Instead of performing request instantly client serializes it, pushes to queue, and immediately return control back. The job is then fetched with a worker and real API request is performed. And this all is absolutely transparent for the app.
To enable this mode add async: true to bot's config.
For more information and custom configuration check out
docs or
source.
If you want async mode, but don't want to setup queue, know that Rails 5 are shipped with Async adapter by default, and there is Sucker Punch for Rails 4.
To disable async mode for the block of code use bot.async(false) { bot.send_photo }.
Yes, it's threadsafe too.
After checking out the repo, run bin/setup to install dependencies and git hooks.
Then, run appraisal rake spec to run the tests.
You can also run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install.
To release a new version, update the version number in version.rb,
and then run bundle exec rake release, which will create a git tag for the version,
push git commits and tags, and push the .gem file to rubygems.org.
Use bin/fetch-telegram-methods to update API methods list from Telegram website.
Bug reports and pull requests are welcome on GitHub at https://github.com/telegram-bot-rb/telegram-bot.
No open issues yet, or sync has not completed.