Python Telethon -按时间间隔发送消息

q5iwbnjs  于 2023-01-27  发布在  Python
关注(0)|答案(3)|浏览(183)

我尝试在指定的时间间隔向我的组发送消息,但在第一次尝试发送消息时,我在输出中收到警告。下一次没有警告,但组中没有发布任何内容。我是组的所有者,因此理论上不应该有任何权限问题。

    • 代码**
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()
    • 产出**
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...
y4ekin9u

y4ekin9u1#

Telethon使用asyncio,但是schedule在设计时并没有考虑到asyncio,你应该考虑使用基于asyncioschedule替代品,或者仅仅使用Python在asyncio模块中的内置函数来“调度”事情:

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

您还应该考虑在main中创建和start()客户机,以避免每次都重新创建它。

zdwk9cvp

zdwk9cvp2#

这意味着您给予时间完成操作,请尝试以下更改:

from telethon import TelegramClient
import schedule

async def sendImage(): # <- make it async
    apiId = 1111111
    apiHash = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    phone = "+111111111111"
    client = TelegramClient(phone, apiId, apiHash)

    toChat = 1641242898

    client.start()

    print("Sending...")
    await client.send_file(toChat, "./image.jpg", caption="Write text here") # <- here too add await

    client.disconnect()
    return

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

    while True:
        schedule.run_pending()

if __name__ == "__main__":
    main()

另外我不认为你应该保持连接和断开,在我看来,客户端。开始()应该在这个函数和客户端。断开了

8i9zcol2

8i9zcol23#

正如输出所说,你需要等待协程的响应,代码可能会触发异常,而这些异常应该被处理。

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

相关问题