telegem 1.0.6 → 2.0.0

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3777c7718d621ee9b2905ea456a9255c16cee07d1dbda297521602786088d046
4
- data.tar.gz: ba5e53faa9da8b44218d709899383d6f932366aa6b9444405489e21062a60b4c
3
+ metadata.gz: c55866ecfc21045fd47141b991f00a209cecd5c866fe52b73c2ffb302f0245ea
4
+ data.tar.gz: 0a0e93a2c61487e759ecbc1e3ed2f86b1e77fbd993076acbebc6287f36584a52
5
5
  SHA512:
6
- metadata.gz: 909c70af6d30e6e780dabb647e320b4986eb518987dcf9740c4194c8941df317afabc0cc5a4ce5ec8be531c5febdfc4e7659c800cbdaf0744e59475d9a4bd0b8
7
- data.tar.gz: 191ccb89c87d3e8b2584324de82836571f10443f32b79ba3bdce98af496de11e32600b3f4cd31d844dc0f19903bf6f3ab6cf42a5fcb9df47151a5c072e7d127f
6
+ metadata.gz: 791184d5d43c592bbd66b844386112bd336ee4a7ab7bcfe30ce08eaca3a30f53eb819642c9ba5640084c4d17f91b81cee11cf006c4537175e2b86db2420c6db8
7
+ data.tar.gz: 668eb8f1b6b3e5d3d2280fb2000e545836fa53af096ab6af89b87560b7484bee51a3be8360dbfe989966423c69ea0a916cb5f40f99862c19a47205d8880d8570
data/docs/Api.md CHANGED
@@ -1,419 +1,211 @@
1
+ # Telegem API Reference (v2.0.0)
1
2
 
2
- # 📚 API Reference
3
+ ![Gem Version](https://img.shields.io/gem/v/telegem?color=blue)
4
+ ![Ruby](https://img.shields.io/badge/Ruby-%3E%3D%203.0-red)
5
+ ![License](https://img.shields.io/badge/license-MIT-green)
6
+ ![Telegram Bot API](https://img.shields.io/badge/Telegram%20Bot%20API-7.0-lightblue)
3
7
 
4
- Quick reference for all Telegem classes and methods. Use this when you know what you need and want the exact syntax.
8
+ Modern Telegram Bot Framework for Ruby. This guide details the core methods provided by the Telegem library, your modern toolkit for building Telegram bots with Ruby. Built on the official Telegram Bot API. For detailed parameter info, always check the official docs.
5
9
 
6
- ---
7
-
8
- ## 📦 Main Classes
9
-
10
- ### `Telegem::Bot` (Main Class)
11
- ```ruby
12
- # Create a bot
13
- bot = Telegem.new(token)
14
- # or
15
- bot = Telegem::Core::Bot.new(token, **options)
16
-
17
- # Options:
18
- # - logger: Custom logger (default: Logger.new($stdout))
19
- # - concurrency: Max parallel updates (default: 10)
20
- # - session_store: :memory, :redis, or custom object
21
- ```
22
-
23
- Context (ctx in handlers)
24
-
25
- The object you get in every handler. Controls the conversation.
10
+ [![Join Official Channel](https://img.shields.io/badge/🔗-Join_Official_Channel-blue?style=flat&logo=telegram)](https://t.me/telegem_ruby)
26
11
 
27
12
  ---
28
13
 
29
- 🎮 Context Methods
14
+ ## 1. 🤖 Core Bot Setup & Lifecycle
30
15
 
31
- Sending Messages
16
+ "First, solve the problem. Then, write the code." - John Johnson
32
17
 
33
- ```ruby
34
- ctx.reply(text, **options) # Send message
35
- ctx.edit_message_text(text, **options) # Edit last message
36
- ctx.delete_message(message_id = nil) # Delete message
37
- ctx.forward_message(from_chat_id, message_id) # Forward message
38
- ctx.copy_message(from_chat_id, message_id) # Copy message
39
- ```
18
+ These methods get your bot online and talking.
40
19
 
41
- Sending Media
20
+ - **Telegem.new(token, **options)**
21
+ - What it does: Creates your bot instance. This is your starting point.
22
+ - Key Options: logger, timeout, max_threads, session_store.
23
+ - Returns: A shiny new Telegem::Core::Bot object.
42
24
 
43
- ```ruby
44
- ctx.photo(photo, caption: nil, **options) # Send photo
45
- ctx.document(doc, caption: nil, **options) # Send file
46
- ctx.audio(audio, caption: nil, **options) # Send audio
47
- ctx.video(video, caption: nil, **options) # Send video
48
- ctx.voice(voice, caption: nil, **options) # Send voice
49
- ctx.sticker(sticker, **options) # Send sticker
50
- ctx.location(lat, long, **options) # Send location
51
- ```
25
+ - **bot.start_polling(**options)**
26
+ - What it does: Starts the classic "call-and-check" method for updates. Perfect for development.
27
+ - Pro-tip: Don't use this if you have a webhook active (it's like trying to receive mail at two different houses).
52
28
 
53
- Chat Actions
29
+ - **bot.webhook(...)** or **Telegem.webhook(bot, ...)**
30
+ - What it does: Sets up a production-grade server so Telegram can push updates directly to your bot. It's the recommended way for serious bots.
31
+ - Telegem Superpowers:
32
+ - Production-ready: Uses the Puma web server out of the box.
33
+ - Cloud-Smart: Automatically figures out if you're on Render, Heroku, etc.
34
+ - Secure: Validates incoming requests with a secret_token.
35
+ - Helper: Call server.set_webhook() after server.run to tell Telegram where to find you.
54
36
 
55
- ```ruby
56
- ctx.send_chat_action(action, **options) # Show typing/uploading
57
- ctx.typing(**options) # Shortcut for 'typing'
58
- ctx.uploading_photo(**options) # Shortcut for 'upload_photo'
59
- ctx.with_typing { block } # Show typing while block runs
60
- ```
61
-
62
- Callback & Inline Queries
37
+ - **bot.shutdown**
38
+ - What it does: The polite way to tell your bot to stop. Closes connections and cleans up threads.
63
39
 
64
- ```ruby
65
- ctx.answer_callback_query(text: nil, show_alert: false)
66
- ctx.answer_inline_query(results, **options)
67
- ```
40
+ ---
68
41
 
69
- Chat Management
42
+ ## 2. 📨 Update Handling & Events
70
43
 
71
- ```ruby
72
- ctx.get_chat(**options)
73
- ctx.get_chat_administrators(**options)
74
- ctx.get_chat_members_count(**options)
75
- ctx.ban_chat_member(user_id, **options)
76
- ctx.unban_chat_member(user_id, **options)
77
- ctx.kick_chat_member(user_id, **options)
78
- ctx.pin_message(message_id, **options)
79
- ctx.unpin_message(**options)
80
- ```
44
+ "Programming is 10% writing code and 90% figuring out why it doesn't work." - Unknown Bot Developer
81
45
 
82
- Keyboard Helpers
46
+ Tell your bot how to react to the world.
83
47
 
84
- ```ruby
85
- ctx.keyboard { block } # Create reply keyboard
86
- ctx.inline_keyboard { block } # Create inline keyboard
87
- ctx.reply_with_keyboard(text, keyboard, **options)
88
- ctx.reply_with_inline_keyboard(text, inline, **options)
89
- ctx.remove_keyboard(text = nil, **options)
90
- ctx.edit_message_reply_markup(reply_markup, **options)
91
- ```
48
+ - **bot.on(type, filters = {}, &block)**
49
+ - What it does: Your main tool for handling any event. Runs your code block when a matching update arrives.
50
+ - Types: :message, :callback_query, :inline_query, :edited_message, etc.
51
+ - Examples:
52
+ ```ruby
53
+ # Respond to text matching a regex
54
+ bot.on(:message, text: /hello/i) { |ctx| ctx.reply("Hi there!") }
55
+ # Handle a specific inline button press
56
+ bot.on(:callback_query, data: "confirm") { |ctx| ctx.answer_callback_query(text: "Done!") }
57
+ ```
92
58
 
93
- Scene Management
59
+ - **bot.command(name, **options, &block)**
60
+ - What it does: The easy way to handle slash commands like /start or /help.
61
+ - Example:
62
+ ```ruby
63
+ bot.command("start") do |ctx|
64
+ ctx.reply("Welcome to the future of Telegram bots!")
65
+ end
66
+ ```
94
67
 
95
- ```ruby
96
- ctx.enter_scene(scene_name, **options)
97
- ctx.leave_scene(**options)
98
- ctx.current_scene # Returns current scene object
99
- ```
68
+ - **bot.hears(pattern, **options, &block)**
69
+ - What it does: A shortcut specifically for catching text messages with a regex pattern.
100
70
 
101
- Information Getters
71
+ - **bot.use(middleware, *args, &block)**
72
+ - What it does: Adds a middleware to the processing chain. Great for logging every request, checking user permissions, or adding timings.
73
+ - Joke: Why did the developer go broke? He used up all his cache.
102
74
 
103
- ```ruby
104
- ctx.message # Message object
105
- ctx.callback_query # CallbackQuery object
106
- ctx.inline_query # InlineQuery object
107
- ctx.from # User who sent
108
- ctx.chat # Chat object
109
- ctx.data # Callback data (for buttons)
110
- ctx.query # Inline query text
111
- ctx.user_id # Shortcut for from.id
112
- ctx.command? # true if message is command
113
- ctx.command_args # Arguments after command
114
- ctx.raw_update # Raw Telegram JSON
115
- ctx.api # Direct API client access
116
- ctx.logger # Bot's logger
117
- ctx.session # User's session hash
118
- ctx.state # Temporary state hash
119
- ctx.match # Regex match data
120
- ```
75
+ - **bot.error(&block)**
76
+ - What it does: Sets up a global safety net to catch any errors that happen inside your handlers, so your bot doesn't just crash silently.
121
77
 
122
78
  ---
123
79
 
124
- ⌨️ Keyboard Builders
80
+ ## 3. 🔄 The Context (ctx) Object - Your Swiss Army Knife
125
81
 
126
- Reply Keyboard
82
+ Inside every handler, you get a ctx object. It's your interface to do everything, from sending messages to managing chats. These methods return async HTTPX request objects.
127
83
 
128
- ```ruby
129
- keyboard = Telegem::Markup.keyboard do
130
- row "Button 1", "Button 2"
131
- row "Cancel"
132
- end
84
+ "Talk is cheap. Show me the code." - Linus Torvalds (Probably while debugging a context method)
133
85
 
134
- # Options can be chained:
135
- keyboard.resize(false).one_time.selective(true)
86
+ ### A. Sending Messages & Content
136
87
 
137
- # Convert to hash for Telegram:
138
- keyboard.to_h
139
- ```
88
+ - **ctx.reply(text, **options)** - Your bread and butter. Sends a text reply.
89
+ - **ctx.photo(photo, caption: nil, **options)** - Sends an image.
90
+ - **ctx.document(document, caption: nil, **options)** - Sends a file.
91
+ - **ctx.audio(audio, caption: nil, **options)** - Sends an audio file.
92
+ - **ctx.video(video, caption: nil, **options)** - Sends a video.
93
+ - **ctx.voice(voice, caption: nil, **options)** - Sends a voice message.
94
+ - **ctx.sticker(sticker, **options)** - Sends a sticker. Because communication is serious business.
95
+ - **ctx.location(latitude, longitude, **options)** - Shares a location.
140
96
 
141
- Inline Keyboard
97
+ ### B. Managing Existing Messages
142
98
 
143
- ```ruby
144
- inline = Telegem::Markup.inline do
145
- row callback("Option 1", "data1"),
146
- callback("Option 2", "data2")
147
- row url("Website", "https://example.com"),
148
- web_app("Open App", "https://app.example.com")
149
- row switch_inline("Search", "query"),
150
- switch_inline_current("Search Here", "")
151
- end
152
- ```
99
+ - **ctx.edit_message_text(text, **options)** - Changes the text of a message you sent.
100
+ - **ctx.delete_message(message_id = nil)** - Poof! Makes a message disappear. Defaults to the current message.
101
+ - **ctx.forward_message(from_chat_id, message_id, **options)** - Forwards a message from elsewhere.
102
+ - **ctx.copy_message(from_chat_id, message_id, **options)** - Copies a message (with forward info).
103
+ - **ctx.pin_message(message_id, **options)** - Pins a message in the chat.
104
+ - **ctx.unpin_message(**options)** - Unpins it.
153
105
 
154
- Special Markups
106
+ ### C. Chat Actions & Info
155
107
 
156
- ```ruby
157
- Telegem::Markup.remove(selective: false) # Remove keyboard
158
- Telegem::Markup.force_reply(selective: false) # Force reply
159
- ```
108
+ - **ctx.send_chat_action(action, **options)** - Shows a status like "typing..." or "uploading photo..." to users. Required: Be polite and use this for long operations!
109
+ - **ctx.get_chat(**options)** - Gets info about the current chat.
110
+ - **ctx.get_chat_administrators(**options)** - Lists the chat admins.
111
+ - **ctx.get_chat_members_count(**options)** - Counts chat members.
160
112
 
161
- ---
113
+ ### D. Callback & Inline Queries
162
114
 
163
- 🧙 Scenes (Wizard System)
115
+ - **ctx.answer_callback_query(text: nil, show_alert: false, **options)** - Responds to a button press. Stops the loading animation on the button.
116
+ - **ctx.answer_inline_query(results, **options)** - Answers an inline query with a list of results.
164
117
 
165
- Defining a Scene
118
+ ### E. Chat Administration
166
119
 
167
- ```ruby
168
- bot.scene :registration do
169
- step :ask_name do |ctx|
170
- ctx.reply "What's your name?"
171
- end
172
-
173
- step :save_name do |ctx|
174
- ctx.session[:name] = ctx.message.text
175
- ctx.reply "Thanks #{ctx.session[:name]}!"
176
- ctx.leave_scene
177
- end
178
-
179
- on_enter do |ctx|
180
- ctx.reply "Welcome to registration!"
181
- end
182
-
183
- on_leave do |ctx|
184
- ctx.reply "Registration complete!"
185
- end
186
- end
187
- ```
120
+ - **ctx.kick_chat_member(user_id, **options)** - Removes a user from the chat.
121
+ - **ctx.ban_chat_member(user_id, **options)** - Bans a user.
122
+ - **ctx.unban_chat_member(user_id, **options)** - Unbans a user.
188
123
 
189
- Scene Methods
124
+ ### F. Convenience Shortcuts
190
125
 
191
- ```ruby
192
- scene.enter(ctx, step_name = :default)
193
- scene.leave(ctx)
194
- scene.current_step(ctx)
195
- scene.reset(ctx)
196
- ```
126
+ - **ctx.typing(**options)** - Shortcut for send_chat_action('typing').
127
+ - **ctx.uploading_photo(**options)** - Shortcut for send_chat_action('upload_photo').
128
+ - **ctx.with_typing(&block)** - A helper that shows "typing..." while your code block executes.
129
+ - **ctx.command?** - Returns true if the current message is a command.
130
+ - **ctx.command_args** - Returns the arguments provided after a command (e.g., for /search ruby, it returns "ruby").
197
131
 
198
132
  ---
199
133
 
200
- 🔌 Middleware
134
+ ## 4. ⌨️ Building Keyboards & Interactions
201
135
 
202
- Using Middleware
136
+ "The best interface is one that the user doesn't notice." - Let's help them not notice it's awesome.
203
137
 
204
- ```ruby
205
- # Add built-in session middleware
206
- bot.use Telegem::Session::Middleware.new
207
-
208
- # Add custom middleware
209
- bot.use do |ctx, next_middleware|
210
- puts "Before: #{ctx.message&.text}"
211
- next_middleware.call(ctx)
212
- puts "After"
213
- end
138
+ Telegem provides a clean DSL for creating interactive keyboards.
214
139
 
215
- # Add middleware class
216
- class LoggingMiddleware
217
- def call(ctx, next_middleware)
218
- # Your code here
219
- next_middleware.call(ctx)
140
+ - **Telegem.keyboard(&block)** - Creates a reply keyboard (appears where users type).
141
+ ```ruby
142
+ keyboard = Telegem.keyboard do
143
+ row "Yes", "No"
144
+ row "Maybe", "Cancel"
145
+ resize true # Fits to screen width
146
+ one_time true # Hides after one use
220
147
  end
221
- end
222
- bot.use LoggingMiddleware.new
223
- ```
224
-
225
- ---
226
-
227
- 💾 Session Stores
228
-
229
- Available Stores
230
-
231
- ```ruby
232
- # Memory store (default)
233
- Telegem::Session::MemoryStore.new
234
-
235
- # Redis store
236
- require 'telegem/session/redis_store'
237
- Telegem::Session::RedisStore.new(redis_client)
238
-
239
- # File store
240
- require 'telegem/session/file_store'
241
- Telegem::Session::FileStore.new("sessions.json")
148
+ ctx.reply("Choose wisely:", reply_markup: keyboard)
242
149
  ```
243
150
 
244
- Session Middleware
245
-
246
- ```ruby
247
- bot.use Telegem::Session::Middleware.new(
248
- store: store_object, # defaults to MemoryStore
249
- key_prefix: "telegem:" # optional prefix for storage keys
250
- )
251
- ```
151
+ · Telegem.inline(&block) - Creates an inline keyboard (appears inside the message).
152
+ ```ruby
153
+ inline_kb = Telegem.inline do
154
+ row do
155
+ callback_button "Approve", "approve_123"
156
+ url_button "Read Docs", "https://gitlab.com/ruby-telegem/telegem"
157
+ end
158
+ end
159
+ ctx.reply("What next?", reply_markup: inline_kb)
160
+ ```
252
161
 
253
162
  ---
254
163
 
255
- 🌐 Webhook Server
256
-
257
- Creating a Server
258
-
259
- ```ruby
260
- server = bot.webhook_server(
261
- port: 3000, # default: 3000
262
- endpoint: endpoint_object, # Async::HTTP::Endpoint
263
- logger: logger_object # custom logger
264
- )
265
-
266
- server.run # Start async server
267
- server.stop # Stop server
268
- server.running? # Check if running
269
- server.webhook_url # Get full webhook URL
270
- ```
271
-
272
- ---
164
+ 5. 🎭 Scene System & Session Management
273
165
 
274
- Bot Methods
166
+ "Good programmers write code that works. Great programmers write code that manages state." - Ancient Developer Proverb
275
167
 
276
- Handler Registration
168
+ Manage multi-step conversations (like a signup flow) easily.
277
169
 
278
- ```ruby
279
- bot.command(name, **options) { |ctx| } # /command handler
280
- bot.hears(pattern, **options) { |ctx| } # Text pattern handler
281
- bot.on(type, filters = {}) { |ctx| } # Generic handler
282
-
283
- # Handler types:
284
- # - :message
285
- # - :callback_query
286
- # - :inline_query
287
- # - :chat_member
288
- # - :poll
289
- # - :pre_checkout_query
290
- # - :shipping_query
291
- ```
170
+ · bot.scene(id, &block) - Defines a new scene with multiple steps.
171
+ · **ctx.enter_scene(scene_name, options) - Puts a user into a scene.
172
+ · ctx.leave_scene(options)** - Takes them out of it.
173
+ · ctx.session - A hash that automatically persists data for each user across different interactions. No setup required!
292
174
 
293
- Bot Control
175
+ Scene Example:
294
176
 
295
177
  ```ruby
296
- bot.start_polling(**options) # Start polling updates
297
- bot.webhook_server(**options) # Create webhook server
298
- bot.set_webhook(url, **options) # Set webhook URL
299
- bot.delete_webhook # Remove webhook
300
- bot.get_webhook_info # Get webhook status
301
- bot.shutdown # Graceful shutdown
302
- ```
178
+ bot.scene("order") do
179
+ step :ask_item do |ctx|
180
+ ctx.reply("What would you like to order?")
181
+ next_step :ask_quantity
182
+ end
303
183
 
304
- Error Handling
184
+ step :ask_quantity do |ctx|
185
+ ctx.state[:item] = ctx.message.text # Temp storage for this flow
186
+ ctx.reply("How many?")
187
+ next_step :confirm
188
+ end
305
189
 
306
- ```ruby
307
- # Global error handler
308
- bot.error do |error, ctx|
309
- ctx.reply "Oops: #{error.message}"
190
+ step :confirm do |ctx|
191
+ ctx.session[:last_order] = ctx.state[:item] # Save to persistent session
192
+ ctx.reply("Order placed for #{ctx.state[:item]}! Thanks.")
193
+ leave_scene
194
+ end
310
195
  end
311
- ```
312
-
313
- Scene Management
314
-
315
- ```ruby
316
- bot.scene(name, &block) # Define a scene
317
- bot.scenes # Hash of all scenes
318
- ```
319
-
320
- ---
321
-
322
- 📞 Telegram API Methods
323
-
324
- All methods below are available via ctx.api.call(method, params) or bot.api.call(method, params).
325
-
326
- Message Methods
327
-
328
- · sendMessage, sendPhoto, sendAudio, sendDocument
329
- · sendVideo, sendVoice, sendSticker, sendLocation
330
- · sendContact, sendPoll, sendDice, sendChatAction
331
- · sendMediaGroup, forwardMessage, copyMessage
332
- · editMessageText, editMessageCaption, editMessageMedia
333
- · editMessageReplyMarkup, deleteMessage, pinChatMessage
334
- · unpinChatMessage
335
-
336
- Chat Methods
337
-
338
- · getChat, getChatAdministrators, getChatMember
339
- · getChatMembersCount, banChatMember, unbanChatMember
340
- · restrictChatMember, promoteChatMember, setChatPermissions
341
- · exportChatInviteLink, createChatInviteLink, revokeChatInviteLink
342
- · approveChatJoinRequest, declineChatJoinRequest, setChatPhoto
343
- · deleteChatPhoto, setChatTitle, setChatDescription
344
- · setChatAdministratorCustomTitle, leaveChat
345
196
 
346
- Callback & Inline Methods
347
-
348
- · answerCallbackQuery, answerInlineQuery, answerWebAppQuery
349
-
350
- Webhook Methods
351
-
352
- · setWebhook, deleteWebhook, getWebhookInfo
353
-
354
- Update Methods
355
-
356
- · getUpdates
357
-
358
- User & Bot Methods
359
-
360
- · getMe, logOut, close
361
-
362
- ---
363
-
364
- 🎯 Common Options
365
-
366
- Message Options
367
-
368
- ```ruby
369
- {
370
- parse_mode: "HTML" | "Markdown" | "MarkdownV2",
371
- disable_web_page_preview: true,
372
- disable_notification: true,
373
- protect_content: true,
374
- reply_to_message_id: 123,
375
- allow_sending_without_reply: true,
376
- reply_markup: keyboard_object
377
- }
378
- ```
379
-
380
- Media Options
381
-
382
- ```ruby
383
- {
384
- caption: "Description",
385
- parse_mode: "HTML",
386
- duration: 60,
387
- width: 1920,
388
- height: 1080,
389
- thumb: input_file,
390
- supports_streaming: true
391
- }
392
- ```
393
-
394
- Chat Member Options
395
-
396
- ```ruby
397
- {
398
- until_date: Time.now + 3600, # Unix timestamp
399
- revoke_messages: true
400
- }
197
+ # Start the scene with a command
198
+ bot.command("pizza") { |ctx| ctx.enter_scene("order") }
401
199
  ```
402
200
 
403
201
  ---
404
202
 
405
- Error Types
203
+ Quick Reference Table
406
204
 
407
- ```ruby
408
- Telegem::Error # Base error
409
- Telegem::APIError # Telegram API errors
410
- Telegem::NetworkError # Network issues
411
- Telegem::ValidationError # Invalid parameters
412
- ```
413
-
414
- ---
415
-
416
- Last updated for Telegem v0.1.0
417
-
418
- ```
419
- ---
205
+ Category Key Methods What it's for
206
+ Setup new, start_polling, webhook, shutdown Creating, running, and stopping your bot.
207
+ Events on, command, hears, use, error Defining how your bot reacts to messages and errors.
208
+ Actions ctx.reply, ctx.photo, ctx.edit_message_text Sending and managing messages and media.
209
+ Chat ctx.get_chat, ctx.ban_chat_member, ctx.pin_message Getting info and managing groups/channels.
210
+ UI Telegem.keyboard, Telegem.inline Creating interactive buttons for users.
211
+ Flow bot.scene, ctx.session, ctx.enter_scene Managing complex user conversations and data.