Class: Telegrammer::Bot

Inherits:
Object
  • Object
show all
Defined in:
lib/telegrammer/bot.rb

Overview

Wrapper for the Telegram’s Bots API

Constant Summary collapse

API_ENDPOINT =
'https://api.telegram.org'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_token) ⇒ Bot

Returns a new instance of Telegrammer::Bot

Examples:

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')

Parameters:

  • api_token (String)

    API Token

Raises:



17
18
19
20
21
22
23
24
25
# File 'lib/telegrammer/bot.rb', line 17

def initialize(api_token)
  @api_token = api_token
  @offset = 0
  @timeout = 60
  @fail_silently = false
  @connection = HTTPClient.new

  @me = get_me
end

Instance Attribute Details

#meObject (readonly)

Returns the value of attribute me.



6
7
8
# File 'lib/telegrammer/bot.rb', line 6

def me
  @me
end

Instance Method Details

#forward_message(params) ⇒ Telegrammer::DataTypes::Message

Forward message to a user or group chat.

Examples:

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')

bot.forward_message(
  chat_id: 123456789,
  from_chat_id: 987654321
  message_id: 111222333
)

Parameters:

  • params (Hash)

    hash of paramers to send to the forwardMessage API operation.

Options Hash (params):

  • :chat_id (Integer, String)

    Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • :from_chat_id (Integer, String)

    Required. Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername).

  • :message_id (Integer)

    Required. Message id to be forwarded.

Returns:

Raises:



162
163
164
165
166
167
168
169
170
171
172
# File 'lib/telegrammer/bot.rb', line 162

def forward_message(params)
  params_validation = {
    chat_id: { required: true, class: [Fixnum] },
    from_chat_id: { required: true, class: [String] },
    message_id: { required: true, class: [Fixnum] }
  }

  response = api_request('forwardMessage', params, params_validation)

  Telegrammer::DataTypes::Message.new(response.result)
end

#get_file(params) ⇒ String

Get basic info about a file and prepare it for downloading.

Examples:

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
bot.get_file(file_id: 123456789)

Parameters:

  • params (Hash)

    hash of paramers to send to the getFile API operation.

Options Hash (params):

  • :file_id (String)

    Required. File identifier to get info about.

Returns:

  • (String)

    URL of the file (valid for one hour) or BadRequestError if the file_id is wrong

Raises:



441
442
443
444
445
446
447
448
449
450
# File 'lib/telegrammer/bot.rb', line 441

def get_file(params)
  params_validation = {
    file_id: { required: true, class: [String] }
  }

  response = response = api_request("getFile", params, params_validation)
  file_object = Telegrammer::DataTypes::File.new(response.result)

  "#{API_ENDPOINT}/file/bot#{@api_token}/#{file_object.file_path}"
end

#get_meTelegrammer::DataTypes::User

Returns basic information about the bot in form of a User object. Used for testing your bot’s auth token.

Examples:

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
bot_user = bot.get_me

Returns:

Raises:



104
105
106
107
108
# File 'lib/telegrammer/bot.rb', line 104

def get_me
  response = api_request('getMe', nil, nil)

  Telegrammer::DataTypes::User.new(response.result)
end

#get_updates(opts = {}, &_block) ⇒ Object

Get incoming updates using long polling

Examples:

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')

bot.get_updates do |message|
  puts "In chat #{message.chat.id}, @#{message.from.username} said: #{message.text}"
  bot.send_message(chat_id: message.chat.id, text: "You said: #{message.text}")

  # Here you can also process message text to detect user commands
  # To learn more about commands, see https://core.telegram.org/bots#commands
end

bot.get_updates({fail_silently:true, timeout:20}) do |message|
  puts "In chat #{message.chat.id}, @#{message.from.username} said: #{message.text}"
  bot.send_message(chat_id: message.chat.id, text: "You said: #{message.text}")

  # Here you can also process message text to detect user commands
  # To learn more about commands, see https://core.telegram.org/bots#commands
end

Parameters:

  • opts (Hash) (defaults to: {})

    Options when getting updates

  • params (Hash)

    a customizable set of options

Raises:



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/telegrammer/bot.rb', line 56

def get_updates(opts={}, &_block)
  loop do
    if opts[:fail_silently]
      @fail_silently = true
    end

    response = api_request('getUpdates', { offset: opts[:offset] || @offset, timeout: opts[:timeout] || @timeout }, nil)

    response.result.each do |raw_update|
      update = Telegrammer::DataTypes::Update.new(raw_update)
      @offset = update.update_id + 1
      yield update.message
    end
  end
end

#get_user_profile_photos(params) ⇒ Telegrammer::DataTypes::UserProfilePhotos

Get a list of profile pictures for a user.

Examples:

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
bot.(user_id: 123456789)

Parameters:

  • params (Hash)

    hash of paramers to send to the getUserProfilePhotos API operation.

Options Hash (params):

  • :user_id (Integer)

    Required. Unique identifier of the target user.

  • :offset (Integer)

    Optional. Sequential number of the first photo to be returned. By default, all photos are returned.

  • :limit (Integer)

    Optional. Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100.

Returns:

Raises:



416
417
418
419
420
421
422
423
424
425
426
# File 'lib/telegrammer/bot.rb', line 416

def (params)
  params_validation = {
    user_id: { required: true, class: [Fixnum] },
    offset: { required: false, class: [Fixnum] },
    limit: { required: false, class: [Fixnum] }
  }

  response = api_request('getUserProfilePhotos', params, params_validation)

  Telegrammer::DataTypes::UserProfilePhotos.new(response.result).to_h
end

#send_audio(params) ⇒ Telegrammer::DataTypes::Message

Sends audio file to a user or group chat.

At this moment, Telegram only allows Ogg files encoded with the OPUS codec. If you need to send another file format, you must use #send_document.

Examples:

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
audio_file = File.open("foo.ogg")
bot.send_audio(chat_id: 123456789, audio: audio_file)

Parameters:

  • params (Hash)

    hash of paramers to send to the sendAudio API operation.

Options Hash (params):

  • :chat_id (Integer, String)

    Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • audio (File, String)

    Required. Audio file to send. You can either pass a file_id as String to resend an audio that is already on the Telegram servers, or upload a new audio file using multipart/form-data

  • duration (Integer)

    Optional. Duration of the audio in seconds.

  • performer (String)

    Optional. Performer.

  • title (String)

    Optional. Track name.

  • :reply_to_message_id (Integer)

    Optional. If the message is a reply, ID of the original message

  • :reply_markup (Telegrammer::DataTypes::ReplyKeyboardMarkup, Telegrammer::DataTypes::ReplyKeyboardHide, Telegrammer::DataTypes::ForceReply)

    Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.

Returns:

Raises:

See Also:



225
226
227
228
229
230
231
232
233
234
# File 'lib/telegrammer/bot.rb', line 225

def send_audio(params)
  extra_params_validation = {
    audio: { required: true, class: [File, String] },
    duration: { required: false, class: [Integer] },
    performer: { required: false, class: [String] },
    title: { required: false, class: [String] }
  }

  send_something(:audio, params, extra_params_validation)
end

#send_chat_action(params) ⇒ Telegrammer::ApiResponse

Sends a status action to a user or group chat.

Used when you need to tell the user that something is happening on the bot’s side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status).

Examples:

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
bot.send_chat_action(chat_id: 123456789, action: "typing")

Parameters:

  • params (Hash)

    hash of paramers to send to the sendChatAction API operation.

Options Hash (params):

  • :chat_id (Integer, String)

    Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • :action (String)

    Required. Type of action to broadcast. Choose one, depending on what the user is about to receive: “typing” for text messages, “upload_photo” for photos, “record_video” or “upload_video” for videos, “record_audio” or “upload_audio” for audio files, “upload_document” for general files, “find_location” for location data.

Returns:

Raises:



392
393
394
395
396
397
398
399
# File 'lib/telegrammer/bot.rb', line 392

def send_chat_action(params)
  params_validation = {
    chat_id: { required: true, class: [Fixnum, String] },
    action: { required: true, class: [String] }
  }

  api_request('sendChatAction', params, params_validation)
end

#send_document(params) ⇒ Telegrammer::DataTypes::Message

Sends a document to a user or group chat.

Examples:

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
my_secret_file = File.open("secrets.doc")
bot.send_document(chat_id: 123456789, document: my_secret_file)

Parameters:

  • params (Hash)

    hash of paramers to send to the sendDocument API operation.

Options Hash (params):

  • :chat_id (Integer, String)

    Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • :document (File, String)

    Required. File to send. You can either pass a file_id as String to resend a file that is already on the Telegram servers, or upload a new file using multipart/form-data.

  • :reply_to_message_id (Integer)

    Optional. If the message is a reply, ID of the original message

  • :reply_markup (Telegrammer::DataTypes::ReplyKeyboardMarkup, Telegrammer::DataTypes::ReplyKeyboardHide, Telegrammer::DataTypes::ForceReply)

    Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.

Returns:

Raises:



284
285
286
287
288
289
290
# File 'lib/telegrammer/bot.rb', line 284

def send_document(params)
  extra_params_validation = {
    document: { required: true, class: [File, String] }
  }

  send_something(:document, params, extra_params_validation)
end

#send_location(params) ⇒ Telegrammer::DataTypes::Message

Sends point on the map to a user or group chat.

Examples:

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
bot.send_location(chat_id: 123456789, latitude: 38.775539, longitude: -4.829988)

Parameters:

  • params (Hash)

    hash of paramers to send to the sendAudio API operation.

Options Hash (params):

  • :chat_id (Integer, String)

    Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • :latitude (Float)

    Required. Latitude of location.

  • :longitude (Float)

    Required. Longitude of location.

  • :reply_to_message_id (Integer)

    Optional. If the message is a reply, ID of the original message.

  • :reply_markup (Telegrammer::DataTypes::ReplyKeyboardMarkup, Telegrammer::DataTypes::ReplyKeyboardHide, Telegrammer::DataTypes::ForceReply)

    Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.

Returns:

Raises:



367
368
369
370
371
372
373
374
# File 'lib/telegrammer/bot.rb', line 367

def send_location(params)
  extra_params_validation = {
    latitude: { required: true, class: [Float] },
    longitude: { required: true, class: [Float] }
  }

  send_something(:location, params, extra_params_validation)
end

#send_message(params) ⇒ Telegrammer::DataTypes::Message

Send text messages to a user or group chat.

Examples:

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')

bot.send_message(
  chat_id: 123456789,
  text: "Hello World!"
)

Parameters:

  • params (Hash)

    hash of paramers to send to the sendMessage API operation.

Options Hash (params):

  • :chat_id (Integer, String)

    Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • :text (String)

    Required. Text of the message to be sent

  • :parse_mode (String)

    Optional. Send Markdown, if you want Telegram apps to show bold, italic and inline URLs in your bot’s message.

  • :disable_web_page_preview (Boolean)

    Optional. Disables link previews for links in this message

  • :reply_to_message_id (Integer)

    Optional. If the message is a reply, ID of the original message

  • :reply_markup (Telegrammer::DataTypes::ReplyKeyboardMarkup, Telegrammer::DataTypes::ReplyKeyboardHide, Telegrammer::DataTypes::ForceReply)

    Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.

Returns:

Raises:



132
133
134
135
136
137
138
139
140
# File 'lib/telegrammer/bot.rb', line 132

def send_message(params)
  extra_params_validation = {
    text: { required: true, class: [String] },
    parse_mode: { required: false, class: [String] },
    disable_web_page_preview: { required: false, class: [TrueClass, FalseClass] }
  }

  send_something(:message, params, extra_params_validation)
end

#send_photo(params) ⇒ Telegrammer::DataTypes::Message

Sends a photo to a user or group chat.

Examples:

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
image_file = File.open("foo.jpg")
bot.send_photo(chat_id: 123456789, photo: image_file)

Parameters:

  • params (Hash)

    hash of paramers to send to the sendPhoto API operation.

Options Hash (params):

  • :chat_id (Integer, String)

    Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • :photo (File, String)

    Required. Photo to send. You can either pass a file_id as String to resend a photo that is already on the Telegram servers, or upload a new photo using multipart/form-data.

  • :caption (String)

    Optional. Photo caption (may also be used when resending photos by file_id).

  • :reply_to_message_id (Integer)

    Optional. If the message is a reply, ID of the original message

  • :reply_markup (Telegrammer::DataTypes::ReplyKeyboardMarkup, Telegrammer::DataTypes::ReplyKeyboardHide, Telegrammer::DataTypes::ForceReply)

    Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.

Returns:

Raises:

See Also:



193
194
195
196
197
198
199
200
# File 'lib/telegrammer/bot.rb', line 193

def send_photo(params)
  extra_params_validation = {
    photo: { required: true, class: [File, String] },
    caption: { required: false, class: [String] }
  }

  send_something(:photo, params, extra_params_validation)
end

#send_sticker(params) ⇒ Telegrammer::DataTypes::Message

Send WebP images as stickers.

Examples:

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
sticker_file = File.open("my-sticker.webp")
bot.send_sticker(chat_id: 123456789, sticker: sticker_file)

Parameters:

  • params (Hash)

    hash of paramers to send to the sendSticker API operation.

Options Hash (params):

  • :chat_id (Integer, String)

    Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • :sticker (File, String)

    Required. Sticker to send. You can either pass a file_id as String to resend a file that is already on the Telegram servers, or upload a new file using multipart/form-data.

  • :reply_to_message_id (Integer)

    Optional. If the message is a reply, ID of the original message

  • :reply_markup (Telegrammer::DataTypes::ReplyKeyboardMarkup, Telegrammer::DataTypes::ReplyKeyboardHide, Telegrammer::DataTypes::ForceReply)

    Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.

Returns:

Raises:

See Also:



310
311
312
313
314
315
316
# File 'lib/telegrammer/bot.rb', line 310

def send_sticker(params)
  extra_params_validation = {
    sticker: { required: true, class: [File, String] }
  }

  send_something(:sticker, params, extra_params_validation)
end

#send_video(params) ⇒ Telegrammer::DataTypes::Message

Sends a video file to a user or group chat.

At this moment, Telegram only support mp4 videos. If you need to send other formats you must use #send_document.

Examples:

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
my_video = File.open("foo.mp4")
bot.send_video(chat_id: 123456789, video: my_video)

Parameters:

  • params (Hash)

    hash of paramers to send to the sendVideo API operation.

Options Hash (params):

  • :chat_id (Integer, String)

    Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • :video (File, String)

    Required. Video to send. You can either pass a file_id as String to resend a video that is already on the Telegram servers, or upload a new video file.

  • :duration (Integer)

    Optional. Duration of sent video in seconds.

  • :caption (String)

    Optional. Video caption (may also be used when resending videos by file_id).

  • :reply_to_message_id (Integer)

    Optional. If the message is a reply, ID of the original message

  • :reply_markup (Telegrammer::DataTypes::ReplyKeyboardMarkup, Telegrammer::DataTypes::ReplyKeyboardHide, Telegrammer::DataTypes::ForceReply)

    Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.

Returns:

Raises:

See Also:



340
341
342
343
344
345
346
347
348
# File 'lib/telegrammer/bot.rb', line 340

def send_video(params)
  extra_params_validation = {
    video: { required: true, class: [File, String] },
    duration: { required: false, class: [Integer] },
    caption: { required: false, class: [String] }
  }

  send_something(:video, params, extra_params_validation)
end

#send_voice(params) ⇒ Telegrammer::DataTypes::Message

Sends audio files file to a user or group chat that the users will see as a playable voice message.

At this moment, Telegram only allows Ogg files encoded with the OPUS codec. If you need to send another file format, you must use #send_document.

Examples:

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')
voice_file = File.open("foo.ogg")
bot.send_voice(chat_id: 123456789, voice: audio_file)

Parameters:

  • params (Hash)

    hash of paramers to send to the sendAudio API operation.

Options Hash (params):

  • :chat_id (Integer, String)

    Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername).

  • voice (File, String)

    Required. Audio file to send. You can either pass a file_id as String to resend an audio that is already on the Telegram servers, or upload a new audio file using multipart/form-data

  • duration (Integer)

    Optional. Duration of sent audio in seconds.

  • :reply_to_message_id (Integer)

    Optional. If the message is a reply, ID of the original message

  • :reply_markup (Telegrammer::DataTypes::ReplyKeyboardMarkup, Telegrammer::DataTypes::ReplyKeyboardHide, Telegrammer::DataTypes::ForceReply)

    Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.

Returns:

Raises:

See Also:



257
258
259
260
261
262
263
264
# File 'lib/telegrammer/bot.rb', line 257

def send_voice(params)
  extra_params_validation = {
    voice: { required: true, class: [File, String] },
    duration: { required: false, class: [Integer] }
  }

  send_something(:audio, params, extra_params_validation)
end

#set_webhook(url) ⇒ Telegrammer::ApiResponse

Set a webhook where Telegram will send the messages received by your bot.

Examples:

bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]')

# Set up a webhook
bot.set_webhook("http://www.example.com/my/action")

# Delete a webhook
bot.set_webhook("")

Parameters:

  • url (String)

Returns:

Raises:

See Also:



90
91
92
# File 'lib/telegrammer/bot.rb', line 90

def set_webhook(url)
  api_request('setWebhook', { url: url }, nil)
end