Certainly! Below is a detailed Python script that will read messages from a Telegram channel and store them in a Firebase backend. The script uses the Telethon library to interact with the Telegram API and the Firebase Admin SDK to interact with Firebase. I've included step-by-step instructions and comments to help you set everything up.
Prerequisites
- Python 3.6+: Ensure you have Python installed on your system.
- Telegram API Credentials: You'll need an API ID and API hash from Telegram.
- Firebase Project: You'll need to set up a Firebase project and obtain a service account key JSON file.
Step 1: Get Telegram API Credentials
- Visit: my.telegram.org
- Login with your Telegram account.
- Navigate to the API development tools.
- Create a new application:
- Provide an app title and a short name.
- Save your
API ID and API Hash.
Step 2: Create a Firebase Project and Service Account
- Visit: Firebase Console
- Create a new project or use an existing one.
- Navigate to Project Settings (Gear icon).
- Go to the Service Accounts tab.
- Click on Generate new private key.
- Save the downloaded JSON file (e.g.,
serviceAccountKey.json).
Step 3: Install Required Python Libraries
Open your terminal or command prompt and run:
pip install telethon firebase-admin
Step 4: Write the Script
Create a new Python file (e.g., telegram_to_firebase.py) and paste the following code:
import asyncio
from telethon import TelegramClient, events
import firebase_admin
from firebase_admin import credentials, firestore
# Replace these with your own values
api_id = 'YOUR_TELEGRAM_API_ID'
api_hash = 'YOUR_TELEGRAM_API_HASH'
channel_username = 'YOUR_CHANNEL_USERNAME' # e.g., 'https://t.me/your_channel'
# Path to your Firebase service account key
firebase_cred_path = 'path/to/serviceAccountKey.json'
# Initialize Firebase Admin SDK
cred = credentials.Certificate(firebase_cred_path)
firebase_admin.initialize_app(cred)
db = firestore.client()
# Initialize Telegram Client
client = TelegramClient('session_name', api_id, api_hash)
# Function to save message to Firebase Firestore
def save_message_to_firebase(message):
doc_ref = db.collection('telegram_messages').document(str(message.id))
doc_ref.set({
'id': message.id,
'message': message.message,
'date': message.date.isoformat(),
'sender_id': message.sender_id,
'channel_id': message.to_id.channel_id
})
print(f"Message {message.id} saved to Firebase.")
async def main():
# Start the client
await client.start()
# Get the channel entity
channel = await client.get_entity(channel_username)
# Fetch and store the last 100 messages (optional)
async for message in client.iter_messages(channel, limit=100):
save_message_to_firebase(message)
# Event handler for new messages
@client.on(events.NewMessage(chats=channel))
async def handler(event):
message = event.message
save_message_to_firebase(message)
print("Listening for new messages...")
# Keep the script running
await client.run_until_disconnected()
# Run the main function
with client:
client.loop.run_until_complete(main())
Step 5: Configure the Script
Replace the placeholder values with your own:
api_id: Your Telegram API ID.
api_hash: Your Telegram API Hash.
channel_username: The username or link of your Telegram channel (e.g., '@your_channel' or 'https://t.me/your_channel').
firebase_cred_path: The path to your Firebase service account key JSON file.
Understanding the Script
- Imports:
telethon is used to interact with Telegram.
firebase_admin is used to interact with Firebase.
- Firebase Initialization:
- Credentials are loaded, and the Firestore client is initialized.
- Telegram Client Initialization:
- A session is created with your API credentials.
save_message_to_firebase Function:
- Saves each message as a document in the
telegram_messages collection.
- Uses the message ID as the document ID to prevent duplicates.
main Function:
- Starts the Telegram client.
- Retrieves the channel entity.
- (Optional) Fetches and stores the last 100 messages from the channel.
- Sets up an event handler to listen for new messages and saves them to Firebase.
- Running the Script:
- The script runs
main within the client's loop and keeps running until disconnected.
Step 6: Run the Script
In your terminal or command prompt, navigate to the directory containing your script and run:
python telegram_to_firebase.py
Additional Notes
-
Message Fields:
message.id: Unique ID of the message.
message.message: The text content of the message.
message.date: Timestamp of the message.
message.sender_id: ID of the sender (will be None in channels).
message.to_id.channel_id: ID of the channel.
-
Security:
- Ensure your
serviceAccountKey.json file is kept secure and not exposed publicly.
- Consider using environment variables or a configuration file to store sensitive information.
-
Error Handling:
- For production use, add error handling to manage exceptions that may occur during execution.
-
Firestore Structure:
- Messages are stored in the
telegram_messages collection.
- Each document's ID is the Telegram message ID, which ensures uniqueness.
Advanced Usage
- Filtering Messages:
- You can modify the event handler to filter messages based on content or other criteria.
- Storing Additional Data:
- If you need to store media or other message attributes, extend the
save_message_to_firebase function accordingly.
- Real-time Updates:
- Utilize Firebase's real-time capabilities to reflect new messages in your applications instantly.
Conclusion
By running this script, you'll have a system that listens to your specified Telegram channel and stores each message in your Firebase backend. This setup is ideal for personal note-taking, archiving important messages, or building applications that require synchronization between Telegram and Firebase.
Feel free to customize the script to suit your specific needs!