Professional Telegram bot with webhook support, Spring Boot framework, and production-ready 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
- Java 17
- Spring Boot 3.2
- TelegramBots API 6.8
- PostgreSQL 15
- Redis 7
- Docker & Docker Compose
- Nginx (Reverse Proxy)
# Clone repository
git clone <repository-url>
cd telegram-webhook-bot
# Create .env file
cp .env.example .env
# .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
# Build and start all services
docker-compose up -d
# Check logs
docker-compose logs -f telegram-bot
# Check health
curl http://localhost:8080/health
# 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.
# Enable Spring Boot DevTools
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"
# Get SSL certificate (Let's Encrypt)
certbot --nginx -d yourdomain.com
# Or use Cloudflare SSL
# 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"}'
# Check webhook info
curl "https://api.telegram.org/bot${BOT_TOKEN}/getWebhookInfo"
# Application health
GET /health
# Application status
GET /status
# Actuator endpoints
GET /actuator/health
GET /actuator/metrics
GET /actuator/prometheus
# View application logs
docker-compose logs -f telegram-bot
# Log files location
./logs/telegram-webhook-bot.log
-- 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
);
# User session caching
user:session:{user_id} -> JSON data
# Rate limiting
user:rate:{user_id} -> counter
# Bot statistics
bot:stats:daily -> JSON data
# 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
@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();
}
}
mvn clean package -Pprod
# 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
# Production deployment
docker-compose -f docker-compose.prod.yml up -d
# Update deployment
docker-compose pull && docker-compose up -d
# 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
# Use provided docker-compose files
# Configure load balancer and SSL
# Set up CI/CD pipeline
# 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
# docker-compose.yml
services:
telegram-bot:
deploy:
replicas: 3
nginx:
# Load balancer configuration
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;
}
}
@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
}
}
-
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
-
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
-
Memory issues
# Monitor memory usage docker stats telegram-bot # Adjust JVM settings JAVA_OPTS="-Xms512m -Xmx1024m"
-
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
# Enable debug logging
docker-compose exec telegram-bot \
java -jar app.jar \
--logging.level.dev.feruzlabs.telegrambot=DEBUG \
--spring.profiles.active=dev
# 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
# Expose metrics
management.endpoints.web.exposure.include=health,info,metrics,prometheus
management.endpoint.health.show-details=always
# .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
# Run all tests
mvn test
# Run specific test
mvn test -Dtest=InteractiveWebhookBotTest
# 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"}}'
# Install artillery
npm install -g artillery
# Run load test
artillery run load-test.yml
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"
}
}
GET /health - Application health status
GET /status - Bot status information
GET /actuator/health - Detailed health information
GET /actuator/metrics - Application metrics
- Fork the repository
- Create feature branch (
git checkout -b feature/amazing-feature
) - Commit changes (
git commit -m 'Add amazing feature'
) - Push to branch (
git push origin feature/amazing-feature
) - Open Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- π§ Email: support@feruzlabs.dev
- π¬ Telegram: @yoursupport
- π Issues: GitHub Issues
- π Documentation: Wiki
π Ready for production! Deploy your Telegram bot with confidence!