python实现与AI对话

 python实现与AI对话_第1张图片

 注释很详细,代码很简洁,直接上源码

# -*- coding: utf-8 -*-

import requests
import json
import re
import time

from bs4 import BeautifulSoup

# 一些可用的用户名和token
tokens = ['da510ca1-63ff-4771-8375-fc34c977ca8f', 'b97a0ca3-2f30-4a15-809a-f27126ded0e0',
          '5cedb043-120a-43ae-9db8-535cf4c333a6', '3c6e8535-45e9-4000-ae86-ed03d6ed9600',
          'da510ca1-63ff-4771-8375-fc34c977ca81', 'da510ca1-63ff-4771-8375-fc34c977ca82',
          'da510ca1-63ff-4771-8375-fc34c977ca83', 'da510ca1-63ff-4771-8375-fc34c977ca84',
          'da510ca1-63ff-4771-8375-fc34c977ca85', 'da510ca1-63ff-4771-8375-fc34c977ca86',
          'da510ca1-63ff-4771-8375-fc34c977ca87', 'da510ca1-63ff-4771-8375-fc34c977ca88',
          'da510ca1-63ff-4771-8375-fc34c977ca89', 'da510ca1-63ff-4771-8375-fc34c977caaa',
          'da510ca1-63ff-4771-8375-fc34c977cabb', 'da510ca1-63ff-4771-8375-fc34c977cavv',
          'da510ca1-63ff-4771-8375-fc34c977cacc', 'da510ca1-63ff-4771-8375-fc34c977cass']
userNames = ['apiuser002', 'apiuser003', 'apiuser004', 'apiuser005', 'apiuser006', 'apiuser007',
             'apiuser008', 'apiuser009', 'apiuser010', 'apiuser011', 'apiuser012', 'apiuser013',
             'apiuser014', 'apiuser015', 'apiuser016', 'apiuser017', 'apiuser018', 'apiuser019']



# 当前使用的token索引
current_index = 0

prompt = input('请输入问题:')
url = 'https://www.1bit.asia/openai/api/ask'

# 是否成功标记
ok = 0
ans = ""

while True:
    # print(current_index)
    # 文本内容,token和用户名
    data = {'prompt': prompt, 'token': tokens[current_index], 'userName': userNames[current_index]}
    headers = {'Content-Type': 'application/json'}
    # 申请返回数据并处理数据
    response = requests.post(url, data=json.dumps(data), headers=headers)
    json_data = json.loads(response.text)
    answer_url = json_data['message']
    # 正则表达式提取返回数据的url
    url_pattern = r'https?://[^\s]+'
    urls = re.findall(url_pattern, answer_url)
    res = requests.get(urls[0], headers=headers)
    html_1 = res.text
    # 如果返回的是该接口额度用完则换账号进行申请
    # 如果返回思考中则等待其思考完毕返回答案,每过3s再次申请内容直到思考完毕
    # 正常返回则存入答案等待输出
    if "今日额度已用完" in html_1:
        pass
    elif "思考中" in html_1:
        while "思考中" in html_1:
            time.sleep(3)
            res = requests.get(urls[0], headers=headers)
            html_1 = res.text
            if "思考中" not in html_1:
                ans = html_1
                ok = 1
                break
        break
    else:
        ans = html_1
        ok = 1
        break

    # 更新token和userName索引,以便下一次使用不同的token和userName
    current_index = current_index + 1
    # 如果遍历到最后一个接口仍然没有可行接口则不改变ok的标记值
    if current_index == len(tokens):
        break
# 输出答案
if ok == 0:
    print("无可用接口")
else:
    print(ans)

你可能感兴趣的:(python,笔记,python,经验分享,笔记)