提问人:Bohdan Liutko 提问时间:11/16/2023 更新时间:11/16/2023 访问量:22
如果用户等待很长时间并开始新的请求,我需要取消请求
I need to cancel request if user waiting to long and start new one
问:
我正在使用 aoigram 构建电报聊天机器人,所以一切都是异步的,我需要连接 openai 一旦用户发送 reuest 并等待很长时间或改变主意,我希望他能够取消它,并在需要时开始一个新的 所以它应该用 /start 取消 在这里我所拥有的
@dp.message_handler(Regexp(r'.*/start.*'), state='*')
async def start(message: types.Message, state: FSMContext):
chat_id = message.chat.id
global ongoing_tasks
if chat_id in ongoing_tasks and not ongoing_tasks[chat_id].done():
ongoing_tasks[chat_id].cancel()
del ongoing_tasks[chat_id]
current_state = await state.get_state()
if current_state:
await state.finish()
在这里,用户将发送请求
@dp.message_handler(state=TaskCreation.ImprovementDetails)
async def process_improvement_details(message: types.Message, state: FSMContext):
improvement_details = message.text
global running_tasks
chat_id = message.chat.id
start_time = time.time()
await message.answer('Треба подумати кілька секунд)')
user_data = await state.get_data()
description = user_data.get("description")
response_text = ""
if improvement_details != "":
response_text = ""
# improvement_details = None # or some default value
if chat_id in ongoing_tasks and not ongoing_tasks[chat_id].done():
ongoing_tasks[chat_id].cancel()
task = asyncio.create_task(
send_request("generate_response/", {"text": message.text, "chat_id": chat_id})
)
ongoing_tasks[chat_id] = task
try:
response = await task
await wait_for_response(response, message) # here just igame that appear once waiting for responce
except asyncio.CancelledError:
await message.answer("Task was cancelled.")
return
finally:
# Cleanup the task from the tracking dictionary
if chat_id in ongoing_tasks:
del ongoing_tasks[chat_id]
以及我如何发送请求
url = urljoin(BACKEND_URL, endpoint)
async with aiohttp.ClientSession() as session:
try:
async with session.post(url, json=data) as response:
if response.status == 200:
return await response.json()
else:
print(f"Error: Server responded with status code {response.status}")
return None
except aiohttp.ClientError as e:
print(f"Connection error: {e}")
return None```
once I type /start to cancel it all during waiting for response here what I have
`Connection error: HTTPConnectionPool(host='46.101.4.220', port=32191): Max retries exceeded with url: /gen/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001FCCD269790>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))
`
please help
答: 暂无答案
评论