skip to Main Content

I’m working on a Telegram bot using the Telethon library in Python to fetch the last message from a source channel and forward it to a target channel. The bot connects to my account and asks for the authentication code sent to my Telegram app. However, after entering the code, the script hangs indefinitely without any error messages or further output.

Here’s the code I’ve been using:

import asyncio
from telethon.sync import TelegramClient
from telethon.sessions import StringSession
import socks

api_id = 'YOUR_API_ID'
api_hash = 'YOUR_API_HASH'

phone_number = 'YOUR_PHONE_NUMBER'  # Include country code, e.g., +1XXXXXXXXXX

source_channel = '@source_channel_username'
target_channel = '@target_channel_username'

# Proxy settings
proxy_host = 'YOUR_SOCKS5_HOST'
proxy_port = YOUR_SOCKS5_PORT
proxy_username = 'PROXY_USERNAME'  # If the proxy requires authentication
proxy_password = 'PROXY_PASSWORD'  # If the proxy requires authentication

# Session storage
session_string = ''

async def main():
    async with TelegramClient(StringSession(session_string), api_id, api_hash, proxy=(socks.SOCKS5, proxy_host, proxy_port, True, proxy_username, proxy_password), sequential_updates=True) as client:
        print("Connecting to account...")
        # Login with your phone number
        await client.start(phone_number)
        print("Successfully connected to account.")

        print("Fetching the last message...")
        # Fetch the last message from the source channel
        last_message = await client.get_messages(source_channel, limit=1)
        print("Last message fetched.")
        
        # Delay before sending the message
        await asyncio.sleep(3)

        # Copy and send the message to the target channel
        if last_message:
            message_text = last_message[0].text
            message_media = last_message[0].media

            print("Sending message...")
            if message_media is not None:
                await client.send_message(target_channel, message_text, file=message_media)
            else:
                await client.send_message(target_channel, message_text)
            print("Successfully copied and sent the last message.")
        else:
            print("No messages found in the source channel.")

        # Save the session string after a successful login
        saved_session_string = client.session.save()
        print("Session saved. Copy this string and use it on the next launch:")
        print(saved_session_string)

# Run the asynchronous function main() using asyncio.run()
asyncio.run(main())

The issue occurs after the following output:

Please enter your phone (or bot token): +XXXXXXXXXXX
Please enter the code you received: XXXXX

After this point, there are no more messages, and the script seems to hang forever. My Telegram app shows that the bot is connected and has an active session.

I’ve already tried adding a delay before sending the message and using "sequential_updates=True" when creating the "TelegramClient" object, but it didn’t help. Any suggestions or solutions would be greatly appreciated. Thanks in advance!

2

Answers


  1. telethon.sync is meant to be used without await. use from telethon import import TelegramClient instead.

    Login or Signup to reply.
  2. You likely have an account password enabled. Telethon uses Python’s getpass module to prompt for this password. Unfortunately, getpass.getpass doesn’t always play very nice with all terminals.

    Depending on your terminal, it is possible Telethon attempted to ask for your password, but no output was shown. You should still be able to type in your password (although you will not see any characters being typed) and press enter to send it.

    Otherwise, since you can also provide the password in your script. Note however that in v1 with calls start(), which doesn’t give you a chance to do that.

    async with TelegramClient(...) as client:
        # ^^^^ this called `start()` already!
        ...
        # The next line doesn't do anything.
        # `with` already called `start` and went through the interactive flow.
        await client.start(...)
    

    But you can call start before with by doing it like so:

    async with TelegramClient(...).start(...) as client:
        ...                     # ^^^^^^^^^^^ you can pass any parameters here, including phone and password
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search