-
获得个人访问令牌
首先,你需要找到你的个人token(令牌)
跟随扣子官方指引 找到自己的token https://www.coze.cn/docs/developer_guides/pat
-
在扣子上制作并发布一个你的BOT
发布时,不发布到商店(选商店需要等审批),勾选 API 之后可以立刻调用。
3. 在代码中配置你的BOT和应用
打开你的空间,bot 后面的内容就是 botid
YOUR_BOT_ID = '你的 BOT ID'
第一步中 ,写入你的token YOUR_COZE_TOKEN = '你的COZE TOKEN'
Python 完整代码
import requests
import json
import uuid
YOUR_BOT_ID = '你的 BOT ID'
YOUR_COZE_TOKEN = '你的COZE TOKEN'
class ChatBot:
def __init__(self):
self.messages = []
self.input_value = ''
self.conversation_id = None
self.bot_id = YOUR_BOT_ID # 确保 bot_id 是一个有效的整数
self.user_id = self.generate_uuid() # 初始化 user_id
def generate_uuid(self):
return str(uuid.uuid4())
def send_message(self):
message = self.input_value
if not message:
return
# 检查 conversation_id 是否为 None
if not self.conversation_id:
# 如果是 None,先创建一个新的会话
self.create_empty_conversation(self.send_message)
return
# 添加用户消息到消息列表
self.messages.append({'role': 'user', 'content': message})
self.input_value = ''
access_token = YOUR_COZE_TOKEN # 确保使用正确的访问令牌
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
data = {
'conversation_id': self.conversation_id, # 可选参数
'bot_id': self.bot_id,
'user_id': self.user_id,
'stream': True, # 启用流式返回
'auto_save_history': True,
'additional_messages': [
{
'role': 'user',
'content': message,
'content_type': 'text'
}
]
}
response = requests.post('https://api.coze.cn/v3/chat', headers=headers, json=data, stream=True)
try:
response.raise_for_status() # 检查请求是否成功
for line in response.iter_lines():
if line:
decoded_line = line.decode('utf-8')
if decoded_line.startswith('event:'):
event_type = decoded_line.split(':', 1)[1].strip()
elif decoded_line.startswith('data:'):
event_data = decoded_line.split(':', 1)[1].strip()
self.handle_event(event_type, event_data)
except requests.exceptions.HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
except json.JSONDecodeError:
print('JSON decode error: 响应不是有效的 JSON 格式')
print('响应内容:', response.text)
except Exception as err:
print(f'Other error occurred: {err}')
def handle_event(self, event_type, event_data):
# 处理不同类型的事件
if event_type == 'conversation.chat.created':
data = json.loads(event_data)
print('对话已创建:', data)
elif event_type == 'conversation.chat.in_progress':
data = json.loads(event_data)
print('对话进行中:', data)
elif event_type == 'conversation.message.delta':
data = json.loads(event_data)
if data.get('role') == 'assistant':
self.messages.append({'role': 'assistant', 'content': data.get('content')})
print('助手消息:', data.get('content'))
elif event_type == 'conversation.chat.completed':
data = json.loads(event_data)
print('对话已完成:', data)
elif event_type == 'conversation.chat.failed':
data = json.loads(event_data)
print('对话失败:', data)
else:
print('未知事件类型:', event_type)
def create_empty_conversation(self, callback):
access_token = YOUR_COZE_TOKEN # 确保使用正确的访问令牌
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
data = {
'bot_id': self.bot_id,
'user_id': self.user_id
}
response = requests.post('https://api.coze.cn/v1/conversation/create', headers=headers, json=data)
try:
response.raise_for_status() # 检查请求是否成功
res_data = response.json()
if res_data.get('code') == 0:
self.conversation_id = res_data['data']['id']
self.messages.append({'role': 'system', 'content': f'空会话已创建,ID: {self.conversation_id}'})
if callback:
callback() # 执行回调函数
else:
print('创建空会话失败:', res_data.get('msg'))
except requests.exceptions.HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
except json.JSONDecodeError:
print('JSON decode error: 响应不是有效的 JSON 格式')
print('响应内容:', response.text)
except Exception as err:
print(f'Other error occurred: {err}')
if __name__ == '__main__':
# 使用示例
chat_bot = ChatBot()
chat_bot.input_value = "你好,你是谁?"
chat_bot.send_message()
pass
输出
PS C:\Users\m1391\Downloads> c:; cd 'c:\Users\m1391\Downloads'; & 'e:\python_sdk\python.exe' 'c:\Users\m1391.vscode\extensions\ms-python.debugpy-2024.12.0-win32-x64\bundled\libs\debugpy\adapter/../..\debugpy\launcher' '65377' '--' 'C:\Users\m1391\Downloads\coze-test.py'
对话已创建: {'id': '7443422541437239347', 'conversation_id': '7443422541437222963', 'bot_id': '7443362942911496207', 'created_at': 1733056865, 'last_error': {'code': 0, 'msg': ''}, 'status': 'created', 'usage': {'token_count': 0, 'output_count': 0, 'input_count': 0}, 'section_id': '7443422541437222963'}
对话进行中: {'id': '7443422541437239347', 'conversation_id': '7443422541437222963', 'bot_id': '7443362942911496207', 'created_at': 1733056865, 'last_error': {'code': 0, 'msg': ''}, 'status': 'in_progress', 'usage': {'token_count': 0, 'output_count': 0, 'input_count': 0}, 'section_id': '7443422541437222963'}
助手消息: 我
助手消息: 是
助手消息: 微信
助手消息: AI
助手消息: 我
助手消息: 是
助手消息: 微信
助手消息: AI
助手消息:
助手消息: 助手
助手消息: ,
助手消息: 能
助手消息: 为
助手消息: 您
助手消息:
助手消息: 助手
助手消息: ,
助手消息: 能
助手消息: 为
助手消息: 您
助手消息: 解答
助手消息: 微信
助手消息: 解答
助手消息: 微信
助手消息: 使用
助手消息: 相关
助手消息: 使用
助手消息: 相关
助手消息: 问题
助手消息: 或
助手消息: 提供
助手消息: 一般性
助手消息: 知识
助手消息: 的
助手消息: 帮助
助手消息: 。
助手消息:
未知事件类型: conversation.message.completed
未知事件类型: conversation.message.completed
未知事件类型: conversation.message.completed
未知事件类型: conversation.message.completed
未知事件类型: conversation.message.completed
对话已完成: {'id': '7443422541437239347', 'conversation_id': '7443422541437222963', 'bot_id': '7443362942911496207', 'created_at': 1733056865, 'completed_at': 1733056868, 'last_error': {'code': 0, 'msg': ''}, 'status': 'completed', 'usage': {'token_count': 281, 'output_count': 23, 'input_count': 258}, 'section_id': '7443422541437222963'}
未知事件类型: done