智能医疗平台专属定制化机器人(前后端代码)
立即下载
资源介绍:
智能医疗平台专属定制化机器人(前后端代码)
import requests
from requests.exceptions import HTTPError, RequestException
def send_message_to_bot(bot_id, user_id, message):
url = 'https://api.coze.cn/v3/chat'
headers = {
'Authorization': '',
'Content-Type': 'application/json'
}
data = {
"bot_id": bot_id,
"user_id": user_id,
"stream": True,
"auto_save_history": True,
"additional_messages": [
{
"role": "user",
"content": message,
"content_type": "text"
}
]
}
try:
with (requests.post(url, headers=headers, json=data, stream=True) as response):
response.raise_for_status() # 如果响应状态码不是 200,将抛出 HTTPError 异常
for line in response.iter_lines(): # 使用 iter_lines 迭代响应内容
if line:
json_response = line.decode('utf-8') # 解码每行 JSON 数据
yield json_response # 使用 yield 返回流式数据
except HTTPError as http_err:
yield f'HTTP 错误发生: {http_err}'
except RequestException as req_err:
yield f'请求错误发生: {req_err}'
except Exception as err:
yield f'其他错误发生: {err}'
@app.route('/send_msg', methods=['POST'])
def handle_msg():
accumulated_msgs = []
data = request.get_json()
print(data)
bot_id = ''
user_id = '123456789'
message = data.get('message')
if not bot_id or not user_id or not message:
return jsonify({'error': 'Missing required parameters (bot_id, user_id, message)'}), 400
try:
print("正在发往")
i = send_message_to_bot(bot_id, user_id, message) # 获取生成器对象
a = list(i) # 将生成器对象的值放入列表中
for c in range(len(a)):
if a[c] == 'event:conversation.message.completed':
b=a[c+1].replace("data:", "")
print(b)
if re.search('[\u4e00-\u9fff]', b): # 匹配中文字符范围
accumulated_msgs.append(b)
print(accumulated_msgs[-4])
return jsonify(accumulated_msgs[-4])
except Exception as e:
return jsonify({'error': str(e)}), 500