telegem 3.3.0 → 3.4.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.
@@ -0,0 +1,574 @@
1
+ # Troubleshooting
2
+
3
+ Common issues and solutions when working with Telegem bots.
4
+
5
+ ## Bot Not Responding
6
+
7
+ ### Check Bot Token
8
+
9
+ **Problem:** Bot doesn't respond to messages.
10
+
11
+ **Symptoms:**
12
+ - Commands are sent but no response
13
+ - Bot appears offline
14
+
15
+ **Solutions:**
16
+
17
+ 1. **Verify token validity:**
18
+ ```ruby
19
+ # Test token
20
+ bot = Telegem.new(token: 'YOUR_TOKEN')
21
+ me = bot.api.call('getMe')
22
+ puts me.inspect
23
+ ```
24
+
25
+ 2. **Check token format:**
26
+ - Should start with bot ID
27
+ - Format: `123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11`
28
+
29
+ 3. **Ensure bot is not blocked:**
30
+ - Check @BotFather for bot status
31
+ - Verify token hasn't expired
32
+
33
+ ### Check Polling/Webhook Setup
34
+
35
+ **Problem:** Bot receives messages but doesn't process them.
36
+
37
+ **For Polling:**
38
+ ```ruby
39
+ bot = Telegem.new(token: 'YOUR_TOKEN')
40
+
41
+ # Add debug logging
42
+ bot.logger = Logger.new(STDOUT)
43
+ bot.logger.level = Logger::DEBUG
44
+
45
+ bot.command('test') do |ctx|
46
+ ctx.reply('Working!')
47
+ end
48
+
49
+ bot.start_polling
50
+ ```
51
+
52
+ **For Webhooks:**
53
+ ```ruby
54
+ # Check webhook info
55
+ webhook_info = bot.api.call('getWebhookInfo')
56
+ puts webhook_info.inspect
57
+
58
+ # Delete webhook if needed
59
+ bot.api.call('deleteWebhook')
60
+
61
+ # Then start polling
62
+ bot.start_polling
63
+ ```
64
+
65
+ ### Check Network Connectivity
66
+
67
+ **Problem:** Connection issues to Telegram API.
68
+
69
+ **Test connectivity:**
70
+ ```ruby
71
+ require 'net/http'
72
+
73
+ uri = URI('https://api.telegram.org/botYOUR_TOKEN/getMe')
74
+ response = Net::HTTP.get(uri)
75
+ puts response
76
+ ```
77
+
78
+ **Common issues:**
79
+ - Firewall blocking outbound connections
80
+ - DNS resolution problems
81
+ - Proxy configuration needed
82
+
83
+ ## Handler Not Triggering
84
+
85
+ ### Command Handler Issues
86
+
87
+ **Problem:** `/command` doesn't work.
88
+
89
+ **Check:**
90
+ 1. **Command registration:**
91
+ ```ruby
92
+ bot.command('test') do |ctx|
93
+ puts "Command received" # Add debug
94
+ ctx.reply('Working!')
95
+ end
96
+ ```
97
+
98
+ 2. **Command format:**
99
+ - Must start with `/`
100
+ - Case-sensitive
101
+ - No spaces in command name
102
+
103
+ 3. **Bot permissions:**
104
+ - Bot must be added to chat
105
+ - Bot must have message reading permissions
106
+
107
+ ### Hears Handler Issues
108
+
109
+ **Problem:** Pattern matching doesn't work.
110
+
111
+ **Check regex patterns:**
112
+ ```ruby
113
+ # Test pattern
114
+ pattern = /^hello/
115
+ text = "hello world"
116
+ puts pattern.match?(text) # Should be true
117
+
118
+ bot.hears(/^hello/) do |ctx|
119
+ ctx.reply('Hi!')
120
+ end
121
+ ```
122
+
123
+ **Common mistakes:**
124
+ - Forgetting word boundaries: `/^hello/` vs `/hello/`
125
+ - Case sensitivity: `/hello/i` for case-insensitive
126
+ - Special characters need escaping
127
+
128
+ ### Callback Query Issues
129
+
130
+ **Problem:** Inline keyboard buttons don't work.
131
+
132
+ **Check:**
133
+ 1. **Callback data format:**
134
+ ```ruby
135
+ bot.callback_query('button1') do |ctx|
136
+ ctx.answer_callback_query('Clicked!')
137
+ end
138
+ ```
139
+
140
+ 2. **Button setup:**
141
+ ```ruby
142
+ keyboard = Telegem.inline_keyboard do |kb|
143
+ kb.button('Click me', callback_data: 'button1')
144
+ end
145
+ ```
146
+
147
+ 3. **Message ownership:**
148
+ - Callback queries only work for messages sent by the bot
149
+
150
+ ## Session Issues
151
+
152
+ ### Session Not Persisting
153
+
154
+ **Problem:** Session data lost between messages.
155
+
156
+ **Check middleware setup:**
157
+ ```ruby
158
+ # Ensure middleware is loaded
159
+ bot.use Telegem::Session::Middleware.new
160
+
161
+ # Use memory store for testing
162
+ bot.session_store = Telegem::Session::MemoryStore.new
163
+ ```
164
+
165
+ **For Redis:**
166
+ ```ruby
167
+ require 'redis'
168
+ bot.session_store = Telegem::Session::RedisStore.new(ENV['REDIS_URL'])
169
+ ```
170
+
171
+ ### Session Store Errors
172
+
173
+ **Problem:** Database connection issues.
174
+
175
+ **Check connection:**
176
+ ```ruby
177
+ begin
178
+ bot.session_store.test_connection
179
+ puts "Session store connected"
180
+ rescue => e
181
+ puts "Session store error: #{e.message}"
182
+ end
183
+ ```
184
+
185
+ ## API Errors
186
+
187
+ ### Rate Limiting
188
+
189
+ **Problem:** `429 Too Many Requests` errors.
190
+
191
+ **Solutions:**
192
+ 1. **Implement rate limiting:**
193
+ ```ruby
194
+ bot.use do |ctx, next_middleware|
195
+ # Simple rate limit
196
+ user_id = ctx.from.id
197
+ key = "rate_limit:#{user_id}"
198
+
199
+ if bot.session_store.get(key)
200
+ ctx.reply('Please wait before sending another message')
201
+ return
202
+ end
203
+
204
+ bot.session_store.set(key, '1', ttl: 1) # 1 second limit
205
+ next_middleware.call(ctx)
206
+ end
207
+ ```
208
+
209
+ 2. **Use exponential backoff:**
210
+ ```ruby
211
+ def api_call_with_retry(method, params, retries = 3)
212
+ begin
213
+ bot.api.call(method, params)
214
+ rescue Telegem::API::APIError => e
215
+ if e.code == 429 && retries > 0
216
+ sleep_time = 2 ** (4 - retries) # Exponential backoff
217
+ sleep(sleep_time)
218
+ api_call_with_retry(method, params, retries - 1)
219
+ else
220
+ raise
221
+ end
222
+ end
223
+ end
224
+ ```
225
+
226
+ ### Invalid Parameters
227
+
228
+ **Problem:** `400 Bad Request` errors.
229
+
230
+ **Common causes:**
231
+ - Invalid chat_id
232
+ - Malformed message text
233
+ - Unsupported file format
234
+ - Missing required parameters
235
+
236
+ **Debug:**
237
+ ```ruby
238
+ begin
239
+ result = bot.api.call('sendMessage', chat_id: chat_id, text: text)
240
+ rescue Telegem::API::APIError => e
241
+ puts "API Error: #{e.message}"
242
+ puts "Chat ID: #{chat_id}"
243
+ puts "Text: #{text.inspect}"
244
+ end
245
+ ```
246
+
247
+ ### File Upload Issues
248
+
249
+ **Problem:** File sending fails.
250
+
251
+ **Check:**
252
+ 1. **File size limits:**
253
+ - Documents: 20MB
254
+ - Photos: 10MB
255
+ - Videos: 50MB
256
+
257
+ 2. **File format:**
258
+ ```ruby
259
+ # Check file type
260
+ file_path = '/path/to/file'
261
+ mime_type = `file --mime-type -b #{file_path}`.strip
262
+
263
+ # Send appropriate type
264
+ if mime_type.start_with?('image/')
265
+ bot.api.call('sendPhoto', chat_id: chat_id, photo: File.open(file_path))
266
+ elsif mime_type.start_with?('video/')
267
+ bot.api.call('sendVideo', chat_id: chat_id, video: File.open(file_path))
268
+ else
269
+ bot.api.call('sendDocument', chat_id: chat_id, document: File.open(file_path))
270
+ end
271
+ ```
272
+
273
+ ## Webhook Issues
274
+
275
+ ### Webhook Not Receiving Updates
276
+
277
+ **Problem:** Webhook URL not getting requests.
278
+
279
+ **Check:**
280
+ 1. **URL accessibility:**
281
+ ```bash
282
+ curl -X POST https://your-domain.com/webhook \
283
+ -H "Content-Type: application/json" \
284
+ -d '{"update_id": 1}'
285
+ ```
286
+
287
+ 2. **SSL certificate:**
288
+ ```bash
289
+ openssl s_client -connect your-domain.com:443 -servername your-domain.com
290
+ ```
291
+
292
+ 3. **Webhook registration:**
293
+ ```ruby
294
+ webhook_info = bot.api.call('getWebhookInfo')
295
+ puts webhook_info.inspect
296
+ ```
297
+
298
+ ### Webhook Server Errors
299
+
300
+ **Problem:** Webhook server crashes.
301
+
302
+ **Check logs:**
303
+ ```ruby
304
+ # Add error handling
305
+ bot.error do |error, ctx|
306
+ puts "Error: #{error.message}"
307
+ puts error.backtrace
308
+ end
309
+ ```
310
+
311
+ **Common issues:**
312
+ - Port already in use
313
+ - SSL certificate problems
314
+ - Memory leaks in handlers
315
+
316
+ ## Scene Issues
317
+
318
+ ### Scene Not Starting
319
+
320
+ **Problem:** `enter_scene` doesn't work.
321
+
322
+ **Check:**
323
+ 1. **Scene definition:**
324
+ ```ruby
325
+ bot.scene('test_scene') do |scene|
326
+ scene.step('step1') do |ctx|
327
+ # Handler code
328
+ end
329
+ end
330
+ ```
331
+
332
+ 2. **Scene entry:**
333
+ ```ruby
334
+ bot.command('start_scene') do |ctx|
335
+ ctx.enter_scene('test_scene')
336
+ end
337
+ ```
338
+
339
+ ### Scene State Lost
340
+
341
+ **Problem:** Scene progress lost.
342
+
343
+ **Check session persistence:**
344
+ ```ruby
345
+ # Ensure session middleware
346
+ bot.use Telegem::Session::Middleware.new
347
+
348
+ # Check session data
349
+ bot.command('debug') do |ctx|
350
+ puts ctx.session.inspect
351
+ end
352
+ ```
353
+
354
+ ## Performance Issues
355
+
356
+ ### High Memory Usage
357
+
358
+ **Problem:** Bot consumes too much memory.
359
+
360
+ **Check:**
361
+ 1. **Session cleanup:**
362
+ ```ruby
363
+ # Clear old sessions
364
+ bot.session_store.cleanup_expired
365
+ ```
366
+
367
+ 2. **File handling:**
368
+ ```ruby
369
+ # Don't load large files into memory
370
+ File.open('large_file') do |file|
371
+ bot.api.call('sendDocument', chat_id: chat_id, document: file)
372
+ end
373
+ ```
374
+
375
+ ### Slow Response Times
376
+
377
+ **Problem:** Bot responds slowly.
378
+
379
+ **Profile code:**
380
+ ```ruby
381
+ require 'ruby-prof'
382
+
383
+ bot.command('profile') do |ctx|
384
+ RubyProf.start
385
+
386
+ # Your code here
387
+
388
+ result = RubyProf.stop
389
+ printer = RubyProf::FlatPrinter.new(result)
390
+ printer.print(STDOUT)
391
+ end
392
+ ```
393
+
394
+ **Common bottlenecks:**
395
+ - Database queries
396
+ - File processing
397
+ - External API calls
398
+
399
+ ## Deployment Issues
400
+
401
+ ### Environment Variables
402
+
403
+ **Problem:** Configuration not loading.
404
+
405
+ **Check:**
406
+ ```bash
407
+ # Print environment
408
+ puts ENV['TELEGRAM_BOT_TOKEN'] ? 'Token set' : 'Token missing'
409
+ puts ENV['REDIS_URL'] ? 'Redis set' : 'Redis missing'
410
+ ```
411
+
412
+ ### Process Management
413
+
414
+ **Problem:** Bot stops unexpectedly.
415
+
416
+ **Check logs:**
417
+ ```bash
418
+ # Systemd logs
419
+ journalctl -u telegem-bot -f
420
+
421
+ # Process status
422
+ ps aux | grep telegem
423
+ ```
424
+
425
+ **Add monitoring:**
426
+ ```ruby
427
+ # Health check endpoint
428
+ bot.get('/health') do |ctx|
429
+ ctx.response.body = {
430
+ status: 'ok',
431
+ uptime: Time.now - START_TIME,
432
+ memory: `ps -o rss= -p #{Process.pid}`.to_i
433
+ }.to_json
434
+ end
435
+ ```
436
+
437
+ ## Plugin Issues
438
+
439
+ ### Plugin Loading Errors
440
+
441
+ **Problem:** Plugin fails to load.
442
+
443
+ **Check dependencies:**
444
+ ```ruby
445
+ begin
446
+ require 'telegem/plugins/file_extract'
447
+ rescue LoadError => e
448
+ puts "Plugin dependency missing: #{e.message}"
449
+ # Install missing gems
450
+ end
451
+ ```
452
+
453
+ ### Plugin Runtime Errors
454
+
455
+ **Problem:** Plugin throws exceptions.
456
+
457
+ **Add error handling:**
458
+ ```ruby
459
+ bot.document do |ctx|
460
+ begin
461
+ extractor = Telegem::Plugins::FileExtract.new(ctx.bot, ctx.message.document.file_id)
462
+ result = extractor.extract
463
+ # Process result
464
+ rescue => e
465
+ ctx.logger.error("Plugin error: #{e.message}")
466
+ ctx.reply("File processing failed")
467
+ end
468
+ end
469
+ ```
470
+
471
+ ## Testing Issues
472
+
473
+ ### Test Failures
474
+
475
+ **Problem:** Tests don't pass.
476
+
477
+ **Check:**
478
+ 1. **Mock setup:**
479
+ ```ruby
480
+ # Ensure API is mocked
481
+ allow(bot.api).to receive(:call).and_return({'ok' => true})
482
+ ```
483
+
484
+ 2. **Async operations:**
485
+ ```ruby
486
+ # Wait for async completion
487
+ sleep 0.1
488
+ ```
489
+
490
+ ### Coverage Issues
491
+
492
+ **Problem:** Low test coverage.
493
+
494
+ **Check uncovered code:**
495
+ ```ruby
496
+ # Run with coverage
497
+ bundle exec rspec --format html
498
+ ```
499
+
500
+ ## Common Error Messages
501
+
502
+ ### "Bot token is required"
503
+
504
+ **Cause:** Token not provided or invalid.
505
+
506
+ **Fix:**
507
+ ```ruby
508
+ bot = Telegem.new(token: ENV['TELEGRAM_BOT_TOKEN'])
509
+ ```
510
+
511
+ ### "Invalid bot token"
512
+
513
+ **Cause:** Malformed token.
514
+
515
+ **Fix:** Get new token from @BotFather.
516
+
517
+ ### "Chat not found"
518
+
519
+ **Cause:** Invalid chat_id.
520
+
521
+ **Fix:** Use correct chat ID or username.
522
+
523
+ ### "Message is too long"
524
+
525
+ **Cause:** Message exceeds 4096 characters.
526
+
527
+ **Fix:** Split long messages.
528
+
529
+ ### "Bad Request: query is too old"
530
+
531
+ **Cause:** Callback query answered too late.
532
+
533
+ **Fix:** Answer callback queries immediately.
534
+
535
+ ### "Conflict: terminated by other getUpdates request"
536
+
537
+ **Cause:** Multiple polling instances.
538
+
539
+ **Fix:** Stop other bot instances.
540
+
541
+ ## Getting Help
542
+
543
+ 1. **Check documentation:** Review docs/ folder
544
+ 2. **Search issues:** Check GitHub issues
545
+ 3. **Enable debug logging:**
546
+ ```ruby
547
+ bot.logger.level = Logger::DEBUG
548
+ ```
549
+ 4. **Test with minimal code:**
550
+ ```ruby
551
+ # Minimal test bot
552
+ bot = Telegem.new(token: 'YOUR_TOKEN')
553
+ bot.command('test') { |ctx| ctx.reply('OK') }
554
+ bot.start_polling
555
+ ```
556
+ 5. **Check Telegram Bot API status:** https://t.me/botapiupdates
557
+
558
+ ## Debug Checklist
559
+
560
+ - [ ] Bot token is valid
561
+ - [ ] Network connectivity works
562
+ - [ ] Handlers are registered
563
+ - [ ] Session middleware loaded
564
+ - [ ] Error handlers implemented
565
+ - [ ] Logs enabled
566
+ - [ ] Dependencies installed
567
+ - [ ] Environment variables set
568
+ - [ ] No conflicting processes
569
+ - [ ] SSL certificates valid (webhooks)
570
+ - [ ] Rate limits not exceeded
571
+ - [ ] File size limits respected
572
+
573
+ Use this checklist when debugging issues.</content>
574
+ <parameter name="filePath">/home/slick/telegem/docs/troubleshooting.md