gruubY 0.2.1 → 0.2.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.
Files changed (57) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +21 -21
  3. data/README.md +11 -6
  4. data/Rakefile +51 -51
  5. data/config/config.rb +1 -1
  6. data/example/bot.rb +122 -2
  7. data/example/generate_user_session.rb +81 -81
  8. data/example/tdlib.rb +77 -77
  9. data/example/userbot.rb +133 -133
  10. data/lib/gruubY/api.rb +540 -363
  11. data/lib/gruubY/async.rb +13 -13
  12. data/lib/gruubY/bot.rb +104 -90
  13. data/lib/gruubY/bound.rb +14 -14
  14. data/lib/gruubY/client.rb +310 -296
  15. data/lib/gruubY/context.rb +296 -242
  16. data/lib/gruubY/dispatcher.rb +60 -60
  17. data/lib/gruubY/enums.rb +57 -62
  18. data/lib/gruubY/exception.rb +5 -5
  19. data/lib/gruubY/file_stream.rb +17 -17
  20. data/lib/gruubY/filters.rb +292 -292
  21. data/lib/gruubY/group_manager.rb +213 -213
  22. data/lib/gruubY/handlers.rb +225 -170
  23. data/lib/gruubY/keyboard.rb +49 -49
  24. data/lib/gruubY/media.rb +38 -38
  25. data/lib/gruubY/middleware.rb +18 -18
  26. data/lib/gruubY/plugin.rb +27 -14
  27. data/lib/gruubY/raw.rb +25 -25
  28. data/lib/gruubY/retry.rb +14 -14
  29. data/lib/gruubY/server.rb +18 -18
  30. data/lib/gruubY/session.rb +30 -30
  31. data/lib/gruubY/tdlib/client.rb +565 -565
  32. data/lib/gruubY/tdlib/client_manager.rb +37 -37
  33. data/lib/gruubY/tdlib/decorators.rb +17 -17
  34. data/lib/gruubY/tdlib/errors.rb +6 -6
  35. data/lib/gruubY/tdlib/group_manager.rb +58 -58
  36. data/lib/gruubY/tdlib/native.rb +72 -72
  37. data/lib/gruubY/tdlib/schema_builder.rb +237 -237
  38. data/lib/gruubY/tdlib/tdjson.rb +49 -49
  39. data/lib/gruubY/tdlib/user_session.rb +69 -69
  40. data/lib/gruubY/types/base_object.rb +72 -72
  41. data/lib/gruubY/types/bound_entities.rb +289 -245
  42. data/lib/gruubY/types/chat.rb +93 -93
  43. data/lib/gruubY/types/chat_info.rb +32 -31
  44. data/lib/gruubY/types/extra.rb +289 -251
  45. data/lib/gruubY/types/message.rb +301 -295
  46. data/lib/gruubY/types/message_entity.rb +14 -14
  47. data/lib/gruubY/types/registry.rb +86 -67
  48. data/lib/gruubY/types/user.rb +47 -31
  49. data/lib/gruubY/webapp.rb +22 -22
  50. data/lib/gruubY.rb +39 -41
  51. data/plugins/logger.rb +7 -7
  52. metadata +3 -9
  53. data/example/ntgcalls.rb +0 -80
  54. data/lib/gruubY/ntgcalls/native.rb +0 -100
  55. data/lib/gruubY/ntgcalls.rb +0 -478
  56. data/lib/gruubY/raw_types.rb +0 -57
  57. data/plugins/media_tools.rb +0 -13
data/lib/gruubY/api.rb CHANGED
@@ -1,363 +1,540 @@
1
- require "json"
2
- require "net/http"
3
- require "uri"
4
- require_relative "retry"
5
-
6
- module GrubY
7
- class API
8
- class Error < StandardError; end
9
- METHOD_ALIASES = {
10
- "set_bot_commands" => "setMyCommands",
11
- "get_bot_commands" => "getMyCommands",
12
- "delete_bot_commands" => "deleteMyCommands",
13
- "set_bot_name" => "setMyName",
14
- "get_bot_name" => "getMyName",
15
- "set_bot_info_description" => "setMyDescription",
16
- "get_bot_info_description" => "getMyDescription",
17
- "set_bot_info_short_description" => "setMyShortDescription",
18
- "get_bot_info_short_description" => "getMyShortDescription",
19
- "set_bot_default_privileges" => "setMyDefaultAdministratorRights",
20
- "get_bot_default_privileges" => "getMyDefaultAdministratorRights",
21
- "get_chat_members_count" => "getChatMemberCount",
22
- "get_chat_photos" => "getUserProfilePhotos",
23
- "get_chat_audios" => "getUserProfileAudios",
24
- "set_emoji_status" => "setUserEmojiStatus",
25
- "get_managed_bot_token" => "getManagedBotToken",
26
- "replace_managed_bot_token" => "replaceManagedBotToken",
27
- "ban_chat_member" => "banChatMember",
28
- "unban_chat_member" => "unbanChatMember",
29
- "restrict_chat_member" => "restrictChatMember",
30
- "promote_chat_member" => "promoteChatMember",
31
- "set_administrator_title" => "setChatAdministratorCustomTitle",
32
- "set_chat_member_tag" => "setChatMemberTag",
33
- "set_chat_menu_button" => "setChatMenuButton",
34
- "get_chat_menu_button" => "getChatMenuButton",
35
- "send_reaction" => "setMessageReaction",
36
- "set_message_reaction" => "setMessageReaction",
37
- "export_chat_invite_link" => "exportChatInviteLink",
38
- "create_chat_invite_link" => "createChatInviteLink",
39
- "edit_chat_invite_link" => "editChatInviteLink",
40
- "revoke_chat_invite_link" => "revokeChatInviteLink",
41
- "approve_chat_join_request" => "approveChatJoinRequest",
42
- "decline_chat_join_request" => "declineChatJoinRequest",
43
- "send_message_draft" => "sendMessageDraft",
44
- "send_paid_reaction" => "sendPaidReaction",
45
- "get_user_chat_boosts" => "getUserChatBoosts",
46
- "get_business_connection" => "getBusinessConnection",
47
- "forward_media_group" => "forwardMessages",
48
- "copy_media_group" => "copyMessages"
49
- }.freeze
50
-
51
- def initialize(token)
52
- @token = token
53
- @base = URI("https://api.telegram.org/bot#{token}/")
54
- end
55
-
56
- def request(method, params = {})
57
- payload = raw(method, params)
58
- payload["result"]
59
- end
60
-
61
- def raw(method, params = {})
62
- uri = @base + method.to_s
63
- response = Retry.call { Net::HTTP.post_form(uri, serialize_params(params)) }
64
- parse_response(response)
65
- end
66
-
67
- def get_updates(offset = nil, timeout: 30, **opts)
68
- params = { timeout: timeout }.merge(opts)
69
- params[:offset] = offset if offset
70
- request("getUpdates", params)
71
- end
72
-
73
- def get_file(file_id)
74
- request("getFile", { file_id: file_id })
75
- end
76
-
77
- def download_file(file_path, save_as)
78
- url = URI("https://api.telegram.org/file/bot#{@token}/#{file_path}")
79
- File.open(save_as, "wb") do |file|
80
- file.write(Net::HTTP.get(url))
81
- end
82
- save_as
83
- end
84
-
85
- def send_message(chat_id, text, **opts)
86
- request("sendMessage", { chat_id: chat_id, text: text }.merge(opts))
87
- end
88
-
89
- def forward_message(chat_id, from_chat_id, message_id, **opts)
90
- request("forwardMessage", {
91
- chat_id: chat_id,
92
- from_chat_id: from_chat_id,
93
- message_id: message_id
94
- }.merge(opts))
95
- end
96
-
97
- def forward_messages(chat_id, from_chat_id, message_ids, **opts)
98
- request("forwardMessages", {
99
- chat_id: chat_id,
100
- from_chat_id: from_chat_id,
101
- message_ids: message_ids
102
- }.merge(opts))
103
- end
104
-
105
- def forward_media_group(chat_id, from_chat_id, message_ids, **opts)
106
- forward_messages(chat_id, from_chat_id, message_ids, **opts)
107
- end
108
-
109
- def copy_message(chat_id, from_chat_id, message_id, **opts)
110
- request("copyMessage", {
111
- chat_id: chat_id,
112
- from_chat_id: from_chat_id,
113
- message_id: message_id
114
- }.merge(opts))
115
- end
116
-
117
- def copy_messages(chat_id, from_chat_id, message_ids, **opts)
118
- request("copyMessages", {
119
- chat_id: chat_id,
120
- from_chat_id: from_chat_id,
121
- message_ids: message_ids
122
- }.merge(opts))
123
- end
124
-
125
- def copy_media_group(chat_id, from_chat_id, message_ids, **opts)
126
- copy_messages(chat_id, from_chat_id, message_ids, **opts)
127
- end
128
-
129
- def send_photo(chat_id, photo, **opts)
130
- request("sendPhoto", { chat_id: chat_id, photo: photo }.merge(opts))
131
- end
132
-
133
- def send_audio(chat_id, audio, **opts)
134
- request("sendAudio", { chat_id: chat_id, audio: audio }.merge(opts))
135
- end
136
-
137
- def send_document(chat_id, document, **opts)
138
- request("sendDocument", { chat_id: chat_id, document: document }.merge(opts))
139
- end
140
-
141
- def send_video(chat_id, video, **opts)
142
- request("sendVideo", { chat_id: chat_id, video: video }.merge(opts))
143
- end
144
-
145
- def send_animation(chat_id, animation, **opts)
146
- request("sendAnimation", { chat_id: chat_id, animation: animation }.merge(opts))
147
- end
148
-
149
- def send_voice(chat_id, voice, **opts)
150
- request("sendVoice", { chat_id: chat_id, voice: voice }.merge(opts))
151
- end
152
-
153
- def send_video_note(chat_id, video_note, **opts)
154
- request("sendVideoNote", { chat_id: chat_id, video_note: video_note }.merge(opts))
155
- end
156
-
157
- def send_sticker(chat_id, sticker, **opts)
158
- request("sendSticker", { chat_id: chat_id, sticker: sticker }.merge(opts))
159
- end
160
-
161
- def send_cached_media(chat_id, file_id, **opts)
162
- request("sendDocument", { chat_id: chat_id, document: file_id }.merge(opts))
163
- end
164
-
165
- def send_screenshot_notification(chat_id, **opts)
166
- request("sendScreenshotNotification", { chat_id: chat_id }.merge(opts))
167
- end
168
-
169
- def send_paid_media(chat_id, star_count, media, **opts)
170
- request("sendPaidMedia", {
171
- chat_id: chat_id,
172
- star_count: star_count,
173
- media: media
174
- }.merge(opts))
175
- end
176
-
177
- def send_media_group(chat_id, media, **opts)
178
- request("sendMediaGroup", { chat_id: chat_id, media: media }.merge(opts))
179
- end
180
-
181
- def send_location(chat_id, latitude, longitude, **opts)
182
- request("sendLocation", {
183
- chat_id: chat_id,
184
- latitude: latitude,
185
- longitude: longitude
186
- }.merge(opts))
187
- end
188
-
189
- def send_venue(chat_id, latitude, longitude, title, address, **opts)
190
- request("sendVenue", {
191
- chat_id: chat_id,
192
- latitude: latitude,
193
- longitude: longitude,
194
- title: title,
195
- address: address
196
- }.merge(opts))
197
- end
198
-
199
- def send_contact(chat_id, phone_number, first_name, **opts)
200
- request("sendContact", {
201
- chat_id: chat_id,
202
- phone_number: phone_number,
203
- first_name: first_name
204
- }.merge(opts))
205
- end
206
-
207
- def send_poll(chat_id, question, options, **opts)
208
- request("sendPoll", {
209
- chat_id: chat_id,
210
- question: question,
211
- options: options
212
- }.merge(opts))
213
- end
214
-
215
- def send_checklist(chat_id, checklist, business_connection_id:, **opts)
216
- request("sendChecklist", {
217
- business_connection_id: business_connection_id,
218
- chat_id: chat_id,
219
- checklist: checklist
220
- }.merge(opts))
221
- end
222
-
223
- def get_web_app_link_url(**opts)
224
- request("getWebAppLinkUrl", opts)
225
- end
226
-
227
- def get_web_app_url(**opts)
228
- request("getWebAppUrl", opts)
229
- end
230
-
231
- def open_web_app(**opts)
232
- request("openWebApp", opts)
233
- end
234
-
235
- def send_dice(chat_id, **opts)
236
- request("sendDice", { chat_id: chat_id }.merge(opts))
237
- end
238
-
239
- def send_message_draft(chat_id, draft_id, text, **opts)
240
- request("sendMessageDraft", {
241
- chat_id: chat_id,
242
- draft_id: draft_id,
243
- text: text
244
- }.merge(opts))
245
- end
246
-
247
- def send_chat_action(chat_id, action, **opts)
248
- request("sendChatAction", { chat_id: chat_id, action: action }.merge(opts))
249
- end
250
-
251
- def set_message_reaction(chat_id, message_id, **opts)
252
- request("setMessageReaction", {
253
- chat_id: chat_id,
254
- message_id: message_id
255
- }.merge(opts))
256
- end
257
-
258
- def send_reaction(chat_id, message_id, **opts)
259
- set_message_reaction(chat_id, message_id, **opts)
260
- end
261
-
262
- def answer_callback_query(callback_query_id, **opts)
263
- request("answerCallbackQuery", {
264
- callback_query_id: callback_query_id
265
- }.merge(opts))
266
- end
267
-
268
- def answer_callback(callback_query_id, **opts)
269
- answer_callback_query(callback_query_id, **opts)
270
- end
271
-
272
- def edit_message_text(chat_id, message_id, text, **opts)
273
- request("editMessageText", {
274
- chat_id: chat_id,
275
- message_id: message_id,
276
- text: text
277
- }.merge(opts))
278
- end
279
-
280
- def delete_message(chat_id, message_id)
281
- request("deleteMessage", {
282
- chat_id: chat_id,
283
- message_id: message_id
284
- })
285
- end
286
-
287
- def delete_messages(chat_id, message_ids, **opts)
288
- request("deleteMessages", {
289
- chat_id: chat_id,
290
- message_ids: message_ids
291
- }.merge(opts))
292
- end
293
-
294
- def method_missing(name, *args, **kwargs, &block)
295
- return super if block
296
-
297
- params = {}
298
- if args.length == 1 && args.first.is_a?(Hash)
299
- params.merge!(args.first)
300
- elsif !args.empty?
301
- return super
302
- end
303
- params.merge!(kwargs) unless kwargs.empty?
304
-
305
- request(self.class.camelize_api_method(name), params)
306
- end
307
-
308
- def respond_to_missing?(_name, _include_private = false)
309
- true
310
- end
311
-
312
- def self.escape_markdown_v2(text)
313
- text.to_s.gsub(/([_\*\[\]\(\)~`>#+\-=|{}.!\\])/, '\\\\\1')
314
- end
315
-
316
- def self.escape_html(text)
317
- text.to_s
318
- .gsub("&", "&amp;")
319
- .gsub("<", "&lt;")
320
- .gsub(">", "&gt;")
321
- .gsub('"', "&quot;")
322
- end
323
-
324
- def self.camelize_api_method(name)
325
- alias_name = METHOD_ALIASES[name.to_s]
326
- return alias_name if alias_name
327
-
328
- parts = name.to_s.split("_")
329
- return name.to_s if parts.empty?
330
-
331
- parts.first + parts[1..].map(&:capitalize).join
332
- end
333
-
334
- private
335
-
336
- def serialize_params(params)
337
- params.each_with_object({}) do |(key, value), out|
338
- next if value.nil?
339
-
340
- out[key.to_s] = serialize_value(value)
341
- end
342
- end
343
-
344
- def serialize_value(value)
345
- case value
346
- when Hash, Array
347
- JSON.generate(value)
348
- else
349
- value
350
- end
351
- end
352
-
353
- def parse_response(response)
354
- payload = JSON.parse(response.body)
355
- return payload if payload["ok"]
356
-
357
- message = payload["description"] || "Unknown Telegram API error"
358
- raise Error, message
359
- rescue JSON::ParserError
360
- raise Error, "Invalid Telegram API response (HTTP #{response.code})"
361
- end
362
- end
363
- end
1
+ require "json"
2
+ require "net/http"
3
+ require "uri"
4
+ require_relative "retry"
5
+ require "stringio"
6
+
7
+ module GrubY
8
+ class API
9
+ class Error < StandardError; end
10
+ BOT_API_VERSION = "10.5".freeze
11
+ OFFICIAL_METHODS = %w[
12
+ getFile getUpdates setWebhook deleteWebhook getWebhookInfo
13
+ sendAudio sendDocument sendVoice getMe logOut close sendMessage
14
+ forwardMessage forwardMessages copyMessage copyMessages sendPhoto
15
+ sendLivePhoto sendVideo sendAnimation sendVideoNote sendWidget
16
+ sendRichMessage sendRichMessageDraft
17
+ sendSharedWidget sendPaidMedia sendMediaGroup sendLocation sendVenue
18
+ sendContact sendPoll sendChecklist sendDice sendMessageDraft
19
+ sendChatAction setMessageReaction getUserProfilePhotos getUserProfileAudios
20
+ setUserEmojiStatus banChatMember unbanChatMember restrictChatMember
21
+ promoteChatMember setChatAdministratorCustomTitle setChatMemberTag
22
+ banChatSenderChat unbanChatSenderChat setChatPermissions
23
+ exportChatInviteLink createChatInviteLink editChatInviteLink
24
+ createChatSubscriptionInviteLink editChatSubscriptionInviteLink
25
+ revokeChatInviteLink approveChatJoinRequest declineChatJoinRequest
26
+ answerChatJoinRequestQuery sendChatJoinRequestWebApp setChatPhoto
27
+ deleteChatPhoto setChatTitle setChatDescription pinChatMessage
28
+ unpinChatMessage unpinAllChatMessages leaveChat getChat
29
+ getChatAdministrators getChatMemberCount getChatMember
30
+ getChatShareThemeBackdrops getUserPersonalChatMessages setChatStickerSet
31
+ deleteChatStickerSet getForumTopicIconStickers createForumTopic
32
+ editForumTopic closeForumTopic reopenForumTopic deleteForumTopic
33
+ unpinAllForumTopicMessages editGeneralForumTopic closeGeneralForumTopic
34
+ reopenGeneralForumTopic hideGeneralForumTopic unhideGeneralForumTopic
35
+ unpinAllGeneralForumTopicMessages answerCallbackQuery answerWidgetQuery
36
+ answerGuestQuery getUserChatBoosts getBusinessConnection
37
+ getManagedBotToken replaceManagedBotToken getManagedBotAccessSettings
38
+ setManagedBotAccessSettings setMySettings setMyCommands deleteMyCommands
39
+ getMyCommands setMyName getMyName setMyDescription getMyDescription
40
+ setMyShortDescription getMyShortDescription setMyProfilePhoto
41
+ removeMyProfilePhoto setChatMenuButton getChatMenuButton
42
+ setMyDefaultAdministratorRights getMyDefaultAdministratorRights
43
+ getAvailableGifts sendGift giftPremiumSubscription verifyUser verifyChat
44
+ removeUserVerification removeChatVerification readBusinessMessage
45
+ deleteBusinessMessages setBusinessAccountName setBusinessAccountUsername
46
+ setBusinessAccountBio setBusinessAccountProfilePhoto
47
+ removeBusinessAccountProfilePhoto setBusinessAccountGiftSettings
48
+ getBusinessAccountStarBalance transferBusinessAccountStars
49
+ getBusinessAccountGifts getUserGifts getChatGifts getUniqueGift
50
+ convertGiftToStars upgradeGift transferGift deleteBusinessAccountGift
51
+ postStory repostStory editStory deleteStory answerWebAppQuery
52
+ savePreparedInlineMessage savePreparedKeyboardButton editMessageText
53
+ editMessageCaption editMessageMedia editMessageLiveLocation
54
+ stopMessageLiveLocation editMessageChecklist editMessageWidgetData
55
+ editSharedWidgetData editMessageReplyMarkup stopPoll
56
+ editEphemeralMessageText editEphemeralMessageMedia
57
+ editEphemeralMessageCaption editEphemeralMessageReplyMarkup
58
+ approveSuggestedPost declineSuggestedPost deleteMessage deleteMessages
59
+ deleteEphemeralMessage deleteMessageReaction deleteAllMessageReactions
60
+ sendSticker getStickerSet getCustomEmojiStickers uploadStickerFile
61
+ createNewStickerSet addStickerToSet setStickerPositionInSet
62
+ deleteStickerFromSet replaceStickerInSet setStickerEmojiList
63
+ setStickerKeywords setStickerMaskPosition setStickerSetTitle
64
+ setStickerSetThumbnail setCustomEmojiStickerSetThumbnail deleteStickerSet
65
+ answerInlineQuery sendInvoice createInvoiceLink answerShippingQuery
66
+ answerPreCheckoutQuery getMyStarBalance getStarTransactions
67
+ refundStarPayment editUserStarSubscription setPassportDataErrors
68
+ sendGame setGameScore getGameHighScores
69
+ ].freeze
70
+ METHOD_ALIASES = {
71
+ "set_bot_commands" => "setMyCommands",
72
+ "get_bot_commands" => "getMyCommands",
73
+ "delete_bot_commands" => "deleteMyCommands",
74
+ "set_bot_name" => "setMyName",
75
+ "get_bot_name" => "getMyName",
76
+ "set_bot_info_description" => "setMyDescription",
77
+ "get_bot_info_description" => "getMyDescription",
78
+ "set_bot_info_short_description" => "setMyShortDescription",
79
+ "get_bot_info_short_description" => "getMyShortDescription",
80
+ "set_bot_default_privileges" => "setMyDefaultAdministratorRights",
81
+ "get_bot_default_privileges" => "getMyDefaultAdministratorRights",
82
+ "get_chat_members_count" => "getChatMemberCount",
83
+ "get_chat_photos" => "getUserProfilePhotos",
84
+ "get_chat_audios" => "getUserProfileAudios",
85
+ "set_emoji_status" => "setUserEmojiStatus",
86
+ "get_managed_bot_token" => "getManagedBotToken",
87
+ "replace_managed_bot_token" => "replaceManagedBotToken",
88
+ "ban_chat_member" => "banChatMember",
89
+ "unban_chat_member" => "unbanChatMember",
90
+ "restrict_chat_member" => "restrictChatMember",
91
+ "promote_chat_member" => "promoteChatMember",
92
+ "set_administrator_title" => "setChatAdministratorCustomTitle",
93
+ "set_chat_member_tag" => "setChatMemberTag",
94
+ "set_chat_menu_button" => "setChatMenuButton",
95
+ "get_chat_menu_button" => "getChatMenuButton",
96
+ "send_reaction" => "setMessageReaction",
97
+ "set_message_reaction" => "setMessageReaction",
98
+ "export_chat_invite_link" => "exportChatInviteLink",
99
+ "create_chat_invite_link" => "createChatInviteLink",
100
+ "edit_chat_invite_link" => "editChatInviteLink",
101
+ "revoke_chat_invite_link" => "revokeChatInviteLink",
102
+ "approve_chat_join_request" => "approveChatJoinRequest",
103
+ "decline_chat_join_request" => "declineChatJoinRequest",
104
+ "send_message_draft" => "sendMessageDraft",
105
+ "set_my_settings" => "setMySettings",
106
+ "send_rich_message" => "sendRichMessage",
107
+ "send_rich_message_draft" => "sendRichMessageDraft",
108
+ "send_live_photo" => "sendLivePhoto",
109
+ "send_widget" => "sendWidget",
110
+ "send_shared_widget" => "sendSharedWidget",
111
+ "answer_widget_query" => "answerWidgetQuery",
112
+ "get_unique_gift" => "getUniqueGift",
113
+ "delete_ephemeral_message" => "deleteEphemeralMessage",
114
+ "edit_ephemeral_message_text" => "editEphemeralMessageText",
115
+ "edit_ephemeral_message_media" => "editEphemeralMessageMedia",
116
+ "edit_ephemeral_message_caption" => "editEphemeralMessageCaption",
117
+ "edit_ephemeral_message_reply_markup" => "editEphemeralMessageReplyMarkup",
118
+ "send_paid_reaction" => "sendPaidReaction",
119
+ "get_user_chat_boosts" => "getUserChatBoosts",
120
+ "get_business_connection" => "getBusinessConnection",
121
+ "forward_media_group" => "forwardMessages",
122
+ "copy_media_group" => "copyMessages"
123
+ }.freeze
124
+
125
+ def initialize(token)
126
+ @token = token
127
+ @base = URI("https://api.telegram.org/bot#{token}/")
128
+ end
129
+
130
+ def request(method, params = {})
131
+ payload = raw(method, params)
132
+ payload["result"]
133
+ end
134
+
135
+ def raw(method, params = {})
136
+ uri = @base + method.to_s
137
+ response = Retry.call do
138
+ clean_params = params.each_with_object({}) do |(key, value), out|
139
+ next if value.nil?
140
+
141
+ out[key.to_s] = value
142
+ end
143
+
144
+ if clean_params.any? { |key, value| multipart_file_field?(key) && upload_value?(value) }
145
+ post_multipart(uri, clean_params)
146
+ else
147
+ post_json(uri, clean_params)
148
+ end
149
+ end
150
+ parse_response(response)
151
+ end
152
+
153
+ def get_updates(offset = nil, timeout: 30, **opts)
154
+ params = { timeout: timeout }.merge(opts)
155
+ params[:offset] = offset if offset
156
+ request("getUpdates", params)
157
+ end
158
+
159
+ def get_file(file_id)
160
+ request("getFile", { file_id: file_id })
161
+ end
162
+
163
+ def download_file(file_path, save_as)
164
+ url = URI("https://api.telegram.org/file/bot#{@token}/#{file_path}")
165
+ File.open(save_as, "wb") do |file|
166
+ file.write(Net::HTTP.get(url))
167
+ end
168
+ save_as
169
+ end
170
+
171
+ def send_message(chat_id, text, **opts)
172
+ request("sendMessage", { chat_id: chat_id, text: text }.merge(opts))
173
+ end
174
+
175
+ def forward_message(chat_id, from_chat_id, message_id, **opts)
176
+ request("forwardMessage", {
177
+ chat_id: chat_id,
178
+ from_chat_id: from_chat_id,
179
+ message_id: message_id
180
+ }.merge(opts))
181
+ end
182
+
183
+ def forward_messages(chat_id, from_chat_id, message_ids, **opts)
184
+ request("forwardMessages", {
185
+ chat_id: chat_id,
186
+ from_chat_id: from_chat_id,
187
+ message_ids: message_ids
188
+ }.merge(opts))
189
+ end
190
+
191
+ def forward_media_group(chat_id, from_chat_id, message_ids, **opts)
192
+ forward_messages(chat_id, from_chat_id, message_ids, **opts)
193
+ end
194
+
195
+ def copy_message(chat_id, from_chat_id, message_id, **opts)
196
+ request("copyMessage", {
197
+ chat_id: chat_id,
198
+ from_chat_id: from_chat_id,
199
+ message_id: message_id
200
+ }.merge(opts))
201
+ end
202
+
203
+ def copy_messages(chat_id, from_chat_id, message_ids, **opts)
204
+ request("copyMessages", {
205
+ chat_id: chat_id,
206
+ from_chat_id: from_chat_id,
207
+ message_ids: message_ids
208
+ }.merge(opts))
209
+ end
210
+
211
+ def copy_media_group(chat_id, from_chat_id, message_ids, **opts)
212
+ copy_messages(chat_id, from_chat_id, message_ids, **opts)
213
+ end
214
+
215
+ def send_photo(chat_id, photo, **opts)
216
+ request("sendPhoto", { chat_id: chat_id, photo: photo }.merge(opts))
217
+ end
218
+
219
+ def send_audio(chat_id, audio, **opts)
220
+ request("sendAudio", { chat_id: chat_id, audio: audio }.merge(opts))
221
+ end
222
+
223
+ def send_document(chat_id, document, **opts)
224
+ request("sendDocument", { chat_id: chat_id, document: document }.merge(opts))
225
+ end
226
+
227
+ def send_video(chat_id, video, **opts)
228
+ request("sendVideo", { chat_id: chat_id, video: video }.merge(opts))
229
+ end
230
+
231
+ def send_animation(chat_id, animation, **opts)
232
+ request("sendAnimation", { chat_id: chat_id, animation: animation }.merge(opts))
233
+ end
234
+
235
+ def send_voice(chat_id, voice, **opts)
236
+ request("sendVoice", { chat_id: chat_id, voice: voice }.merge(opts))
237
+ end
238
+
239
+ def send_video_note(chat_id, video_note, **opts)
240
+ request("sendVideoNote", { chat_id: chat_id, video_note: video_note }.merge(opts))
241
+ end
242
+
243
+ def send_sticker(chat_id, sticker, **opts)
244
+ request("sendSticker", { chat_id: chat_id, sticker: sticker }.merge(opts))
245
+ end
246
+
247
+ def send_cached_media(chat_id, file_id, **opts)
248
+ request("sendDocument", { chat_id: chat_id, document: file_id }.merge(opts))
249
+ end
250
+
251
+ def send_screenshot_notification(chat_id, **opts)
252
+ request("sendScreenshotNotification", { chat_id: chat_id }.merge(opts))
253
+ end
254
+
255
+ def send_paid_media(chat_id, star_count, media, **opts)
256
+ request("sendPaidMedia", {
257
+ chat_id: chat_id,
258
+ star_count: star_count,
259
+ media: media
260
+ }.merge(opts))
261
+ end
262
+
263
+ def send_media_group(chat_id, media, **opts)
264
+ request("sendMediaGroup", { chat_id: chat_id, media: media }.merge(opts))
265
+ end
266
+
267
+ def send_location(chat_id, latitude, longitude, **opts)
268
+ request("sendLocation", {
269
+ chat_id: chat_id,
270
+ latitude: latitude,
271
+ longitude: longitude
272
+ }.merge(opts))
273
+ end
274
+
275
+ def send_venue(chat_id, latitude, longitude, title, address, **opts)
276
+ request("sendVenue", {
277
+ chat_id: chat_id,
278
+ latitude: latitude,
279
+ longitude: longitude,
280
+ title: title,
281
+ address: address
282
+ }.merge(opts))
283
+ end
284
+
285
+ def send_contact(chat_id, phone_number, first_name, **opts)
286
+ request("sendContact", {
287
+ chat_id: chat_id,
288
+ phone_number: phone_number,
289
+ first_name: first_name
290
+ }.merge(opts))
291
+ end
292
+
293
+ def send_poll(chat_id, question, options, **opts)
294
+ request("sendPoll", {
295
+ chat_id: chat_id,
296
+ question: question,
297
+ options: options
298
+ }.merge(opts))
299
+ end
300
+
301
+ def send_checklist(chat_id, checklist, business_connection_id:, **opts)
302
+ request("sendChecklist", {
303
+ business_connection_id: business_connection_id,
304
+ chat_id: chat_id,
305
+ checklist: checklist
306
+ }.merge(opts))
307
+ end
308
+
309
+ def get_web_app_link_url(**opts)
310
+ request("getWebAppLinkUrl", opts)
311
+ end
312
+
313
+ def get_web_app_url(**opts)
314
+ request("getWebAppUrl", opts)
315
+ end
316
+
317
+ def open_web_app(**opts)
318
+ request("openWebApp", opts)
319
+ end
320
+
321
+ def send_dice(chat_id, **opts)
322
+ request("sendDice", { chat_id: chat_id }.merge(opts))
323
+ end
324
+
325
+ def send_message_draft(chat_id, draft_id, text, **opts)
326
+ request("sendMessageDraft", {
327
+ chat_id: chat_id,
328
+ draft_id: draft_id,
329
+ text: text
330
+ }.merge(opts))
331
+ end
332
+
333
+ def send_chat_action(chat_id, action, **opts)
334
+ request("sendChatAction", { chat_id: chat_id, action: action }.merge(opts))
335
+ end
336
+
337
+ def set_message_reaction(chat_id, message_id, **opts)
338
+ request("setMessageReaction", {
339
+ chat_id: chat_id,
340
+ message_id: message_id
341
+ }.merge(opts))
342
+ end
343
+
344
+ def send_reaction(chat_id, message_id, **opts)
345
+ set_message_reaction(chat_id, message_id, **opts)
346
+ end
347
+
348
+ def answer_callback_query(callback_query_id, **opts)
349
+ request("answerCallbackQuery", {
350
+ callback_query_id: callback_query_id
351
+ }.merge(opts))
352
+ end
353
+
354
+ def answer_callback(callback_query_id, **opts)
355
+ answer_callback_query(callback_query_id, **opts)
356
+ end
357
+
358
+ def edit_message_text(chat_id, message_id, text, **opts)
359
+ request("editMessageText", {
360
+ chat_id: chat_id,
361
+ message_id: message_id,
362
+ text: text
363
+ }.merge(opts))
364
+ end
365
+
366
+ def delete_message(chat_id, message_id)
367
+ request("deleteMessage", {
368
+ chat_id: chat_id,
369
+ message_id: message_id
370
+ })
371
+ end
372
+
373
+ def delete_messages(chat_id, message_ids, **opts)
374
+ request("deleteMessages", {
375
+ chat_id: chat_id,
376
+ message_ids: message_ids
377
+ }.merge(opts))
378
+ end
379
+
380
+ OFFICIAL_METHODS.each do |api_method|
381
+ snake_name = api_method
382
+ .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
383
+ .gsub(/([a-z\d])([A-Z])/, '\1_\2')
384
+ .downcase
385
+
386
+ define_method(snake_name) do |*args, **kwargs|
387
+ params = {}
388
+ if args.length == 1 && args.first.is_a?(Hash)
389
+ params.merge!(args.first)
390
+ elsif !args.empty?
391
+ raise ArgumentError, "#{snake_name} accepts a parameter hash or keyword arguments"
392
+ end
393
+ params.merge!(kwargs) unless kwargs.empty?
394
+ request(api_method, params)
395
+ end
396
+ end
397
+
398
+ def method_missing(name, *args, **kwargs, &block)
399
+ return super if block
400
+
401
+ params = {}
402
+ if args.length == 1 && args.first.is_a?(Hash)
403
+ params.merge!(args.first)
404
+ elsif !args.empty?
405
+ return super
406
+ end
407
+ params.merge!(kwargs) unless kwargs.empty?
408
+
409
+ request(self.class.camelize_api_method(name), params)
410
+ end
411
+
412
+ def respond_to_missing?(_name, _include_private = false)
413
+ true
414
+ end
415
+
416
+ def self.escape_markdown_v2(text)
417
+ text.to_s.gsub(/([_\*\[\]\(\)~`>#+\-=|{}.!\\])/, '\\\\\1')
418
+ end
419
+
420
+ def self.escape_html(text)
421
+ text.to_s
422
+ .gsub("&", "&amp;")
423
+ .gsub("<", "&lt;")
424
+ .gsub(">", "&gt;")
425
+ .gsub('"', "&quot;")
426
+ end
427
+
428
+ def self.camelize_api_method(name)
429
+ alias_name = METHOD_ALIASES[name.to_s]
430
+ return alias_name if alias_name
431
+
432
+ parts = name.to_s.split("_")
433
+ return name.to_s if parts.empty?
434
+
435
+ parts.first + parts[1..].map(&:capitalize).join
436
+ end
437
+
438
+ private
439
+
440
+ def post_json(uri, params)
441
+ request = Net::HTTP::Post.new(uri)
442
+ request["Content-Type"] = "application/json"
443
+ request.body = JSON.generate(params)
444
+ Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
445
+ http.request(request)
446
+ end
447
+ end
448
+
449
+ def post_multipart(uri, params)
450
+ boundary = "----gruby#{object_id}#{Process.pid}"
451
+ body = StringIO.new
452
+
453
+ params.each do |key, value|
454
+ if multipart_file_field?(key) && upload_value?(value)
455
+ append_multipart_file(body, boundary, key, value)
456
+ elsif value.is_a?(Hash) || value.is_a?(Array)
457
+ append_multipart_field(body, boundary, key, JSON.generate(value))
458
+ else
459
+ append_multipart_field(body, boundary, key, value.to_s)
460
+ end
461
+ end
462
+ body.write("--#{boundary}--\r\n")
463
+
464
+ request = Net::HTTP::Post.new(uri)
465
+ request["Content-Type"] = "multipart/form-data; boundary=#{boundary}"
466
+ request.body = body.string
467
+ Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
468
+ http.request(request)
469
+ end
470
+ end
471
+
472
+ def append_multipart_field(body, boundary, name, value)
473
+ body.write("--#{boundary}\r\n")
474
+ body.write("Content-Disposition: form-data; name=\"#{name}\"\r\n\r\n")
475
+ body.write(value)
476
+ body.write("\r\n")
477
+ end
478
+
479
+ def append_multipart_file(body, boundary, name, value)
480
+ io = value.respond_to?(:read) ? value : File.open(value, "rb")
481
+ filename = if value.respond_to?(:path)
482
+ File.basename(value.path)
483
+ elsif value.is_a?(String)
484
+ File.basename(value)
485
+ else
486
+ "upload"
487
+ end
488
+ body.write("--#{boundary}\r\n")
489
+ body.write("Content-Disposition: form-data; name=\"#{name}\"; filename=\"#{filename}\"\r\n")
490
+ body.write("Content-Type: application/octet-stream\r\n\r\n")
491
+ body.write(io.read)
492
+ body.write("\r\n")
493
+ io.close if value.is_a?(String)
494
+ end
495
+
496
+ def upload_value?(value)
497
+ value.is_a?(File) ||
498
+ value.is_a?(StringIO) ||
499
+ value.respond_to?(:read) ||
500
+ (value.is_a?(String) && File.file?(value))
501
+ rescue StandardError
502
+ false
503
+ end
504
+
505
+ def multipart_file_field?(name)
506
+ %w[
507
+ photo video animation audio voice video_note document sticker
508
+ thumb thumbnail certificate png_sticker tgs_sticker webp_sticker
509
+ profile_photo file
510
+ ].include?(name.to_s)
511
+ end
512
+
513
+ def serialize_params(params)
514
+ params.each_with_object({}) do |(key, value), out|
515
+ next if value.nil?
516
+
517
+ out[key.to_s] = serialize_value(value)
518
+ end
519
+ end
520
+
521
+ def serialize_value(value)
522
+ case value
523
+ when Hash, Array
524
+ JSON.generate(value)
525
+ else
526
+ value
527
+ end
528
+ end
529
+
530
+ def parse_response(response)
531
+ payload = JSON.parse(response.body.to_s)
532
+ return payload if payload["ok"]
533
+
534
+ message = payload["description"] || "Unknown Telegram API error"
535
+ raise Error, message
536
+ rescue JSON::ParserError
537
+ raise Error, "Invalid Telegram API response (HTTP #{response.code})"
538
+ end
539
+ end
540
+ end