Creating a Telegram bot that facilitates mobile recharges requires careful planning and execution due
to the interactions with external payment and mobile recharge APIs. Below is a step-by-step guide to
help you develop a basic Telegram bot for mobile recharges using Python and the `python-telegram-
bot` library.
### Prerequisites
1. **Python 3.6+**:
Ensure Python is installed on your development machine. You can download it from [python.org]
(https://www.python.org/downloads/).
2. **Python Libraries**:
Install the necessary Python libraries using pip:
```bash
pip install python-telegram-bot requests
```
3. **Telegram Bot Token**:
Create a new bot on Telegram by chatting with [BotFather](https://t.me/botfather) and follow the
steps to get your bot token.
4. **Recharge API**:
You will need access to a mobile recharge API. For demonstration, I'll outline how you might
structure the bot assuming you have such an API (like Reloadly, Twilio for SMS confirmation, etc.).
Ensure you have the API keys and any necessary permissions set up.
### Example Bot Overview
This bot will:
- Start a conversation with the user to get the mobile number and recharge amount.
- Confirm the details with the user before proceeding.
- Use a mock recharge function to simulate the recharge process.
- Inform the user of the success or failure of their recharge.
### Step-by-Step Guide to Create the Bot
#### 1. Define the Bot Structure and Imports
```python
from telegram import Update, ReplyKeyboardMarkup, ReplyKeyboardRemove
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters,
ConversationHandler, CallbackContext
import logging
# Enable logging for debugging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# Define states for the conversation
PHONE, AMOUNT, CONFIRMATION = range(3)
```
#### 2. Start the Conversation
```python
def start(update: Update, context: CallbackContext) -> int:
# Send a message when the command /start is issued.
update.message.reply_text(
'Hi! Welcome to the Recharge Bot. Please enter your phone number.'
return PHONE
```
#### 3. Get and Store the Phone Number
```python
def phone(update: Update, context: CallbackContext) -> int:
user = update.message.from_user
logger.info("Phone number of %s: %s", user.first_name, update.message.text)
context.user_data['phone'] = update.message.text
update.message.reply_text(
'Thank you! Now, please send me the recharge amount.'
return AMOUNT
```
#### 4. Get and Store the Recharge Amount
```python
def amount(update: Update, context: CallbackContext) -> int:
user = update.message.from_user
logger.info("Amount for %s: %s", user.first_name, update.message.text)
context.user_data['amount'] = update.message.text
# Ask for confirmation
update.message.reply_text(
f'You are recharging {context.user_data["phone"]} with {context.user_data["amount"]} units.\n'
'Is this correct? (yes/no)'
return CONFIRMATION
```
#### 5. Confirm and Process the Recharge
```python
def confirmation(update: Update, context: CallbackContext) -> int:
user_input = update.message.text.lower()
if user_input in ['yes', 'y']:
phone = context.user_data['phone']
amount = context.user_data['amount']
if process_recharge(phone, amount):
update.message.reply_text('Recharge successful!')
else:
update.message.reply_text('Recharge failed. Please try again later.')
else:
update.message.reply_text('Recharge canceled. Please start over with /start.')
return ConversationHandler.END
```
#### 6. Mock Recharge Function
This function is a placeholder for where you would integrate with an actual recharge API.
```python
def process_recharge(phone: str, amount: str) -> bool:
# In a real application, you would make an API call to a service to recharge the phone
logger.info("Recharging phone %s with amount %s", phone, amount)
# Simulate a successful recharge operation
return True
```
#### 7. Cancel the Conversation
```python
def cancel(update: Update, context: CallbackContext) -> int:
update.message.reply_text('Recharge operation canceled.')
return ConversationHandler.END
```
#### 8. Error Handler
```python
def error(update: Update, context: CallbackContext):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, context.error)
```
#### 9. Main Function to Start the Bot
```python
def main() -> None:
"""Start the bot."""
# Create the Updater and pass it your bot's token.
updater = Updater("YOUR_TELEGRAM_BOT_TOKEN")
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
# Add conversation handler with the states
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
PHONE: [MessageHandler(Filters.text & ~Filters.command, phone)],
AMOUNT: [MessageHandler(Filters.text & ~Filters.command, amount)],
CONFIRMATION: [MessageHandler(Filters.text & ~Filters.command, confirmation)]
},
fallbacks=[CommandHandler('cancel', cancel)]
)
dispatcher.add_handler(conv_handler)
# Log all errors
dispatcher.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until the user presses Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT
updater.idle()
```
#### 10. Run the Bot
To run the bot, ensure you replace `"YOUR_TELEGRAM_BOT_TOKEN"` with your actual bot token and
execute the script.
### Additional Notes
- **Security**: Be cautious with user input and ensure no sensitive information is logged or
mishandled.
- **Testing**: Thoroughly test each part of your bot, especially the integration with the recharge API.
- **Scalability**: If your bot gains traction, consider using a more scalable approach with webhooks
instead of polling.
This bot is a basic prototype. Depending on the APIs and the specific requirements you have, you
would need to expand and adapt it, particularly in error handling and integrating with payment and
recharge services.