Skip to content

Commit

Permalink
Added initial project files with README.md
Browse files Browse the repository at this point in the history
- Added the main script for forwarding messages between Telegram channels
- Created README.md with instructions on setup, usage, and installation
- Included MIT License
  • Loading branch information
alimahdibahrami committed Aug 31, 2024
1 parent f198d09 commit 33f4839
Show file tree
Hide file tree
Showing 2 changed files with 148 additions and 0 deletions.
72 changes: 72 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Telegram Channel Forwarder

A Python script that forwards messages from one Telegram channel to another using the Telethon library. This script supports both text and media messages and keeps track of the last forwarded message to avoid duplicates.

## Features

- **Forward text and media messages**: Forward text and media messages from a source channel to a destination channel.
- **Track last sent message**: Keeps track of the last sent message to avoid duplicate forwarding.
- **Persistent Telegram session**: The session is saved locally, so you don’t need to re-enter the login code every time you run the script. This prevents getting temporarily blocked by Telegram for too many login requests.
- **Resume from the last sent message**: If the program stops for any reason (e.g., internet issues), it can resume from the last sent message after restarting.
- **Random delay between messages**: Random delay between messages to avoid being flagged by Telegram.

## Prerequisites

- Python 3.7 or higher
- Telethon library

## Installation

1. **Clone the Repository**

```bash
git clone https://github.com/yourusername/telegram-channel-forwarder.git
cd telegram-channel-forwarder
```

2. **Install Dependencies**

Install the required Python libraries using pip:

```bash
pip install telethon
```

## Getting Started

1. **Obtain API Credentials from Telegram**

To use this script, you need to get your `api_id` and `api_hash` from the [Telegram API Development Tools](https://my.telegram.org/apps).

2. **Configure the Script**

Open the `script.py` file and fill in the following variables:

```python
api_id = 'YOUR_API_ID'
api_hash = 'YOUR_API_HASH'
phone_number = '+YOUR_PHONE_NUMBER'
session_name = 'YOUR_SESSION_NAME'
source_channel_id = 'SOURCE_CHANNEL_ID'
destination_channel_id = 'DESTINATION_CHANNEL_ID'
```

3. **Run the Script**

Run the script with Python:

```bash
python script.py
```

The script will ask for a login code sent to your Telegram app if it is the first time you are running it. Enter the code to authenticate.

## How It Works

- The script connects to the Telegram client using the provided credentials.
- It fetches messages from the specified source channel and forwards them to the destination channel.
- A JSON file (`last_message.json`) is used to keep track of the last sent message, ensuring no message is sent twice.

## License

This project is licensed under the MIT License - see the [LICENSE](https://github.com/alimahdibahrami/telegram-channel-forwarder/blob/main/LICENSE) file for details.
76 changes: 76 additions & 0 deletions script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import asyncio # Importing asyncio for asynchronous operations
from telethon import TelegramClient # Importing the TelegramClient from the Telethon library for interacting with Telegram API
from telethon.tl.types import MessageMediaPhoto, MessageMediaDocument # Importing necessary Telegram types for handling media messages
import json # Importing JSON module to handle reading and writing JSON files
import os # Importing os module to interact with the operating system (e.g., file operations)
import random # Importing random module to add random delays

# Initial settings for Telegram API access
api_id = 'YOUR_API_ID' # Your Telegram API ID
api_hash = 'YOUR_API_HASH' # Your Telegram API Hash
phone_number = '+YOUR_PHONE_NUMBER' # Your phone number with country code
session_name = 'YOUR_SESSION_NAME' # Session name for the Telegram client

# Channel IDs for the source and destination channels
source_channel_id = 'SOURCE_CHANNEL_ID' # Source channel ID
destination_channel_id = 'DESTINATION_CHANNEL_ID' # Destination channel ID

# File to store the ID of the last sent message
last_message_file = 'last_message.json'

async def handle_telegram_session(client):
"""
Main function to handle fetching messages from the source channel and sending them to the destination channel.
It keeps track of the last sent message to avoid duplicates.
"""
# Retrieving the last sent message ID
last_message = None
if os.path.exists(last_message_file):
with open(last_message_file, 'r') as f:
try:
last_message = json.load(f)
except json.JSONDecodeError:
last_message = None

# Fetching all messages from the source channel starting from the first message
async for message in client.iter_messages(source_channel_id, reverse=True):
if last_message and message.id <= last_message['id']:
continue # Skip messages that have already been sent

# Sending text messages to the destination channel
if message.text:
await client.send_message(destination_channel_id, message.text)
# Sending media messages (photos or documents) to the destination channel
if message.media:
if isinstance(message.media, (MessageMediaPhoto, MessageMediaDocument)):
await client.send_file(destination_channel_id, message.media)

# Save the last sent message ID
with open(last_message_file, 'w') as f:
json.dump({'id': message.id}, f)

print(f"Message {message.id} sent successfully")

# Random delay between 3 to 10 seconds between each message to avoid being flagged by Telegram
await asyncio.sleep(random.uniform(3, 10))

async def main():
"""
Main function to initialize the Telegram client and manage user authorization.
"""
try:
# Creating the client and connecting to Telegram
async with TelegramClient(session_name, api_id, api_hash) as client:
# If the session file does not exist, request the login code
if not await client.is_user_authorized():
await client.send_code_request(phone_number)
code = input('Enter the code you received: ')
await client.sign_in(phone_number, code)

# Execute the main session handling function
await handle_telegram_session(client)
except Exception as e:
print(f"An error occurred: {e}")

# Running the main function
asyncio.run(main())

0 comments on commit 33f4839

Please sign in to comment.