MonitizeRobot is a powerful, feature-rich Telegram bot designed to help group administrators manage subscription-based access to their groups.
- π° Monetize Your Telegram Groups: Turn your communities into revenue streams
- π Subscription Management: Control access to your groups through paid subscriptions
- π³ Payment Integration: Built-in support for PayFast with expandable payment options
- π Detailed Analytics: Track subscribers, revenue, and group activity
- βοΈ Customizable Settings: Configure subscription prices, welcome messages, and more
- π Advanced Permission Control: Restrict non-subscribers from sending or viewing messages
- π User Trial Periods: Automatically grant trial access to new group members
- π§© Modular Design: Easily extendable for additional features
A new feature has been added to improve user experience when a group is first monetized:
- 24-Hour Transition Period: When subscription requirement is first enabled for a group, existing members get a 24-hour grace period before restrictions apply
- Smart Detection: Bot automatically identifies which users were members before monetization
- Automatic Notifications: Both group-wide announcements and individual DMs are sent to notify members about the upcoming requirement
- Configurable Duration: Group admins can adjust the grace period duration (default is 24 hours)
- New
monetizationDatefield added to track when subscription was first enabled - New
existingUserGracePeriodfield to configure grace period duration - Enhanced subscription permission middleware to respect the grace period
- Automated notification system to alert users about the change
This enhancement ensures a smoother transition for community members when a group switches to a subscription model.
- Node.js v14+
- MongoDB database
- Telegram Bot Token (from @BotFather)
-
Clone the repository
git clone https://github.com/yourusername/telegram-subscription-bot.git cd telegram-subscription-bot -
Install dependencies
npm install
-
Configure environment variables Create a
.envfile in the root directory:BOT_TOKEN=your_telegram_bot_token MONGODB_URI=your_mongodb_connection_string # Payment Gateway Configuration BASE_URL=https://your-server-domain.com PORT=3000 # PayFast Configuration (if using PayFast) PAYFAST_MERCHANT_ID=your_merchant_id PAYFAST_MERCHANT_KEY=your_merchant_key PAYFAST_PASSPHRASE=your_passphrase PAYFAST_SANDBOX=true # Use false for production -
Start the bot
npm start
User Commands:
- π³
/subscribe- Start subscription process - π
/status- Check your subscription status - β
/help- Display help information
Admin Commands:
- π
/admin_toggle- Toggle subscription requirement - π¬
/admin_welcome- Set welcome message - π
/admin_stats- View subscription statistics - π°
/admin_subscription- Configure subscription settings - π³
/admin_payment- Configure payment options - βοΈ
/manage- Access group management panel - π’
/my_groups- Manage your groups (in private chat)
Group administrators can configure several aspects of their groups:
- Subscription prices and currency
- Payment methods
- Welcome messages
- Subscription requirement toggle
- Message permissions for non-subscribers:
- Restrict non-subscribers from sending messages
- Restrict non-subscribers from viewing messages (auto-kick on join)
This helps maintain a paid community with minimal administrative overhead.
When enabled, this feature:
- Monitors all messages sent to the group
- Automatically deletes messages from users without an active subscription
- Notifies the user privately that they need to subscribe to send messages
- Respects existing Telegram group permissions (doesn't override group-level permissions)
When enabled, this feature:
- Automatically removes non-subscribers when they attempt to join the group
- Notifies removed users that they need to subscribe to view the group
- Users can rejoin after subscribing
Note: Group admins are exempt from these restrictions.
The User Trial feature allows group administrators to automatically grant new members a free trial subscription when they join:
- Enable User Trials: Admins can enable this feature from the group configuration menu
- Set Trial Duration: Choose how many days (1-30) new users get access for free
- Automatic Application: When a new user joins a group with trials enabled, they automatically receive a trial subscription
- User Notification: Users receive a private message from the bot informing them of their trial period and expiration date
- Seamless Conversion: When the trial expires, users are prompted to subscribe to maintain access
To configure user trials:
- Use the
/managecommand in your group or access group settings from/my_groupsin private chat - Navigate to "Group Configuration Options"
- Select "Enable User Trial Period" or "Update User Trial Period"
- Toggle the setting on/off and set your preferred trial duration
This feature helps increase conversion rates by letting users experience the value of your group before committing to a paid subscription.
The bot provides detailed analytics on:
- Total subscribers
- Revenue generated
- Active subscriptions
- Payment history
- Group activity metrics
- User engagement statistics
The bot features a robust plugin-based payment gateway architecture with a centralized webhook system that makes it easy to add new payment processors:
- PayFast: Complete integration with South African payment processor
The bot now includes a unified webhook handling system that:
- β Single Entry Point: Provides a central endpoint for all payment gateway callbacks
- π Automatic Routing: Routes webhook notifications to the appropriate payment provider
- π‘οΈ Validation & Security: Each provider handles its own signature validation and security checks
- π§© Extendable Design: Makes adding new payment gateways simpler with standardized interfaces
- π Custom Routes: Supports provider-specific webhook URLs when required
Payment gateway callbacks will be received at:
- Main endpoint:
https://your-server.com/api/payments/webhook/:provider - PayFast endpoint:
https://your-server.com/api/payments/webhook/payfast-itn
A status endpoint is also available at https://your-server.com/api/payments/webhook/status that shows active payment providers.
Payment gateways are configured through a centralized configuration system:
- Configuration File: Payment gateways are defined in
config/paymentGateways.js - Easy Management: Enable/disable gateways without code changes
- Structured Configuration: Each gateway has its own configuration schema
- Display Name Mapping: Consistent naming across the application
Example configuration:
module.exports = {
availableGateways: [
{
id: 'payfast',
name: 'π³ PayFast',
enabled: true,
configSteps: ['merchantId', 'merchantKey', 'passphrase']
},
// Additional payment gateways can be added here
],
providerDisplayNames: {
'payfast': 'π³ PayFast',
// More display names...
}
};The system is designed with a modular approach that makes adding new payment gateways straightforward:
- Define the Gateway: Add the new gateway to
config/paymentGateways.js - Implement Provider: Create a new provider class that extends
PaymentProviderin thepayment-providersdirectory - Register Provider: Add the provider to the
bot.jsinitialization
-
Add the gateway to the configuration file:
// In config/paymentGateways.js module.exports = { availableGateways: [ // ...existing gateways { id: 'newgateway', name: 'π³ New Gateway', enabled: true, configSteps: ['apiKey', 'secretKey'] } ], providerDisplayNames: { // ...existing display names 'newgateway': 'π³ New Gateway' } };
-
Create a new provider class that extends the base PaymentProvider:
// In payment-providers/newgateway/NewGatewayProvider.js const PaymentProvider = require('../PaymentProvider'); class NewGatewayProvider extends PaymentProvider { constructor(config) { super(config); this.name = "newgateway"; } // Generate payment URL for the payment gateway generatePaymentUrl(userId, amount, itemName, itemDescription, options = {}) { // Implementation } // Required method to handle webhook callbacks async handleWebhook(req, successCallback) { // Validate the webhook data const isValid = await this.validatePayment(req.body); if (!isValid) { return { status: 400, body: 'Invalid payment data' }; } // Process payment data const paymentData = this.processPaymentData(req.body); // Call success callback with payment data await successCallback(paymentData); return { status: 200, body: 'Payment processed successfully' }; } // Optional - Define a custom webhook path if needed getCustomWebhookPath() { return '/webhook/custom-newgateway-path'; } // Other required methods... } module.exports = NewGatewayProvider;
-
Register the provider in
bot.js:const NewGatewayProvider = require('./payment-providers/newgateway/NewGatewayProvider'); // Configure provider const newGatewayConfig = { apiKey: process.env.NEW_GATEWAY_API_KEY, secretKey: process.env.NEW_GATEWAY_SECRET_KEY, baseUrl: process.env.BASE_URL || 'https://your-server.com' }; // Register provider with paymentManager paymentManager.registerProvider('newgateway', new NewGatewayProvider(newGatewayConfig));
- Admin configures a payment gateway for their group
- User selects payment method when subscribing
- Bot generates a payment URL using the selected gateway
- User completes payment on the provider's site
- Provider sends webhook notification back to the bot's unified webhook endpoint
- Webhook system routes the request to the appropriate provider
- Provider validates the payment and processes the data
- Bot activates the subscription when payment is confirmed
The bot uses MongoDB to store:
- User information and subscriptions
- Group configurations and settings
- Payment history and analytics data
Key collections:
users- Stores user data and subscription informationgroups- Contains group settings, including auto-kick configurationpayments- Records payment transactions
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.
