Search code examples
pythonpython-3.xtelethon

How can I send messages to my private telegram channel with Telethon?


I want to send a message to a private telegram channel using python with Telethon.

What I tried:

from telethon import TelegramClient
from telethon.tl.types import Channel

client = TelegramClient('fx', api id, "API hash")
client.start()


def sendMSG(channel, msg):
    entity = client.get_entity(channel)
    client.send_message(entity = entity,message=msg)


sendMSG("Channel Name", "Hello")

But this code gives me this error:

RuntimeWarning: coroutine 'UserMethods.get_entity' was never awaited
  sendMSG("Channel", "Hello")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

Solution

  • Telethon is an asynchronous library. This means you need to await almost everything.

    import asyncio
    
    async def sendMSG(channel, msg):
        entity = client.get_entity(channel)
        await client.send_message(entity = entity,message=msg)
    
    
    asyncio.run(sendMSG("Channel Name", "Hello"))