telegram-plaid-bot

Telegram Plaid Bot

A full-stack application that integrates a Telegram bot with Plaid’s banking API, allowing users to securely connect their bank accounts and view financial information directly through Telegram.

🌟 Features

🎯 How It Works - Telegram as Your GUI

Unlike traditional web apps, this bot uses Telegram as the entire user interface:

The flow: User's Telegram App β†’ Your Bot β†’ Express API β†’ PostgreSQL + Plaid β†’ Bank Data

πŸ“˜ For complete deployment instructions, see DEPLOYMENT.md

πŸ“‹ Prerequisites

Before you begin, ensure you have the following installed:

πŸš€ Installation

1. Clone the Repository

git clone https://github.com/yourusername/telegram-plaid-bot.git
cd telegram-plaid-bot

2. Install Dependencies

npm install

3. Configure Environment Variables

Copy the example environment file and configure it:

cp .env.example .env

Edit .env with your credentials:

# Telegram Bot Token (get from @BotFather)
TELEGRAM_BOT_TOKEN=your_telegram_bot_token

# Plaid Credentials (from Plaid Dashboard)
PLAID_CLIENT_ID=your_plaid_client_id
PLAID_SECRET=your_plaid_secret
PLAID_ENV=sandbox  # Use 'sandbox' for testing, 'production' for live

# Database Connection
DATABASE_URL=postgresql://user:password@localhost:5432/telegram_plaid

# Server Configuration
PORT=3000
API_BASE_URL=http://localhost:3000

# Security (IMPORTANT: Change these!)
ENCRYPTION_KEY=your_32_character_encryption_key_here
JWT_SECRET=your_jwt_secret_here

# Logging
LOG_LEVEL=info

Important Security Notes:

4. Set Up Database

Option A: Manual Setup

Create the database:

createdb telegram_plaid

Initialize the schema:

npm run init-db
docker-compose up -d db

The database will be automatically initialized with the schema.

πŸƒ Running the Application

Development Mode

npm run dev

This uses nodemon for automatic reloading on file changes.

Production Mode

npm start

Using Docker

Build and run everything with Docker Compose:

docker-compose up -d

Stop the application:

docker-compose down

View logs:

docker-compose logs -f app

πŸ’¬ Available Bot Commands

Command Description
/start Welcome message and initialization
/link Connect your bank account via Plaid
/balance View all connected account balances
/transactions View recent transactions (last 30 days)
/help Display help information

Keyboard Shortcuts

The bot also provides interactive buttons:

πŸ”Œ API Documentation

Endpoints

POST /api/plaid/create-link-token
Content-Type: application/json

{
  "telegram_id": 123456789
}

Response:
{
  "success": true,
  "link_token": "link-sandbox-xxx",
  "expiration": "2024-01-01T12:00:00Z"
}

Exchange Public Token

POST /api/plaid/exchange-token
Content-Type: application/json

{
  "public_token": "public-sandbox-xxx",
  "telegram_id": 123456789
}

Response:
{
  "success": true,
  "institution_name": "Chase"
}

Get Accounts

GET /api/plaid/accounts/:telegram_id

Response:
{
  "success": true,
  "accounts": [
    {
      "name": "Plaid Checking",
      "balance": 100.00,
      "available": 95.00,
      "type": "depository",
      "subtype": "checking",
      "institution": "Chase"
    }
  ]
}

Get Transactions

GET /api/plaid/transactions/:telegram_id?start_date=2024-01-01&end_date=2024-01-31

Response:
{
  "success": true,
  "transactions": [
    {
      "transaction_id": "xxx",
      "name": "Uber",
      "amount": 12.50,
      "date": "2024-01-15",
      "category": ["Transportation"],
      "pending": false,
      "institution": "Chase"
    }
  ]
}

Webhook Handler

POST /api/webhook/plaid
Content-Type: application/json

{
  "webhook_type": "TRANSACTIONS",
  "webhook_code": "DEFAULT_UPDATE",
  "item_id": "xxx"
}

Response:
{
  "received": true
}

Health Check

GET /health

Response:
{
  "status": "ok",
  "timestamp": "2024-01-01T12:00:00.000Z"
}

πŸ§ͺ Testing in Sandbox

Plaid provides a sandbox environment for testing without real bank connections.

Sandbox Test Credentials

When using Plaid Link in sandbox mode:

  1. Institution: Search for β€œFirst Platypus Bank”
  2. Username: user_good
  3. Password: pass_good
  4. MFA: 1234 (if prompted)

Testing the Flow

  1. Start the bot with /start
  2. Use /link to get a link token
  3. In a real implementation, you’d complete Plaid Link flow in a web interface
  4. The bot will guide you through the connection process
  5. Use /balance to view connected accounts
  6. Use /transactions to see transaction history

πŸ—‚οΈ Project Structure

telegram-plaid-bot/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ bot/                      # Telegram bot
β”‚   β”‚   β”œβ”€β”€ index.js              # Bot initialization
β”‚   β”‚   β”œβ”€β”€ commands/             # Command handlers
β”‚   β”‚   β”‚   β”œβ”€β”€ start.js
β”‚   β”‚   β”‚   β”œβ”€β”€ link.js
β”‚   β”‚   β”‚   β”œβ”€β”€ balance.js
β”‚   β”‚   β”‚   β”œβ”€β”€ transactions.js
β”‚   β”‚   β”‚   └── help.js
β”‚   β”‚   └── middleware/           # Bot middleware
β”‚   β”‚       └── auth.js
β”‚   β”œβ”€β”€ api/                      # Express API
β”‚   β”‚   β”œβ”€β”€ server.js             # Server setup
β”‚   β”‚   β”œβ”€β”€ routes/               # Route definitions
β”‚   β”‚   β”‚   β”œβ”€β”€ plaid.js
β”‚   β”‚   β”‚   └── webhook.js
β”‚   β”‚   └── controllers/          # Request handlers
β”‚   β”‚       β”œβ”€β”€ plaidController.js
β”‚   β”‚       └── webhookController.js
β”‚   β”œβ”€β”€ services/                 # Business logic
β”‚   β”‚   β”œβ”€β”€ plaidService.js       # Plaid API wrapper
β”‚   β”‚   β”œβ”€β”€ userService.js        # User operations
β”‚   β”‚   └── encryptionService.js  # Token encryption
β”‚   β”œβ”€β”€ models/                   # Data models
β”‚   β”‚   β”œβ”€β”€ User.js
β”‚   β”‚   └── PlaidConnection.js
β”‚   β”œβ”€β”€ database/                 # Database setup
β”‚   β”‚   β”œβ”€β”€ connection.js         # DB connection pool
β”‚   β”‚   β”œβ”€β”€ init.sql              # Schema definition
β”‚   β”‚   └── init.js               # Initialization script
β”‚   β”œβ”€β”€ config/                   # Configuration
β”‚   β”‚   └── index.js
β”‚   β”œβ”€β”€ utils/                    # Utilities
β”‚   β”‚   β”œβ”€β”€ logger.js             # Winston logger
β”‚   β”‚   └── errorHandler.js       # Error handling
β”‚   └── index.js                  # Application entry point
β”œβ”€β”€ .env.example                  # Environment template
β”œβ”€β”€ .gitignore
β”œβ”€β”€ package.json
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ docker-compose.yml
β”œβ”€β”€ DEPLOYMENT.md                 # Complete deployment guide
└── README.md

πŸš€ Deployment

This application can be deployed to various platforms. The Telegram bot serves as your GUI - no frontend deployment needed!

Quick Deploy Options

  1. Heroku (Easiest for beginners)
    heroku create my-telegram-bot
    heroku addons:create heroku-postgresql:mini
    git push heroku main
    
  2. DigitalOcean/VPS (Best for production)
    • Install Node.js, PostgreSQL, PM2
    • Clone repo, configure .env
    • Start with pm2 start src/index.js
  3. Docker (Recommended)
    docker-compose up -d
    

Essential Steps for Any Platform

  1. Get Telegram Bot Token: Talk to @BotFather on Telegram
  2. Get Plaid Credentials: Sign up at Plaid.com
  3. Set Environment Variables: Copy .env.example and fill in your credentials
  4. Initialize Database: Run npm run init-db
  5. Start Application: The bot will be your GUI automatically!

πŸ“˜ For detailed deployment instructions (cloud, VPS, Docker, monitoring), see DEPLOYMENT.md

πŸ” Security Best Practices

Implemented Security Measures

  1. Token Encryption
    • All Plaid access tokens encrypted with AES-256-GCM
    • Unique initialization vectors for each encryption
    • Authentication tags for integrity verification
  2. Environment Security
    • All secrets in environment variables
    • .env excluded from version control
    • Validation of required environment variables on startup
  3. API Security
    • Helmet.js for HTTP security headers
    • CORS configured for controlled access
    • Rate limiting (60 requests/minute per IP)
    • Input validation on all endpoints
  4. Database Security
    • Parameterized queries prevent SQL injection
    • Connection pooling with timeouts
    • CASCADE deletes for data integrity
  5. Error Handling
    • No sensitive data in error messages
    • Production mode hides stack traces
    • Comprehensive logging without secrets
  6. Production Recommendations
    • Use HTTPS for all communications
    • Set up SSL/TLS for database connections
    • Implement proper secrets management (AWS Secrets Manager, etc.)
    • Enable webhook signature verification
    • Regular security audits
    • Keep dependencies updated

πŸ› Troubleshooting

Common Issues

Bot Not Responding

Database Connection Errors

Plaid API Errors

Encryption Errors

Rate Limiting

Logs

Check application logs:

# Combined logs
tail -f combined.log

# Error logs only
tail -f error.log

# Docker logs
docker-compose logs -f app

🀝 Contributing

Contributions are welcome! Please follow these steps:

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

Development Guidelines

πŸ“„ License

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

πŸ™ Acknowledgments

πŸ“ž Support

For issues and questions:

⚠️ Disclaimer

This bot handles sensitive financial information. Always:


Happy Banking! 🏦