Search code examples
telegramtelegram-botforwarding

How to forward messages from one channel to another in telegram using user accounts? I tried but it doesn't work, nor I get any errors


I want to forward messages from one channel to another using my user account itself, and not bot account. Online there are many codes available for this but they all only work for bots, none works with user accounts, not sure why though. So I thought to write my own.

This is my code

import os
from dotenv import load_dotenv

load_dotenv()

from telethon import TelegramClient, events

api_id = os.getenv("API_ID")
api_hash = os.getenv("API_HASH")

client = TelegramClient(os.getenv("SESSION_NAME"), api_id, api_hash)

# Log in to your account
client.start()

# Source and target channels
source_channel = os.getenv("FROM_CHANNEL_ID")
target_channel = os.getenv("TO_CHANNEL_ID")

# Get the latest messages from the source channel
async def get_messages(channel):
    messages = await client.get_messages(channel, limit=1)
    print(messages)
    return messages

# Forward the messages to the target channel
async def forward_messages(messages, channel):
    for message in messages:
        await client.forward_messages(channel, message)
        
# Get the latest messages from the source channel
messages = client.loop.run_until_complete(get_messages(source_channel))

# Forward the messages to the target channel
client.loop.run_until_complete(forward_messages(messages, target_channel))

In terminal, when I first ran the code, it asked for phone number and otp, but since then, it hasn't asked for that either and i just see only this in terminal

Server sent a very new message with ID 7229358410288965633, ignoring (see FAQ for details)
Server sent a very new message with ID 7229358410321502209, ignoring (see FAQ for details)

Solution

  • ok so finally after going through the docs i was able to solve it with this code

    import os
    from dotenv import load_dotenv
    
    load_dotenv()
    
    from telethon import TelegramClient, events
    
    api_id = os.getenv("API_ID")
    api_hash = os.getenv("API_HASH")
    
    client = TelegramClient(os.getenv("SESSION_NAME"), api_id, api_hash)
    print("Client Starting...")
    # Log in to your account
    client.start()
    print("Client Created")
    # Source and target channels
    source_channel_id = int(os.getenv("FROM_CHANNEL_ID"))
    target_channel_id = int(os.getenv("TO_CHANNEL_ID"))
    print("Channels Loaded")
    
    
    # keep getting all live messages from source channel
    @client.on(events.NewMessage(chats=source_channel_id))
    async def handler(event):
        print(event.message)
        # send message to target channel
        await client.send_message(target_channel_id, event.message)
        print("Message Sent")
    
    
    # run until disconnect
    client.run_until_disconnected()