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.
@@ -1,367 +0,0 @@
1
- Webhook Setup Guide for Telegem
2
-
3
- ๐Ÿ“– Overview
4
-
5
- This guide covers how to set up and run your Telegram bot using webhooks with Telegem. Webhooks are the preferred method for production bots as they provide faster response times and better reliability compared to polling.
6
-
7
- ๐Ÿš€ Quick Start (For Beginners)
8
-
9
- Basic Webhook Setup
10
-
11
- Here's the simplest way to get your bot running with webhooks:
12
-
13
- ```ruby
14
- # 1. Create your bot
15
- require 'telegem'
16
- bot = Telegem::Core::Bot.new('YOUR_BOT_TOKEN')
17
-
18
- # 2. Add your handlers
19
- bot.command('start') do |ctx|
20
- ctx.reply("Hello! I'm your bot.")
21
- end
22
-
23
- # 3. Start the webhook server
24
- server = bot.webhook
25
- server.run
26
- ```
27
-
28
- That's it! Your bot is now:
29
-
30
- ยท โœ… Listening for webhook requests
31
- ยท โœ… Using the default port (3000)
32
- ยท โœ… Available at /webhook/YOUR_BOT_TOKEN
33
-
34
- Deploying to Render
35
-
36
- For deploying to Render.com, here's your complete setup:
37
-
38
- 1. bot.rb or main.rb:
39
-
40
- ```ruby
41
- require 'telegem'
42
-
43
- # Initialize bot
44
- bot = Telegem::Core::Bot.new(ENV['BOT_TOKEN'])
45
-
46
- # Add your handlers
47
- bot.command('start') { |ctx| ctx.reply("Hello!") }
48
-
49
- # Start webhook server
50
- server = bot.webhook
51
- server.run
52
- ```
53
-
54
- 2. Gemfile:
55
-
56
- ```ruby
57
- source 'https://rubygems.org'
58
- gem 'telegem'
59
- ```
60
-
61
- 3. Render.com Settings:
62
-
63
- ยท Start Command: bundle exec ruby bot.rb
64
- ยท Environment Variables:
65
- ยท BOT_TOKEN: Your Telegram bot token
66
- ยท PORT: Automatically set by Render
67
-
68
- โš™๏ธ Configuration Options
69
-
70
- Using a Configuration Block
71
-
72
- Want to customize your webhook server? Use the block syntax:
73
-
74
- ```ruby
75
- server = bot.webhook do |config|
76
- config.port = 8080 # Custom port
77
- config.host = '0.0.0.0' # Bind to all interfaces
78
- config.logger = MyCustomLogger.new # Custom logger
79
- # No need to set endpoint - it's automatic!
80
- end
81
-
82
- server.run
83
- ```
84
-
85
- Environment Variables
86
-
87
- The server automatically reads these environment variables:
88
-
89
- Variable Purpose Default
90
- WEBHOOK_URL Full webhook URL for Telegram http://host:port/webhook/token
91
- PORT Server port 3000
92
- HOST Server host '0.0.0.0'
93
-
94
- ๐Ÿ”ง Advanced Configuration
95
-
96
- Custom Webhook Path
97
-
98
- Need a different webhook path? Here's how:
99
-
100
- ```ruby
101
- # Method 1: Set WEBHOOK_URL environment variable
102
- ENV['WEBHOOK_URL'] = 'https://your-domain.com/custom/path'
103
-
104
- # Method 2: Configure Telegram manually
105
- bot.set_webhook(
106
- url: 'https://your-domain.com/custom/path',
107
- max_connections: 40,
108
- allowed_updates: ['message', 'callback_query']
109
- )
110
- ```
111
-
112
- SSL/HTTPS Setup
113
-
114
- For production with SSL (required by Telegram for webhooks):
115
-
116
- ```ruby
117
- server = bot.webhook do |config|
118
- config.port = 443
119
- # SSL certificates (if running standalone)
120
- # config.ssl_certificate = '/path/to/cert.pem'
121
- # config.ssl_key = '/path/to/key.pem'
122
- end
123
-
124
- # Or use a reverse proxy (recommended):
125
- # - Nginx
126
- # - Cloudflare
127
- # - Render's built-in HTTPS
128
- ```
129
-
130
- Integration with Web Frameworks
131
-
132
- Integrate Telegem into your existing Rails or Sinatra app:
133
-
134
- ```ruby
135
- # For Rails: config/application.rb or config.ru
136
- require 'telegem'
137
-
138
- bot = Telegem::Core::Bot.new(ENV['BOT_TOKEN'])
139
-
140
- # Mount as middleware in config.ru:
141
- # use Telegem::Webhook::Middleware, bot
142
-
143
- # For Sinatra:
144
- require 'sinatra'
145
- require 'telegem'
146
-
147
- bot = Telegem::Core::Bot.new(ENV['BOT_TOKEN'])
148
- use Telegem::Webhook::Middleware, bot
149
-
150
- get '/' do
151
- "Main app is running!"
152
- end
153
- ```
154
-
155
- ๐Ÿšจ Troubleshooting
156
-
157
- Common Issues & Solutions
158
-
159
- 1. "Undefined method `run'" Error
160
-
161
- ```ruby
162
- # โŒ WRONG - Returns Middleware, not Server
163
- server = bot.webhook(app: something)
164
- server.run # ERROR!
165
-
166
- # โœ… CORRECT - Returns Server
167
- server = bot.webhook # No arguments
168
- server.run # WORKS!
169
- ```
170
-
171
- 2. Webhook Not Receiving Updates
172
-
173
- ```ruby
174
- # Check if webhook is set
175
- info = bot.get_webhook_info
176
- puts "Webhook URL: #{info.url}"
177
- puts "Has pending updates: #{info.pending_update_count}"
178
-
179
- # Set webhook if needed
180
- bot.set_webhook(url: 'https://your-domain.com/webhook/' + bot.token)
181
- ```
182
-
183
- 3. Port Already in Use
184
-
185
- ```ruby
186
- # Use a different port
187
- server = bot.webhook do |config|
188
- config.port = ENV['PORT'] || 3000 # Use Render's PORT
189
- end
190
- ```
191
-
192
- 4. Slow Response to Telegram
193
-
194
- ```ruby
195
- # The server responds immediately (200 OK)
196
- # then processes updates in background threads
197
- # This is NORMAL and by design!
198
- ```
199
-
200
- Debug Mode
201
-
202
- Enable detailed logging for troubleshooting:
203
-
204
- ```ruby
205
- require 'logger'
206
-
207
- logger = Logger.new(STDOUT)
208
- logger.level = Logger::DEBUG
209
-
210
- bot = Telegem::Core::Bot.new('TOKEN', logger: logger)
211
- server = bot.webhook do |config|
212
- config.logger = logger
213
- end
214
- ```
215
-
216
- ๐Ÿ“Š Production Best Practices
217
-
218
- 1. Health Checks
219
-
220
- The webhook server includes a built-in health endpoint:
221
-
222
- ```
223
- GET /health
224
- ```
225
-
226
- Returns 200 OK - use this for monitoring.
227
-
228
- 2. Error Handling
229
-
230
- ```ruby
231
- bot.error do |error, ctx|
232
- # Log to your error tracking service
233
- Sentry.capture_exception(error)
234
-
235
- # Optional: notify admin
236
- bot.api.send_message(
237
- chat_id: ADMIN_ID,
238
- text: "Bot error: #{error.message}"
239
- )
240
- end
241
- ```
242
-
243
- 3. Rate Limiting
244
-
245
- Consider adding rate limiting middleware:
246
-
247
- ```ruby
248
- class RateLimiter
249
- def initialize(bot, requests_per_minute: 60)
250
- @bot = bot
251
- @limits = {}
252
- end
253
-
254
- def call(ctx)
255
- user_id = ctx.from.id
256
- # Implement your rate limiting logic
257
- # ...
258
- yield # Continue to next middleware/handler
259
- end
260
- end
261
-
262
- bot.use RateLimiter
263
- ```
264
-
265
- 4. Monitoring
266
-
267
- Monitor these key metrics:
268
-
269
- ยท Response time to Telegram (< 1 second)
270
- ยท Error rate (< 1%)
271
- ยท Queue length (pending updates)
272
-
273
- ๐Ÿ”„ Webhook vs Polling
274
-
275
- Aspect Webhook Polling
276
- Performance Faster (real-time) Slower (up to 30s delay)
277
- Resource Use Efficient Constant requests
278
- Setup More complex Simple
279
- Production โœ… Recommended Only for dev/testing
280
- Render.com Web Service Background Worker
281
-
282
- ```ruby
283
- # Switching between methods is easy:
284
- if ENV['RACK_ENV'] == 'production'
285
- # Use webhooks in production
286
- bot.webhook.run
287
- else
288
- # Use polling in development
289
- bot.start_polling
290
- sleep # Keep process alive
291
- end
292
- ```
293
-
294
- ๐ŸŽฏ Example: Complete Production Setup
295
-
296
- ```ruby
297
- # production_bot.rb
298
- require 'telegem'
299
- require 'logger'
300
-
301
- # Configure bot
302
- bot = Telegem::Core::Bot.new(
303
- ENV['BOT_TOKEN'],
304
- logger: Logger.new('logs/bot.log', 'daily')
305
- )
306
-
307
- # Add middleware
308
- bot.use MyAuthMiddleware
309
- bot.use RateLimiter
310
-
311
- # Add handlers
312
- bot.command('start') { |ctx| ctx.reply("Welcome!") }
313
- # ... more handlers
314
-
315
- # Error handling
316
- bot.error do |error, ctx|
317
- logger.error("Error: #{error.message}")
318
- ctx&.reply("Sorry, something went wrong!")
319
- end
320
-
321
- # Get Render's port or use default
322
- port = ENV['PORT'] || 3000
323
-
324
- # Start server
325
- server = bot.webhook do |config|
326
- config.port = port
327
- config.host = '0.0.0.0'
328
- end
329
-
330
- puts "๐Ÿš€ Starting bot on port #{port}"
331
- puts "๐Ÿ“ก Webhook URL: #{server.webhook_url}"
332
- server.run
333
- ```
334
-
335
- โ“ FAQ
336
-
337
- Q: What port should I use?
338
- A: Use ENV['PORT'] on Render/Heroku, or 3000 for local development.
339
-
340
- Q: Do I need to call set_webhook?
341
- A: Not with Telegem! It sets the webhook automatically when you call server.webhook_url.
342
-
343
- Q: Can I run multiple bots?
344
- A: Yes! Each needs its own server instance on a different port.
345
-
346
- Q: How do I handle bot restarts?
347
- A: The server gracefully shuts down on SIGTERM. Set restart: always in your deployment config.
348
-
349
- Q: My bot stops after some time?
350
- A: On Render's free tier, services sleep after inactivity. Upgrade to a paid plan for 24/7 uptime.
351
-
352
- ๐Ÿ“š Additional Resources
353
-
354
- ยท Telegram Bot API Documentation
355
- ยท Render.com Deployment Guide
356
- ยท Telegem GitHub Repository
357
- ยท Webhook vs Polling Explained
358
-
359
- ---
360
-
361
- Need Help?
362
-
363
- ยท Check the server logs: tail -f logs/bot.log
364
- ยท Verify webhook URL with bot.get_webhook_info
365
- ยท Test locally with ngrok: ngrok http 3000
366
-
367
- Happy bot building! ๐Ÿค–
@@ -1,241 +0,0 @@
1
- ๐Ÿ“ก Setting Up Webhooks - Complete Beginner's Guide
2
-
3
- Webhooks sound complicated, but they're actually simple. Let me explain with an analogy:
4
-
5
- ๐Ÿ• The Pizza Delivery Analogy
6
-
7
- Polling (The Old Way)
8
-
9
- You call the pizza shop every minute: "Is my pizza ready yet? No? OK, I'll call again in a minute..."
10
-
11
- Code: bot.start_polling() - Your bot calls Telegram every second asking for new messages.
12
-
13
- Webhooks (The Smart Way)
14
-
15
- You give the pizza shop your address. When pizza is ready, they deliver it to you.
16
-
17
- Code: bot.set_webhook(url) - You give Telegram your server's address. When there's a message, they send it to you.
18
-
19
- ๐Ÿš€ Quick Examples
20
-
21
- Example 1: Polling (Easiest for Beginners)
22
-
23
- ```ruby
24
- require 'telegem'
25
-
26
- bot = Telegem.new('YOUR_TOKEN')
27
-
28
- bot.command('start') do |ctx|
29
- ctx.reply("Hello! I'm using polling ๐Ÿ•")
30
- end
31
-
32
- # Just ONE line - that's it!
33
- bot.start_polling
34
- ```
35
-
36
- Run it:
37
-
38
- ```bash
39
- ruby bot.rb
40
- # Bot starts checking for messages every second
41
- ```
42
-
43
- Example 2: Webhook (For Production)
44
-
45
- ```ruby
46
- require 'telegem'
47
-
48
- bot = Telegem.new('YOUR_TOKEN')
49
-
50
- bot.command('start') do |ctx|
51
- ctx.reply("Hello! I'm using webhooks ๐Ÿšš")
52
- end
53
-
54
- # Step 1: Start your "delivery address" (server)
55
- server = bot.webhook(port: 3000)
56
- server.run
57
-
58
- # Step 2: Tell Telegram your address
59
- bot.set_webhook!("https://your-domain.com/webhook/#{bot.token}")
60
- ```
61
-
62
- Run it:
63
-
64
- ```bash
65
- ruby bot.rb
66
- # Bot waits for Telegram to deliver messages
67
- ```
68
-
69
- ๐Ÿ”„ Hot-Swap Between Polling & Webhooks
70
-
71
- Here's how to switch while your bot is running:
72
-
73
- ```ruby
74
- require 'telegem'
75
-
76
- bot = Telegem.new('YOUR_TOKEN')
77
-
78
- bot.command('mode') do |ctx|
79
- ctx.reply("Use /polling or /webhook to switch modes")
80
- end
81
-
82
- bot.command('polling') do |ctx|
83
- # Switch TO polling
84
- bot.shutdown # Stop current mode
85
- bot.start_polling # Start polling
86
- ctx.reply("โœ… Switched to polling mode")
87
- end
88
-
89
- bot.command('webhook') do |ctx|
90
- # Switch TO webhook
91
- bot.shutdown # Stop current mode
92
-
93
- server = bot.webhook(port: 3000)
94
- server.run
95
-
96
- # For demo, use ngrok URL (get yours at ngrok.com)
97
- bot.set_webhook!("https://abc123.ngrok.io/webhook/#{bot.token}")
98
-
99
- ctx.reply("โœ… Switched to webhook mode")
100
- end
101
-
102
- # Start with polling by default
103
- bot.start_polling
104
- ```
105
-
106
- ๐Ÿ“Š Polling vs Webhooks: Side-by-Side Comparison
107
-
108
- |Polling ๐Ÿ•| Webhooks ๐Ÿšš |
109
- | ------- | ------- |
110
- | Bot asks Telegram: "New messages?" | Telegram sends messages to bot |
111
- | Setup bot.start_polling() | Server + set_webhook() |
112
- | Best for Development, testing | Production, high traffic |
113
- | Speed Up to 1-second delay | Instant delivery |
114
- | SSL Required? โŒ No | โœ… Yes (Telegram requires HTTPS) |
115
- | Server Needed? โŒ No | โœ… Yes |
116
- | Battery/CPU โš ๏ธ Uses more (always checking) | โœ… Efficient (sleeps until delivery) |
117
- | Can Switch? โœ… Yes (hot-swap) | โœ… Yes (hot-swap) |
118
-
119
- ๐ŸŽฏ When to Use Which?
120
-
121
- Use Polling When:
122
-
123
- ยท ๐Ÿ‘ถ You're learning - Keep it simple
124
- ยท ๐Ÿ’ป Developing locally - No server setup needed
125
- ยท ๐Ÿงช Testing new features - Quick restarts
126
- ยท ๐Ÿ“ฑ Running on your laptop - No public URL needed
127
-
128
- Use Webhooks When:
129
-
130
- ยท ๐Ÿš€ Going to production - Better performance
131
- ยท ๐Ÿ“ˆ Expecting many users - Handles traffic better
132
- ยท โ˜๏ธ Hosting on a server - You have a public URL
133
- ยท ๐Ÿ”‹ Saving resources - Uses less CPU/battery
134
-
135
- ๐Ÿ”ง Webhook Setup for Beginners
136
-
137
- Step 1: Get a Public URL (Development)
138
-
139
- For development, use ngrok (free):
140
-
141
- ```bash
142
- # Install ngrok, then run:
143
- ngrok http 3000
144
- ```
145
-
146
- You'll get a URL like: https://abc123.ngrok.io
147
-
148
- Step 2: Simple Webhook Bot
149
-
150
- ```ruby
151
- # webhook_bot.rb
152
- require 'telegem'
153
-
154
- bot = Telegem.new('YOUR_TOKEN')
155
-
156
- bot.command('start') do |ctx|
157
- ctx.reply("I'm using webhooks! Try /info")
158
- end
159
-
160
- bot.command('info') do |ctx|
161
- info = bot.get_webhook_info!
162
- ctx.reply("Webhook info: #{info}")
163
- end
164
-
165
- # Start server
166
- server = bot.webhook(port: 3000)
167
- server.run
168
-
169
- puts "๐Ÿš€ Server running! Set webhook to:"
170
- puts "https://YOUR_NGROK_URL.ngrok.io/webhook/#{bot.token}"
171
- puts ""
172
- puts "Run this command to set webhook:"
173
- puts "bot.set_webhook!('https://YOUR_NGROK_URL.ngrok.io/webhook/#{bot.token}')"
174
- ```
175
-
176
- Step 3: Set the Webhook
177
-
178
- Open IRB in another terminal:
179
-
180
- ```ruby
181
- require 'telegem'
182
- bot = Telegem.new('YOUR_TOKEN')
183
- bot.set_webhook!('https://abc123.ngrok.io/webhook/YOUR_TOKEN')
184
- # => true (means success!)
185
- ```
186
-
187
- โ“ Common Questions
188
-
189
- "Do I need to keep my computer on?"
190
-
191
- ยท Polling: โŒ Yes, bot must keep asking
192
- ยท Webhook: โœ… No, your SERVER needs to be on
193
-
194
- "Can I use webhook without a server?"
195
-
196
- No, you need somewhere for Telegram to deliver messages. But many free options:
197
-
198
- ยท Railway (free tier) - railway.app
199
- ยท Render (free tier) - render.com
200
- ยท Heroku (free tier) - heroku.com
201
-
202
- "Which is faster?"
203
-
204
- Webhooks! Messages arrive instantly instead of up to 1-second delay.
205
-
206
- ๐ŸŽฎ Try It Yourself Exercise
207
-
208
- Create mode_demo.rb:
209
-
210
- ```ruby
211
- require 'telegem'
212
-
213
- bot = Telegem.new('YOUR_TOKEN')
214
-
215
- bot.command('help') do |ctx|
216
- ctx.reply(<<~TEXT
217
- ๐Ÿค– Mode Demo Bot
218
-
219
- /polling - Switch to polling mode
220
- /webhook - Switch to webhook mode
221
- /current - Show current mode
222
- /test - Send test message
223
- TEXT
224
- )
225
- end
226
-
227
- # Start in polling mode (easiest)
228
- bot.start_polling
229
- puts "Bot started in polling mode. Try /help"
230
- ```
231
-
232
- Run it and try switching modes while the bot is running!
233
-
234
- ๐Ÿ“š Remember This:
235
-
236
- ยท Start with polling - It's easier
237
- ยท Switch to webhooks when going to production
238
- ยท You can always switch back - It's not permanent
239
- ยท Your bot code stays the same - Only the delivery method changes
240
-
241
- Happy bot building! ๐ŸŽ‰