telegem 3.4.0 → 3.6.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.
data/docs/webhooks.md CHANGED
@@ -1,12 +1,91 @@
1
- # Webhook Deployment
1
+ # Webhook Deployment Guide
2
2
 
3
- Webhooks provide production-ready deployment for Telegram bots. Unlike polling, webhooks push updates instantly and scale better.
3
+ ## What Are Webhooks?
4
+
5
+ Webhooks are a way to receive updates from Telegram **in real-time**. Instead of constantly asking Telegram "do you have any messages for me?", webhooks let Telegram push messages directly to your server when they arrive.
6
+
7
+ ### Polling vs Webhooks
8
+
9
+ **Polling (Old Way):**
10
+ - Your bot repeatedly asks Telegram for updates
11
+ - Slower response time (delays between checks)
12
+ - Higher resource usage
13
+ - Simpler to set up
14
+
15
+ **Webhooks (Modern Way):**
16
+ - Telegram sends updates to your server immediately
17
+ - Instant message delivery
18
+ - More efficient (only send when needed)
19
+ - Requires HTTPS and public server
20
+
21
+ ## Quick Start for Beginners
22
+
23
+ ### What You Need
24
+
25
+ 1. A Telegram bot token (from @BotFather)
26
+ 2. A server with a public domain (or use cloud platforms)
27
+ 3. HTTPS enabled (let's encrypt is free!)
28
+ 4. 5 minutes of setup time
29
+
30
+ ### 60-Second Setup
31
+
32
+ ```bash
33
+ # 1. Create your bot file (bot.rb)
34
+ echo 'require "telegem"
35
+
36
+ bot = Telegem.new(ENV["BOT_TOKEN"])
37
+
38
+ bot.command("start") do |ctx|
39
+ ctx.reply("Hello from webhooks!")
40
+ end
41
+
42
+ server = bot.webhook(port: 3000)
43
+ server.run' > bot.rb
44
+
45
+ # 2. Deploy to Railway, Render, or Heroku (they handle HTTPS)
46
+ # 3. Set the webhook URL
47
+ ruby -e "
48
+ require 'telegem'
49
+ bot = Telegem.new(ENV['BOT_TOKEN'])
50
+ bot.set_webhook(url: 'https://your-domain.com/YOUR_BOT_TOKEN')
51
+ "
52
+
53
+ # 4. Done! Your bot is now live
54
+ ```
4
55
 
5
56
  ## How Webhooks Work
6
57
 
7
- 1. Telegram sends updates to your server URL
8
- 2. Server processes updates and responds
9
- 3. No need to constantly poll for updates
58
+ Here's what happens when a user sends a message:
59
+
60
+ 1. **User sends message** Telegram receives it
61
+ 2. **Telegram sends HTTP POST** → Sends data to your webhook URL
62
+ 3. **Your server processes** → Handles the message with your bot logic
63
+ 4. **Send response** → Returns "OK" to confirm
64
+ 5. **Telegram updates user** → Shows bot's reply
65
+
66
+ ```
67
+ ┌─────────────────────────────────────────────────────┐
68
+ │ User sends message to bot on Telegram │
69
+ └────────────────────┬────────────────────────────────┘
70
+
71
+
72
+ ┌─────────────────────────────────────────────────────┐
73
+ │ Telegram sends HTTP POST to: https://yourdomain.com │
74
+ │ with JSON: {message_id: 123, text: "hello", ...} │
75
+ └────────────────────┬────────────────────────────────┘
76
+
77
+
78
+ ┌─────────────────────────────────────────────────────┐
79
+ │ Your webhook server receives request │
80
+ │ Processes message with your bot handlers │
81
+ │ Sends reply back to Telegram │
82
+ └────────────────────┬────────────────────────────────┘
83
+
84
+
85
+ ┌─────────────────────────────────────────────────────┐
86
+ │ Telegram delivers reply to user │
87
+ └─────────────────────────────────────────────────────┘
88
+ ```
10
89
 
11
90
  ## Basic Webhook Setup
12
91
 
@@ -44,6 +123,320 @@ end
44
123
 
45
124
  ## Production Deployment
46
125
 
126
+ This section shows how to deploy your bot to real servers that stay running 24/7.
127
+
128
+ ### Option 1: Free Cloud Hosting (Easiest for Beginners)
129
+
130
+ **Recommended platforms** (all free tier available):
131
+ - **Railway** - Simple, fast, free tier
132
+ - **Render** - Good free tier, auto-deploys from GitHub
133
+ - **Heroku** - Very popular, free tier removed but still a good option
134
+ - **Replit** - Great for learning, free tier
135
+
136
+ #### Railway Deployment (Easiest!)
137
+
138
+ 1. **Create a simple bot file** (`bot.rb`):
139
+
140
+ ```ruby
141
+ require 'telegem'
142
+
143
+ bot = Telegem.new(ENV['BOT_TOKEN'])
144
+
145
+ # Your bot handlers here
146
+ bot.command('start') do |ctx|
147
+ ctx.reply("Hey #{ctx.from.first_name}!")
148
+ end
149
+
150
+ bot.command('help') do |ctx|
151
+ ctx.reply("Commands: /start, /help")
152
+ end
153
+
154
+ # Start webhook server (Railway provides free HTTPS!)
155
+ server = bot.webhook(port: ENV['PORT'] || 3000)
156
+ server.run
157
+ ```
158
+
159
+ 2. **Create a Gemfile**:
160
+
161
+ ```ruby
162
+ source 'https://rubygems.org'
163
+
164
+ gem 'telegem'
165
+ ```
166
+
167
+ 3. **Deploy to Railway**:
168
+
169
+ ```bash
170
+ # Login to Railway
171
+ npm install -g railway # or use web interface at railway.app
172
+
173
+ # Deploy
174
+ railway up
175
+
176
+ # Or: Push to GitHub and Railway auto-deploys
177
+ git push origin main
178
+ ```
179
+
180
+ 4. **Set webhook URL** (in your bot code or manually):
181
+
182
+ ```bash
183
+ # Once deployed, get your Railway URL
184
+ # Then set webhook:
185
+ curl "https://api.telegram.org/botYOUR_BOT_TOKEN/setWebhook" \
186
+ -d "url=https://your-railway-url/YOUR_BOT_TOKEN"
187
+ ```
188
+
189
+ #### Render Deployment
190
+
191
+ 1. **Push code to GitHub**
192
+
193
+ 2. **Go to** https://dashboard.render.com
194
+
195
+ 3. **Click "New" - "Web Service"**
196
+
197
+ 4. **Connect your GitHub repository**
198
+
199
+ 5. **Configure**:
200
+ - Environment: Ruby
201
+ - Build command: `bundle install`
202
+ - Start command: `ruby bot.rb`
203
+ - Add environment variable: `BOT_TOKEN` (your actual token)
204
+
205
+ 6. **Deploy!** Render automatically sets HTTPS and your bot is live
206
+
207
+ ### Option 2: Self-Hosted Server (Good if you have a server)
208
+
209
+ If you have your own server (VPS, dedicated host, etc.):
210
+
211
+ **Step 1: SSH into your server**
212
+
213
+ ```bash
214
+ ssh user@your-server.com
215
+ ```
216
+
217
+ **Step 2: Install Ruby**
218
+
219
+ ```bash
220
+ # For Ubuntu/Debian
221
+ sudo apt update
222
+ sudo apt install ruby-full build-essential
223
+
224
+ # For CentOS/RHEL
225
+ sudo yum install ruby
226
+ ```
227
+
228
+ **Step 3: Setup your bot directory**
229
+
230
+ ```bash
231
+ mkdir -p ~/telegem-bot
232
+ cd ~/telegem-bot
233
+
234
+ # Create bot.rb with your code
235
+ # Create Gemfile with dependencies
236
+ ```
237
+
238
+ **Step 4: Install SSL certificates using telegem-ssl**
239
+
240
+ ```bash
241
+ # Point your domain to server first (DNS takes 5-15 mins)
242
+ gem install telegem
243
+
244
+ # Get free SSL certificate
245
+ telegem-ssl yourdomain.com your-email@example.com
246
+
247
+ # Answer the prompts - telegem-ssl handles everything!
248
+ ```
249
+
250
+ **Step 5: Run your bot**
251
+
252
+ ```bash
253
+ bundle install
254
+ ruby bot.rb
255
+
256
+ # Or run in background:
257
+ nohup ruby bot.rb > bot.log 2>&1 &
258
+
259
+ # Or use systemd (recommended):
260
+ sudo systemctl start telegem-bot
261
+ ```
262
+
263
+ ### Option 3: Docker Container (Most Professional)
264
+
265
+ Docker makes deployment consistent everywhere:
266
+
267
+ **Step 1: Create Dockerfile**
268
+
269
+ ```dockerfile
270
+ FROM ruby:3.2-alpine
271
+
272
+ WORKDIR /app
273
+
274
+ # Install dependencies
275
+ RUN apk add --no-cache build-base
276
+
277
+ # Copy Gemfile
278
+ COPY Gemfile Gemfile.lock ./
279
+ RUN bundle install --deployment
280
+
281
+ # Copy your bot code
282
+ COPY . .
283
+
284
+ # Expose port for webhooks
285
+ EXPOSE 3000
286
+
287
+ # Run the bot
288
+ CMD ["ruby", "bot.rb"]
289
+ ```
290
+
291
+ **Step 2: Create `.dockerignore`**
292
+
293
+ ```
294
+ .git
295
+ .gitignore
296
+ *.log
297
+ node_modules
298
+ coverage
299
+ tmp
300
+ ```
301
+
302
+ **Step 3: Create `Gemfile`**
303
+
304
+ ```ruby
305
+ source 'https://rubygems.org'
306
+
307
+ gem 'telegem'
308
+ gem 'rack'
309
+ ```
310
+
311
+ **Step 4: Create docker-compose.yml** (for local testing)
312
+
313
+ ```yaml
314
+ version: '3'
315
+ services:
316
+ bot:
317
+ build: .
318
+ ports:
319
+ - "3000:3000"
320
+ environment:
321
+ - BOT_TOKEN=${BOT_TOKEN}
322
+ - WEBHOOK_URL=${WEBHOOK_URL}
323
+ restart: unless-stopped
324
+ ```
325
+
326
+ **Step 5: Deploy**
327
+
328
+ ```bash
329
+ # Build image
330
+ docker build -t telegem-bot .
331
+
332
+ # Run container
333
+ docker run -p 3000:3000 \
334
+ -e BOT_TOKEN=your_token_here \
335
+ telegem-bot
336
+
337
+ # Or with docker-compose
338
+ docker-compose up -d
339
+ ```
340
+
341
+ ### Deploying to Heroku
342
+
343
+ **Step 1: Create Procfile**
344
+
345
+ ```
346
+ web: bundle exec ruby bot.rb
347
+ ```
348
+
349
+ **Step 2: Create app.json** (optional, for easy deploy button)
350
+
351
+ ```json
352
+ {
353
+ "name": "Telegem Bot",
354
+ "description": "A Telegram bot built with Telegem",
355
+ "repository": "https://github.com/yourusername/your-bot-repo",
356
+ "keywords": ["telegram", "bot", "ruby"],
357
+ "env": {
358
+ "BOT_TOKEN": {
359
+ "description": "Your Telegram Bot API Token",
360
+ "required": true
361
+ }
362
+ }
363
+ }
364
+ ```
365
+
366
+ **Step 3: Deploy**
367
+
368
+ ```bash
369
+ # Install Heroku CLI
370
+ npm install -g heroku
371
+
372
+ # Login
373
+ heroku login
374
+
375
+ # Create app
376
+ heroku create your-bot-name
377
+
378
+ # Set environment variables
379
+ heroku config:set BOT_TOKEN=your_token_here
380
+
381
+ # Deploy
382
+ git push heroku main
383
+ ```
384
+
385
+ ### Common Deployment Patterns
386
+
387
+ #### Pattern 1: GitHub + Railway Auto-Deploy
388
+
389
+ ```
390
+ Code changes → Push to GitHub → Railway auto-redeploys → Bot updated
391
+ ```
392
+
393
+ **Setup**:
394
+ 1. Connect Railway to your GitHub repo
395
+ 2. Every push to `main` auto-deploys!
396
+
397
+ #### Pattern 2: GitHub Actions + Custom Server
398
+
399
+ ```
400
+ Code changes → Push → GitHub Actions runs tests → Deploys to server
401
+ ```
402
+
403
+ **.github/workflows/deploy.yml**:
404
+
405
+ ```yaml
406
+ name: Deploy Bot
407
+
408
+ on:
409
+ push:
410
+ branches: [main]
411
+
412
+ jobs:
413
+ deploy:
414
+ runs-on: ubuntu-latest
415
+ steps:
416
+ - uses: actions/checkout@v3
417
+ - name: Deploy to server
418
+ run: |
419
+ ssh deploy@server "cd /app && git pull && bundle install && systemctl restart bot"
420
+ ```
421
+
422
+ #### Pattern 3: Docker Registry + Production Server
423
+
424
+ ```
425
+ Code → Docker image → Push to Docker Hub → Pull & run on server
426
+ ```
427
+
428
+ ```bash
429
+ # Build and push image
430
+ docker build -t yourusername/telegem-bot:latest .
431
+ docker push yourusername/telegem-bot:latest
432
+
433
+ # On server: pull and run
434
+ docker pull yourusername/telegem-bot:latest
435
+ docker run -d -e BOT_TOKEN=xxx yourusername/telegem-bot:latest
436
+ ```
437
+
438
+ ## Production Deployment
439
+
47
440
  ### Heroku Deployment
48
441
 
49
442
  ```ruby
@@ -109,39 +502,138 @@ server = bot.webhook
109
502
  server.run
110
503
  ```
111
504
 
112
- ## SSL/TLS Configuration
505
+ ## SSL/TLS Configuration (HTTPS)
506
+
507
+ **Why HTTPS?** Telegram requires HTTPS for security. All data between your bot and Telegram must be encrypted.
508
+
509
+ Telegem supports **three ways** to get SSL certificates:
113
510
 
114
- Telegram requires HTTPS for webhooks. Telegem supports multiple SSL setups.
511
+ ### 1. Cloud Platform SSL (Easiest for Beginners)
115
512
 
116
- ### Cloud Platform SSL (Recommended)
513
+ If you're using cloud platforms like **Heroku**, **Railway**, **Render**, or **Replit**, they automatically provide HTTPS for free. You don't need to do anything!
117
514
 
118
515
  ```ruby
119
- # For Heroku, Railway, Render, etc.
516
+ # Cloud platforms handle SSL automatically
120
517
  server = bot.webhook
121
- server.run # Platform handles SSL
518
+ server.run # Just works!
122
519
  ```
123
520
 
124
- ### Local SSL Certificates
521
+ **Platforms with automatic HTTPS:**
522
+ - Heroku
523
+ - Railway
524
+ - Render
525
+ - Replit
526
+ - Vercel
527
+ - Netlify
125
528
 
126
- ```ruby
127
- # Create .telegem-ssl file
128
- # cert_path: /path/to/cert.pem
129
- # key_path: /path/to/key.pem
529
+ ### 2. Automated SSL with telegem-ssl (Recommended for Self-Hosted)
130
530
 
131
- server = bot.webhook
132
- server.run # Uses local certificates
531
+ If you're running your own server, use the built-in `telegem-ssl` tool to automatically get free SSL certificates from Let's Encrypt.
532
+
533
+ #### Installation & Usage
534
+
535
+ ```bash
536
+ # Install gem with tools
537
+ gem install telegem
538
+
539
+ # Run the SSL setup tool
540
+ telegem-ssl yourdomain.com your-email@example.com
541
+ ```
542
+
543
+ #### What telegem-ssl Does
544
+
545
+ The `telegem-ssl` script automates the entire SSL setup process:
546
+
547
+ 1. **Checks if certbot is installed** (the Let's Encrypt client)
548
+ - Installs it automatically if missing (supports apt, dnf, yum, brew)
549
+
550
+ 2. **Gets a free SSL certificate** from Let's Encrypt using:
551
+ - **Standalone mode** (easiest) - temporarily stops your bot to verify domain
552
+ - **Webroot mode** (keeps running) - requires your web root path
553
+
554
+ 3. **Creates configuration file** at `.telegem-ssl`
555
+ - Stores certificate and key paths
556
+ - Your bot automatically uses these certificates
557
+
558
+ 4. **Shows auto-renewal instructions**
559
+ - Certificates expire after 90 days
560
+ - Cron job automatically renews them before expiration
561
+
562
+ #### Complete Example
563
+
564
+ ```bash
565
+ # Step 1: Point your domain to your server's IP address
566
+ # (DNS setup - usually takes 5-15 minutes to propagate)
567
+
568
+ # Step 2: Run the SSL setup
569
+ telegem-ssl bot.example.com admin@example.com
570
+
571
+ # Output:
572
+ # → Checks for certbot (installs if needed)
573
+ # → Gets certificate from Let's Encrypt
574
+ # → Creates .telegem-ssl configuration file
575
+ # → Shows renewal instructions
576
+
577
+ # Step 3: Your bot code stays simple
578
+ require 'telegem'
579
+ bot = Telegem.new('YOUR_BOT_TOKEN')
580
+
581
+ # Bot automatically uses SSL from .telegem-ssl
582
+ server = bot.webhook(port: 443)
583
+ server.run
584
+
585
+ # Step 4 (optional): Set up auto-renewal
586
+ # Add this to crontab (crontab -e):
587
+ # 0 0 1 * * certbot renew --quiet && systemctl reload your-bot-service
133
588
  ```
134
589
 
135
- ### Manual SSL Configuration
590
+ #### telegem-ssl Configuration File
591
+
592
+ After running the tool, a `.telegem-ssl` file is created:
593
+
594
+ ```yaml
595
+ # .telegem-ssl
596
+ domain: bot.example.com
597
+ cert_path: /etc/letsencrypt/live/bot.example.com/fullchain.pem
598
+ key_path: /etc/letsencrypt/live/bot.example.com/privkey.pem
599
+ ```
600
+
601
+ Your bot automatically reads this file on startup!
602
+
603
+ #### Troubleshooting telegem-ssl
604
+
605
+ **"Connection refused" / "Failed to get certificate"**
606
+ - Make sure your domain points to your server's IP
607
+ - Wait for DNS to propagate (5-15 minutes)
608
+ - Check firewall allows port 80 and 443
609
+
610
+ **"Certbot not found" / "Package manager not detected"**
611
+ - Manually install certbot: https://certbot.eff.org/instructions
612
+ - Run `telegem-ssl` again
613
+
614
+ **Certificate renewal not working**
615
+ - Check that cron is running: `sudo service cron status`
616
+ - Run renewal manually: `sudo certbot renew --dry-run`
617
+ - View cron logs: `grep CRON /var/log/syslog`
618
+
619
+ ### 3. Manual SSL Configuration
620
+
621
+ For advanced setups or custom certificates:
136
622
 
137
623
  ```ruby
138
624
  require 'openssl'
625
+ require 'telegem'
139
626
 
627
+ # Load your existing certificates
140
628
  ssl_context = OpenSSL::SSL::SSLContext.new
141
629
  ssl_context.cert = OpenSSL::X509::Certificate.new(File.read('cert.pem'))
142
630
  ssl_context.key = OpenSSL::PKey::RSA.new(File.read('key.pem'))
143
631
 
144
- server = bot.webhook(ssl_context: ssl_context)
632
+ bot = Telegem.new('YOUR_BOT_TOKEN')
633
+ server = bot.webhook(
634
+ port: 443,
635
+ ssl_context: ssl_context
636
+ )
145
637
  server.run
146
638
  ```
147
639