我尝试按定义的时间间隔向我的组发送消息,但第一次尝试发送消息时,我在输出中收到警告。下次没有警告,但组里没有发布任何内容。我是该组的所有者,所以理论上不应该有任何权限问题。
代码
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...
Telethon 使用
asyncio
,但 schedule
的设计并未考虑到 asyncio
。您应该考虑使用基于 asyncio
的替代方案来替代 schedule
,或者仅使用 asyncio
模块中的 Python 内置函数来“安排”事情:
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())
您还应该考虑在
start()
内创建和 main
客户端,以避免每次都重新创建它。
这意味着您没有时间完成操作,请尝试以下更改:
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()
另一件事,我认为你不应该保持连接和断开连接,在我看来,client.start() 应该不在这个函数中,client.disconnect 也应该被排除在外
您从错误的位置导入,它适用于异步基础客户端 您应该从
from telethon.sync import TelegramClient
导入 Sync TelegramClient
也正如上面提到的用户考虑使用像 apsscheduler 这样的异步调度程序。
正如输出所示,您需要等待协程的响应。该代码可能会触发应该处理的异常。
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}")