【问题标题】:Connection error while connection has already been established已建立连接时出现连接错误
【发布时间】:2018-12-20 08:44:38
【问题描述】:

我在我的代码中使用Telethon == 1.4.3:

import telepot
import threading
from telethon import TelegramClient
from flask import Flask, request
from telepot.loop import OrderedWebhook
from telepot.delegate import (
    per_chat_id, create_open, pave_event_space, include_callback_query_chat_id)

class Main_Class(telepot.helper.ChatHandler):
    def __init__(self, *args, **kwargs):
        super(Main_Class, self).__init__(*args, **kwargs)

    def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        if content_type == 'text':
            client = TelegramClient('session_name', api_id, api_hash)
            client.connect()
            client.send_message('me', 'Hello World from Telethon!')            

app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def pass_update():
    webhook.feed(request.data)
    return 'OK'
TOKEN = my_token
bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(
        pave_event_space())(
        per_chat_id(types=['private']), create_open, Main_Class, timeout=100000),
])
webhook = OrderedWebhook(bot)

webhook.run_as_thread()

由于我也使用Flask,所以这两者相互干扰,我得到以下错误:

RuntimeError: There is no current event loop in thread 'Thread-1'

我导入asyncio并在代码中添加以下几行,问题就解决了

class Main_Class(telepot.helper.ChatHandler):
     ......
     loop = asyncio.new_event_loop()
     client = TelegramClient('session_name', api_id, api_hash,loop=loop)
     loop.run_until_complete(goo(loop,client))
     loop.close()
 .....

async def goo(loop,client):
      client.connect()
      await client.send_message('me', 'Hello World from Telethon!') 

尽管我已经建立了连接,但仍然出现以下错误:

ConnectionError: Cannot send requests while disconnected

【问题讨论】:

    标签: flask python-asyncio telethon telepot


    【解决方案1】:

    您还应该等待连接完成。因为它是异步完成的。

    async def goo(loop,client):
          await client.connect()
          await client.send_message('me', 'Hello World from Telethon!')
    

    阅读更多,here。

    【讨论】:

    • 谢谢,当我将 await 添加到 client.connect() 时,连接已建立,但我有另一个错误:线程 'Thread-4' 中没有当前事件循环
    • 我可以使用 asyncio.set_event_loop(loop) 为每个线程打开一个事件循环吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 2020-04-04
    • 2023-02-05
    • 1970-01-01
    相关资源
    最近更新 更多