Search code examples
pythonpython-3.xtelegramtelegram-bottelethon

The forwarding robot code based on telethon can run but does not work


import telethon
api_id = XX
api_hash = 'XX'
client = telethon.TelegramClient('anon', api_id, api_hash)
async def main():
    await client.connect()
    me = await client.get_me()
    chat_id = me.id
    while True:
        messages = await client.get_messages(chat_id)
        for message in messages:
            if "vi_" in message.text or "ai_" in message.text:
                await client.forward_messages('user', message.id)
with client:
    client.loop.run_until_complete(main())

When I sent a message containing vi_ or ai_, the robot did not forward it.

I want the robot to receive a new message containing vi_ or ai_ and immediately forward it to the user.


Solution

  • In Telethon v1, with already calls start() (which connect()s). There is no need to connect() inside the async def.

    You have an endless loop constantly getting the latest message. This is likely to lead to flood waits. You probably want to use events instead.

    forward_messages often needs to know where to forward the message from. You can specify that as the third parameter.