【问题标题】:send "hi" to all contacts in telegram using telethon使用 Telethon 向电报中的所有联系人发送“hi”
【发布时间】:2021-06-11 19:54:50
【问题描述】:

我在 python3.7 中使用 Telethon。 我想获取我所有联系人的列表并向他们发送“嗨”。

代码:

async def main():

try:
    async with TelegramClient('anon', api_id, api_hash) as client:
        result = await client(functions.contacts.GetContactsRequest(
        hash=0
        ))
        await print(result.stringify())
except Exception as e:
    print(e)

for u in result.users:
    await client.send_message(InputPeerUser(u.id, u.access_hash), "hi")

with client:
    client.loop.run_until_complete(main())

但我得到了错误:raise ConnectionError('Cannot send requests while disconnected') ConnectionError:断开连接时无法发送请求

【问题讨论】:

    标签: python-3.x telegram telethon


    【解决方案1】:

    with client 在您进入with 块时调用客户端上的start(),并在您退出它时调用disconnectclient.send_messagewith 块之外,所以它失败了。这是正确的做法:

    import asyncio
    
    async def main():
        async with TelegramClient('anon', api_id, api_hash) as client:
            result = await client(functions.contacts.GetContactsRequest(hash=0))
            for u in result.users:
                await client.send_message(u, "hi")
    
    asyncio.run(main())
    

    如果您需要在外部定义客户端,请改为:

    client = TelegramClient('anon', api_id, api_hash)
    
    async def main():
        # code using client...
    
    with client:
        client.loop.run_until_complete(main())
    

    (或async with clientmain())。

    【讨论】:

    • 运行你的第一个,它显示错误:result = await future telethon.errors.rpcerrorlist.PeerFloodError: Too many requests (caused by SendMessageRequest)
    • 那是因为您太快地尝试向太多不同的帐户发送消息。您也不应该向官方客户发送消息。
    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2017-11-19
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    相关资源
    最近更新 更多