Home > Back-end >  Python Telethon - Send messages at timed intervals
Python Telethon - Send messages at timed intervals

Time:11-24

I'm trying to send a message to my group at defined time intervals, but I get a warning in the output the first time I try to send the message. Next times no warning, but nothing is posted in the group. I'm the owner of the group so in theory there shouldn't be any permissions issues.

Code

from telethon import TelegramClient
import schedule

def sendImage():
    apiId = 1111111
    apiHash = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    phone = " 111111111111"
    client = TelegramClient(phone, apiId, apiHash)

    toChat = 1641242898

    client.start()

    print("Sending...")
    client.send_file(toChat, "./image.jpg", caption="Write text here")

    client.disconnect()
    return

def main():
    schedule.every(10).seconds.do(sendImage)

    while True:
        schedule.run_pending()

if __name__ == "__main__":
    main()

Output

Sending...
RuntimeWarning: coroutine 'UploadMethods.send_file' was never awaited
  client.send_file(toChat, "./image.jpg", caption="Write text here")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Sending...
Sending...
Sending...

CodePudding user response:

As the output says you need to await the response of the coroutine. The code may trigger exceptions which should be handled.

try:
    client = TelegramClient(...)
    client.start()
except Exception as e:
    print(f"Exception while starting the client - {e}")
else:
    try:
        ret_value = await client.send_file(...)
    except Exception as e:
        print(f"Exception while sending the message - {e}")
    else:
        print(f"Message sent. Return Value {ret_value}")

CodePudding user response:

Telethon uses asyncio, but schedule wasn't designed with asyncio in mind. You should consider using an asyncio-based alternative to schedule, or just use Python's builtin functions in the asyncio module to "schedule" things:

import asyncio
from telethon import TelegramClient

def send_image():
    ...
    client = TelegramClient(phone, apiId, apiHash)

    await client.start()
    await client.send_file(toChat, "./image.jpg", caption="Write text here")
    await client.disconnect()

async def main():
    while True:  # forever
        await send_image()  # send image, then
        await asyncio.sleep(10)  # sleep 10 seconds

    # this is essentially "every 10 seconds call send_image"

if __name__ == "__main__":
    asyncio.run(main())

You should also consider creating and start()ing the client inside main to avoid recreating it every time.

  • Related