我在同一个循环中使用 telethon 和 quart。 我需要监听新消息,同时我想在加载页面时读取所有 channel 。
但是这样做会导致ConnectionError:断开连接时无法发送请求
,而且我不知道如何处理这个问题。在循环之前添加async with client:
将导致sqlite3.OperationalError:database islocked
。有机会实现我想要的吗?
相关代码如下:
...
executor = ProcessPoolExecutor(1)
...
# Telethon client
client = TelegramClient('bot', int(api_id), api_hash)
# Quart app
app = Quart(__name__, template_folder=None, static_folder=None, static_url_path=None)
main = Blueprint('main', __name__, template_folder='templates', static_folder='static', static_url_path='static')
...
@app.before_serving
async def startup():
client.loop.run_in_executor(executor, telethon_start)
...
@client.on(events.NewMessage(incoming=True))
async def new_chat(event):
#Do something with messages
...
@main.route('/new', methods=['GET', 'POST'])
async def new():
channels = []
async for dialog in client.iter_dialogs(): # Here the problem
channels.append((dialog.id, dialog.name))
return await render_template(
'new_channel.html',
channels=channels
)
def telethon_start():
with client:
client.run_until_disconnected()
async def start(conf):
app.register_blueprint(main, url_prefix=base_url)
await hypercorn.asyncio.serve(app, conf)
if __name__ == '__main__':
config = hypercorn.Config()
config.bind = "127.0.0.1:" + str(expose_port)
client.loop.run_until_complete(start(config))
请帮助我!
最佳答案
执行器
的使用似乎很可疑。你不应该真的需要它。
假设每次请求发生时都会调用@app.before_serving
,则每个请求也会多次连接同一个客户端。这是错误的,因为理想情况下每个客户端实例只应连接一次(不能多次重复使用同一 session )。
我的建议是,您只需在提供应用程序之前连接客户端即可,如下所示:
# @app.before_serving, startup and telethon_start removed entirely
async def start(conf):
async with client:
# ^~~~~~~~~~~ starting the client now occurs here
app.register_blueprint(main, url_prefix=base_url)
await hypercorn.asyncio.serve(app, conf)
关于python - Telethon "Cannot send requests while disconnected"在夸脱 route 获取 channel 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73888541/