代码如下:
import time
import telethon
import asyncio
# Enter your API ID and API hash here
api_id = 13******
api_hash = '8ba0a***********************'
# Enter the name of the text file containing the messages
message_file = 'messages.txt'
async def main():
# Connect to the Telegram API using your API ID and API hash
client = telethon.TelegramClient('sender', api_id, api_hash)
# Read the messages from the text file
with open(message_file, 'r') as f:
messages = f.readlines()
# Send the messages and pause for one minute between each message
for message in messages:
await client.send_message('@Example_recipient', message.strip())
await time.sleep(60)
# Disconnect from the Telegram API
client.disconnect()
async def run() -> asyncio.coroutine:
await main()
asyncio.run(run())
每当我运行它,它给我这个错误:
File "/usr/local/lib/python3.10/dist-packages/telethon/network/mtprotosender.py", line 173, in send
raise ConnectionError('Cannot send requests while disconnected')
ConnectionError: Cannot send requests while disconnected
asyncio.run修复了之前的错误:
RuntimeWarning: coroutine 'run' was never awaited
run()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
现在我被这个新的错误缠住了,我似乎无法解决。
试着把你的代码改成这样:
import asyncio
import telethon
api_id = 13******
api_hash = '8ba0a***********************'
message_file = 'messages.txt'
# Better style would be to have these not initiated
# at the top-level and instead behind the if name == main
# guard, but lets keep it simple.
client = telethon.TelegramClient('sender', api_id, api_hash)
with open(message_file, 'r') as f:
messages = f.readlines()
async def main():
for message in messages:
await client.send_message('@Example_recipient', message.strip())
await asyncio.sleep(60)
if __name__ == "__main__":
# The context manager will release the resource
# (i.e. call client.disconnect) for us when the
# block exits.
with client:
client.loop.run_until_complete(main())
,它更接近文档中的示例。也不清楚为什么你有60秒的等待,或者如果你想在发送消息之间等待,为什么你要使用asyncio。看起来你可以只使用telethon.sync
和块,而没有任何asyncio样板文件?
基于注释更新
with open(file) as handle:
messages = list(handle.readlines())
...
while len(messages):
first = messages.pop()
# check here before popping that the list
# isn't already empty
second = messages.pop()
await client.send_message(first)
await client.send_message(second)