Telegram channel automation + bot that publishes crypto market updates, on-chain alpha, mobile-money opportunities, and drives traffic to crypto.loopnet.tech.
Tech Stack: Node.js (Telegraf), MongoDB (Mongoose), node-cron, Gemini AI, Express
Timezone Support: Europe/London (with DST handling)
Tone: Hacker / High-energy / Mobile-first
- Overview
- Quick Start
- Project Structure
- Environment Variables
- Bot Commands
- Scheduler & Channel Management
- Payment Integrations
- Gemini AI Usage
- API Endpoints
- Documentation
- Deployment
- Testing
- Troubleshooting
Crypto Hub Bot automates publishing crypto market updates, alerts, memes, and mobile-money CTAs to a Telegram channel. Key features:
β
Persistent schedule management β Create/list/pause/resume jobs stored in MongoDB
β
Timezone-aware scheduling β Europe/London with automatic DST handling
β
Gemini AI content generation β Dynamic market summaries and alerts
β
Public crypto APIs β CoinGecko price feeds with caching
β
Mobile money integrations β M-Pesa (Kenya), Airtel Money (Uganda/Malawi)
β
Crypto deposits β USDT/BTC addresses from environment
β
Admin management β Broadcasts, scheduled posts, dispute resolution
β
Analytics tracking β Message views, clicks, reactions
β
Retry/backoff logic β Resilient channel posting with exponential backoff
- Node.js 20+
- MongoDB (local or Atlas)
- Telegram Bot Token (create via @BotFather)
- Telegram Channel (bot must be admin)
# 1. Clone repository
git clone <repo-url>
cd crypto-hub-bot
# 2. Install dependencies
npm install
# 3. Configure environment
cp .env.example .env
# Edit .env with your credentials
# 4. Start development server
npm run dev# Check bot is running
curl http://localhost:3000/api/health
# Test Telegram bot
# Send /start to your bot in Telegramsrc/
βββ bot/
β βββ admin.js # Admin commands (schedule management)
β βββ commands.js # User commands (/start, /deposit, /prices)
βββ cron/
β βββ channelScheduler.js # DB-backed persistent scheduler
β βββ scheduler.js # Simple cron jobs (price caching)
βββ services/
β βββ geminiClient.js # Gemini AI wrapper
β βββ priceFetcher.js # CoinGecko API client
β βββ channelManager.js # Channel posting + analytics
β βββ telegramBot.js # Bot initialization
β βββ analytics.js # Analytics tracking
β βββ payments.js # Payment helpers (placeholder)
βββ models/
β βββ User.js # User accounts
β βββ ChannelMessage.js # Posted messages + analytics
β βββ ScheduledJob.js # Cron job definitions
β βββ Transaction.js # Payment records
β βββ Subscription.js # User subscriptions
β βββ Alert.js # Price alerts
β βββ PriceCache.js # Cached price data
βββ routes/
β βββ api.js # REST API endpoints
βββ utils/
β βββ paymentContacts.js # Mobile money contact helper
βββ config.js # Environment configuration
βββ server.js # Express server
βββ index.js # Application entry point
docs/ # Comprehensive documentation (11 guides)
__tests__/ # Jest test suite
Create .env file (never commit to git):
# === Core ===
NODE_ENV=development
PORT=3000
BASE_URL=https://crypto.loopnet.tech
# === Database ===
MONGO_URI=mongodb://localhost:27017/crypto_hub
# Or MongoDB Atlas:
# MONGO_URI=mongodb+srv://user:pass@cluster.mongodb.net/crypto_hub
# === Telegram ===
TELEGRAM_BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
TELEGRAM_CHANNEL_ID=-1001234567890
ADMIN_TELEGRAM_ID=123456789
# === Gemini AI ===
GEMINI_API_KEY=AIzaSy...
GEMINI_MODEL=gemini-2.0-flash
GEMINI_TEMPERATURE=0.8
GEMINI_MAX_TOKENS=500
# === Crypto Addresses (public) ===
CRYPTO_USDT_ADDRESS=0xYourTetherUSDTAddressHere
CRYPTO_BTC_ADDRESS=bc1qyourbtcaddresshere
# === Mobile Money (E.164 format, no +) ===
MOBILE_MPESA_KE=254XXXXXXXXX
MOBILE_AIRTEL_UG=256XXXXXXXXX
MOBILE_AIRTEL_MW=265XXXXXXXXX
DEFAULT_PAYMENT_COUNTRY=KE
# === M-Pesa Daraja (optional - for STK Push) ===
MPESA_CONSUMER_KEY=your_consumer_key
MPESA_CONSUMER_SECRET=your_consumer_secret
MPESA_SHORTCODE=174379
MPESA_PASSKEY=your_passkey
MPESA_ENVIRONMENT=sandbox
MPESA_CALLBACK_URL=https://yourdomain.com/api/webhook/mpesa/callback
# === Airtel Money (optional) ===
AIRTEL_CLIENT_ID=your_client_id
AIRTEL_CLIENT_SECRET=your_client_secret
AIRTEL_ENVIRONMENT=stagingSee .env.example for complete reference.
| Command | Description |
|---|---|
/start |
Welcome message & signup CTA |
/help |
Show available commands |
/prices |
Latest crypto prices (BTC, ETH, BNB, SOL, ADA) |
/deposit [country] |
Show crypto addresses & mobile money number |
/confirm_deposit <amount> |
Confirm payment (for reconciliation) |
/alerts |
View active price alerts |
/subscribe <ticker> <price> |
Set price alert |
| Command | Description |
|---|---|
/job_create Name || cron || type || content |
Create scheduled job |
/job_list |
List all scheduled jobs |
/job_pause <jobId> |
Pause a job |
/job_resume <jobId> |
Resume paused job |
/job_reschedule <jobId> || <newCron> |
Update job schedule |
/job_run <jobId> |
Force-run job immediately |
/broadcast <message> |
Send message to channel |
/pin <messageId> |
Pin message in channel |
/show_config |
Display configured addresses |
/seed_jobs |
Seed all automation blueprint jobs |
/clear_jobs |
Clear all jobs (requires confirm) |
Daily morning alpha (9 AM London time):
/job_create MorningAlpha || 0 9 * * * || alpha || gemini:Write a hacker-style alpha for BTC and ETH
Quick market update (every 15 minutes):
/job_create QuickUpdate || */15 * * * * || update || gemini:QUICK_UPDATE
Daily digest (6 PM London time):
/job_create EveningDigest || 0 18 * * * || digest || gemini:DAILY_DIGEST
Seed 13 pre-configured jobs in one command:
/seed_jobsThis creates:
- β 5-min marketing messages (drive signups)
- β 5-min strategy tips (educate users)
- β 10-min whale alerts (real-time on-chain data)
- β 15-min trending coins (CoinGecko hot list)
- β 30-min top movers (gainers/losers)
- β Hourly market alpha (AI-generated insights)
- β 3-hour motivation posts (inspire action)
- β Daily greetings (morning/afternoon/night)
- β Daily digest (complete market summary)
See full blueprint: docs/12-CHANNEL-AUTOMATION-BLUEPRINT.md
- Persistent Storage β Jobs stored in MongoDB (
ScheduledJobmodel) - Timezone-Aware β Uses
cronlibrary withEurope/Londontimezone (handles DST automatically) - Dynamic Loading β On startup, loads all enabled jobs from DB
- Content Rotation β Automatically rotates through 30+ pre-written templates
- API Integration β Fetches live data from CoinGecko + Etherscan
- AI Enhancement β Uses Gemini for dynamic content generation
- Admin Control β Create/pause/resume/reschedule via Telegram commands
{
name: "MorningAlpha",
cron: "0 9 * * *",
timezone: "Europe/London",
channelId: "-1001234567890",
enabled: true,
payload: {
type: "alpha", // alpha, update, digest, promo
geminiPrompt: "...", // AI-generated content
content: "...", // OR static content
appendCTA: true // Add CTA + disclaimer
},
retryPolicy: {
retries: 2,
backoffSec: 30
}
}- Generate Content β Static text or Gemini AI call
- Append CTA β Add link to https://crypto.loopnet.tech
- Post with Retry β
channelManager.postToChannel()with exponential backoff - Log Analytics β Store
ChannelMessagerecord for tracking
Addresses configured in .env:
- USDT: ERC-20 or TRC-20 address
- BTC: Native SegWit (bc1...) recommended
User Flow:
- User sends
/deposit - Bot displays addresses with instructions
- User sends crypto and uses
/confirm_deposit <amount> <txid> - Admin manually verifies transaction
Future Enhancement: Implement automated verification via Etherscan/Blockchain.info APIs.
Integration Type: Daraja API (STK Push)
Flow:
- User initiates payment via bot command
- Backend calls STK Push API
- User receives M-Pesa prompt on phone
- User enters PIN
- Daraja sends callback to webhook
- System updates
Transactionstatus
Documentation: See docs/05-PAYMENT-INTEGRATION.md
Integration Type: Collections API
Flow:
- User provides phone number
- Backend initiates collection request
- User receives payment prompt
- User approves transaction
- Webhook confirms payment
- System updates
Transactionstatus
Documentation: See docs/05-PAYMENT-INTEGRATION.md
Set in .env:
GEMINI_API_KEY=your_key
GEMINI_MODEL=gemini-2.0-flash
GEMINI_TEMPERATURE=0.7
GEMINI_MAX_TOKENS=500Hacker-style alpha:
await generateOneLineSummary({
btc: { usd: 50000, change_24h: 2.5 },
eth: { usd: 3000, change_24h: -1.2 }
});
// Output: "Bitcoin surges past $50K as bulls dominate the market."Daily digest:
await generateDailyDigest(priceData);
// Output: Professional 3-4 sentence market summaryβ
Cache AI responses for repeated prompts
β
Limit token length (cost optimization)
β
Always have fallback content for API failures
β
Monitor token usage and costs
β
Test prompts iteratively for quality
Documentation: See docs/06-GEMINI-AI.md
GET /api/health # Health check
GET /api/prices # Latest crypto prices
POST /api/subscribe # Create subscription
POST /api/webhook/mpesa/callback # M-Pesa STK callback
POST /api/webhook/mpesa/validation # M-Pesa C2B validation
POST /api/webhook/mpesa/confirmation # M-Pesa C2B confirmation
POST /api/webhook/airtel/callback # Airtel payment callback
GET /api/admin/jobs # List scheduled jobs
POST /api/admin/jobs # Create job
PUT /api/admin/jobs/:id # Update job
DELETE /api/admin/jobs/:id # Delete job
Comprehensive guides in docs/ directory:
- 00-OVERVIEW.md β Project vision & navigation
- 01-SETUP.md β Local development setup
- 02-ARCHITECTURE.md β System design
- 03-API-REFERENCE.md β Complete API reference
- 04-SCHEDULER-GUIDE.md β Cron job management
- 05-PAYMENT-INTEGRATION.md β M-Pesa, Airtel, crypto
- 06-GEMINI-AI.md β AI content generation
- 07-DEPLOYMENT.md β PM2, Docker, Kubernetes
- 08-OPERATIONS.md β Monitoring & troubleshooting
- 09-ROADMAP.md β 24-week implementation plan
- 10-SECURITY.md β Security best practices
- 11-TESTING.md β Testing guide with Jest
# Install PM2
npm install -g pm2
# Start application
pm2 start src/index.js --name crypto-hub-bot
# Save configuration
pm2 save
pm2 startup# Build image
docker build -t crypto-hub-bot .
# Run container
docker run -d \
--name crypto-hub-bot \
--env-file .env \
-p 3000:3000 \
crypto-hub-botdocker-compose up -dSee docs/07-DEPLOYMENT.md for complete Kubernetes manifests.
# Install test dependencies
npm install --save-dev jest supertest mongodb-memory-server nock @jest/globals
# Run all tests
npm test
# Watch mode
npm run test:watch
# Coverage report
npm run test:coverage__tests__/
βββ setup.js # MongoDB Memory Server setup
βββ models/
β βββ User.test.js
β βββ Transaction.test.js
βββ services/
β βββ priceFetcher.test.js
βββ utils/
βββ paymentContacts.test.js
Documentation: See docs/11-TESTING.md
Check:
TELEGRAM_BOT_TOKENis correct- Bot is admin in channel
- MongoDB connection successful
# Test bot connection
curl https://api.telegram.org/bot<TOKEN>/getMe
# Check logs
pm2 logs crypto-hub-botCheck:
- Job is enabled (
ScheduledJob.enabled = true) - Cron expression is valid
- Timezone is set to
Europe/London
# List jobs via admin command
/job_list
# Force run to test
/job_run <jobId>Check:
- Webhook URL is HTTPS
- Port 443 is open
- URL is registered with payment provider
- Server responds with 200 status quickly
# Test webhook endpoint
curl -X POST https://yourdomain.com/api/webhook/mpesa/callback \
-H "Content-Type: application/json" \
-d '{"test":"data"}'More troubleshooting: See docs/08-OPERATIONS.md
- β Bot with basic commands
- β Channel automation
- β Price fetching
- β Admin commands
- β Payment integration setup
- Per-user crypto addresses
- Automated payment verification
- Analytics dashboard
- Redis caching & locks
- Advanced AI prompts
- React admin dashboard
- Multi-channel support
- Advanced analytics
- Kubernetes deployment
- Revenue optimization
Full roadmap: See docs/09-ROADMAP.md
- Never commit
.envto git - Use environment variables for all secrets
- Rotate API keys regularly
- Validate all webhook payloads
- Implement rate limiting on API endpoints
- Use HTTPS for all webhook URLs
- Add authentication to admin endpoints
Full security guide: See docs/10-SECURITY.md
MIT License - see LICENSE file for details
- 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
- Documentation: Check
docs/directory - Issues: Open GitHub issue
- Email: support@crypto.loopnet.tech
- Telegram: @your_support_channel
# Development
npm run dev # Start with hot reload
npm test # Run tests
npm run test:coverage # Generate coverage report
# Production
npm start # Start application
pm2 start src/index.js # Start with PM2
docker-compose up -d # Start with Docker
# Admin (via Telegram)
/job_create # Create scheduled job
/job_list # View all jobs
/broadcast <msg> # Send to channel
/show_config # View configurationBuilt with β€οΈ for the crypto community
π crypto.loopnet.tech