简体   繁体   中英

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

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM