Skip to content

feruzlabs/telegram-bot1

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Production Telegram Webhook Bot

Professional Telegram bot with webhook support, Spring Boot framework, and production-ready features.

✨ Production Features

  • πŸ”— Webhook Support - Real-time message processing
  • πŸ—οΈ Spring Boot - Enterprise-grade framework
  • 🐳 Docker Support - Containerized deployment
  • πŸ“Š Monitoring - Health checks and metrics
  • πŸ—„οΈ Database - PostgreSQL for persistence
  • πŸš€ Caching - Redis for performance
  • πŸ”’ Security - SSL/TLS and authentication
  • πŸ“ˆ Scalability - Horizontal scaling ready

πŸ› οΈ Technology Stack

  • Java 17
  • Spring Boot 3.2
  • TelegramBots API 6.8
  • PostgreSQL 15
  • Redis 7
  • Docker & Docker Compose
  • Nginx (Reverse Proxy)

πŸš€ Quick Start

1. Environment Setup

# Clone repository
git clone <repository-url>
cd telegram-webhook-bot

# Create .env file
cp .env.example .env

2. Configure Environment Variables

# .env file
TELEGRAM_BOT_TOKEN=your_bot_token_here
TELEGRAM_BOT_USERNAME=your_bot_username
WEBHOOK_URL=https://yourdomain.com
POSTGRES_PASSWORD=your_db_password
REDIS_PASSWORD=your_redis_password

3. Run with Docker

# Build and start all services
docker-compose up -d

# Check logs
docker-compose logs -f telegram-bot

# Check health
curl http://localhost:8080/health

πŸ”§ Development Setup

Local Development

# Install dependencies
mvn clean install

# Run in development mode
mvn spring-boot:run -Dspring-boot.run.profiles=dev

# Or with IDE
# Set active profile: dev
# Environment variables: TELEGRAM_BOT_TOKEN, etc.

Hot Reload

# Enable Spring Boot DevTools
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"

🌐 Webhook Setup

1. Domain and SSL

# Get SSL certificate (Let's Encrypt)
certbot --nginx -d yourdomain.com

# Or use Cloudflare SSL

2. Set Webhook URL

# Automatically set during bot startup
# Or manually:
curl -X POST "https://api.telegram.org/bot${BOT_TOKEN}/setWebhook" \
     -H "Content-Type: application/json" \
     -d '{"url":"https://yourdomain.com/webhook/telegram"}'

3. Verify Webhook

# Check webhook info
curl "https://api.telegram.org/bot${BOT_TOKEN}/getWebhookInfo"

πŸ“Š Monitoring and Health

Health Endpoints

# Application health
GET /health

# Application status
GET /status

# Actuator endpoints
GET /actuator/health
GET /actuator/metrics
GET /actuator/prometheus

Logs

# View application logs
docker-compose logs -f telegram-bot

# Log files location
./logs/telegram-webhook-bot.log

πŸ—„οΈ Database

PostgreSQL Schema

-- Users table
CREATE TABLE users (
                       id BIGINT PRIMARY KEY,
                       username VARCHAR(255),
                       first_name VARCHAR(255),
                       last_name VARCHAR(255),
                       created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                       updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- User sessions
CREATE TABLE user_sessions (
                               user_id BIGINT PRIMARY KEY,
                               step VARCHAR(100),
                               data JSONB,
                               created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                               updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Bot statistics
CREATE TABLE bot_stats (
                           id SERIAL PRIMARY KEY,
                           date DATE UNIQUE,
                           total_users BIGINT,
                           active_users BIGINT,
                           messages_count BIGINT,
                           created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Redis Caching

# User session caching
user:session:{user_id} -> JSON data

# Rate limiting
user:rate:{user_id} -> counter

# Bot statistics
bot:stats:daily -> JSON data

πŸ”§ Configuration

Application Properties

# Development (application-dev.properties)
telegram.bot.token=${TELEGRAM_BOT_TOKEN}
spring.datasource.url=jdbc:sqlite:bot.db
logging.level.dev.feruzlabs.telegrambot=DEBUG

# Production (application-prod.properties)
telegram.bot.token=${TELEGRAM_BOT_TOKEN}
spring.datasource.url=${DATABASE_URL}
spring.redis.url=${REDIS_URL}
logging.level.dev.feruzlabs.telegrambot=INFO

Security Configuration

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .csrf().disable()
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/webhook/**").permitAll()
                        .requestMatchers("/health", "/status").permitAll()
                        .requestMatchers("/actuator/**").hasRole("ADMIN")
                        .anyRequest().authenticated()
                )
                .build();
    }
}

πŸš€ Deployment

1. Build Production JAR

mvn clean package -Pprod

2. Deploy with Docker

# Build image
docker build -t telegram-webhook-bot .

# Run container
docker run -d \
  --name telegram-bot \
  -p 8080:8080 \
  -e TELEGRAM_BOT_TOKEN=${BOT_TOKEN} \
  -e WEBHOOK_URL=https://yourdomain.com \
  telegram-webhook-bot

3. Deploy with Docker Compose

# Production deployment
docker-compose -f docker-compose.prod.yml up -d

# Update deployment
docker-compose pull && docker-compose up -d

4. Deploy to Cloud

Heroku

# Create Heroku app
heroku create telegram-webhook-bot

# Set environment variables
heroku config:set TELEGRAM_BOT_TOKEN=your_token
heroku config:set WEBHOOK_URL=https://your-app.herokuapp.com

# Deploy
git push heroku main

AWS/GCP/Azure

# Use provided docker-compose files
# Configure load balancer and SSL
# Set up CI/CD pipeline

πŸ“ˆ Performance

Optimization

# JVM Options
-Xms512m -Xmx1024m
-XX:+UseG1GC
-XX:MaxGCPauseMillis=200

# Spring Boot
server.tomcat.max-threads=200
spring.datasource.hikari.maximum-pool-size=20
spring.redis.lettuce.pool.max-active=8

Scaling

# docker-compose.yml
services:
  telegram-bot:
    deploy:
      replicas: 3

  nginx:
  # Load balancer configuration

πŸ” Security

SSL/TLS

server {
    listen 443 ssl;
    server_name yourdomain.com;
    
    ssl_certificate /etc/ssl/certs/fullchain.pem;
    ssl_certificate_key /etc/ssl/certs/privkey.pem;
    
    location /webhook/ {
        proxy_pass http://telegram-bot:8080;
    }
}

Rate Limiting

@Component
public class RateLimitService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public boolean isAllowed(Long userId) {
        String key = "rate:limit:" + userId;
        // Implement sliding window rate limiting
        return true; // Simplified
    }
}

πŸ› Troubleshooting

Common Issues

  1. Webhook not working

    # Check webhook status
    curl "https://api.telegram.org/bot${BOT_TOKEN}/getWebhookInfo"
    
    # Check SSL certificate
    curl -I https://yourdomain.com/webhook/telegram
    
    # Check bot logs
    docker-compose logs telegram-bot
  2. Database connection issues

    # Check PostgreSQL
    docker-compose exec postgres psql -U telegram_user -d telegram_bot
    
    # Check connection from app
    docker-compose exec telegram-bot curl localhost:8080/actuator/health
  3. Memory issues

    # Monitor memory usage
    docker stats telegram-bot
    
    # Adjust JVM settings
    JAVA_OPTS="-Xms512m -Xmx1024m"
  4. High CPU usage

    # Check for infinite loops in logs
    docker-compose logs --tail=100 telegram-bot
    
    # Profile application
    java -jar app.jar --spring.profiles.active=prod -XX:+FlightRecorder

Debug Mode

# Enable debug logging
docker-compose exec telegram-bot \
  java -jar app.jar \
  --logging.level.dev.feruzlabs.telegrambot=DEBUG \
  --spring.profiles.active=dev

πŸ“Š Monitoring Setup

Prometheus + Grafana

# monitoring/docker-compose.yml
version: '3.8'
services:
  prometheus:
    image: prom/prometheus
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
      
  grafana:
    image: grafana/grafana
    ports:
      - "3000:3000"
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=admin

Metrics

# Expose metrics
management.endpoints.web.exposure.include=health,info,metrics,prometheus
management.endpoint.health.show-details=always

πŸ”„ CI/CD Pipeline

GitHub Actions

# .github/workflows/deploy.yml
name: Deploy to Production

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Set up JDK 17
        uses: actions/setup-java@v3
        with:
          java-version: '17'
          
      - name: Build with Maven
        run: mvn clean package -Pprod
        
      - name: Build Docker image
        run: docker build -t telegram-bot .
        
      - name: Deploy to server
        run: |
          # Deploy script here

πŸ§ͺ Testing

Unit Tests

# Run all tests
mvn test

# Run specific test
mvn test -Dtest=InteractiveWebhookBotTest

Integration Tests

# Run integration tests
mvn verify -Pintegration-tests

# Test webhook endpoint
curl -X POST http://localhost:8080/webhook/telegram \
  -H "Content-Type: application/json" \
  -d '{"update_id":1,"message":{"message_id":1,"from":{"id":123,"first_name":"Test"},"chat":{"id":123,"type":"private"},"text":"/start"}}'

Load Testing

# Install artillery
npm install -g artillery

# Run load test
artillery run load-test.yml

πŸ“š API Documentation

Webhook Endpoints

POST /webhook/telegram
Content-Type: application/json

# Telegram webhook payload
{
  "update_id": 123456789,
  "message": {
    "message_id": 1,
    "from": {"id": 123, "first_name": "User"},
    "chat": {"id": 123, "type": "private"},
    "text": "/start"
  }
}

Management Endpoints

GET /health           - Application health status
GET /status          - Bot status information  
GET /actuator/health - Detailed health information
GET /actuator/metrics - Application metrics

🀝 Contributing

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ†˜ Support

πŸŽ‰ Acknowledgments


πŸš€ Ready for production! Deploy your Telegram bot with confidence!

About

Test telegram bot

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published