ChatGPT.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. const axios = require('axios')
  2. const sqlite3 = require('sqlite3')
  3. //打开数据库
  4. const db = new sqlite3.Database("./db/data.db")
  5. function getConfigValue(configName) {
  6. return new Promise((resolve, reject) => {
  7. const query = 'SELECT value FROM gptconfig WHERE config = ?';
  8. db.get(query, [configName], (err, row) => {
  9. if (err) {
  10. reject(err);
  11. } else {
  12. const configValue = row ? row.value : null;
  13. // 处理字符串 'null',如果是 'null' 则返回 null
  14. resolve(configValue === 'null' ? null : configValue)
  15. }
  16. });
  17. });
  18. }
  19. // 读取配置信息并设置相应的变量
  20. async function loadConfigValues() {
  21. try {
  22. apiKey = await getConfigValue('apiKey')
  23. apiUrl = await getConfigValue('apiUrl')
  24. app_code = await getConfigValue('app_code')
  25. model = await getConfigValue('model')
  26. } catch (error) {
  27. console.error('加载api接口设置失败!', error)
  28. }
  29. }
  30. // 调用函数加载配置信息
  31. loadConfigValues()
  32. async function getGPTMessage(message) {
  33. const requestData = {
  34. app_code: app_code,
  35. messages: [{ "role": "user", "content": message }],
  36. model: model
  37. }
  38. const token = "Bearer " + apiKey
  39. try {
  40. const responseData = await axios.post(apiUrl, requestData, {
  41. headers: { 'Content-Type': 'application/json', Authorization: token }
  42. })
  43. const apiMessage = responseData.data.choices[0].message.content
  44. return apiMessage
  45. } catch (error) {
  46. console.error("向api接口发送请求时出现错误")
  47. return error
  48. }
  49. }
  50. // 更新api设置到数据库
  51. function updateGPTConfig(configName, configValue) {
  52. const query = 'REPLACE INTO gptconfig (config, value) VALUES (?, ?)';
  53. db.run(query, [configName, configValue], (err) => {
  54. if (err) {
  55. console.error('更新数据失败:', err);
  56. }
  57. loadConfigValues()
  58. })
  59. }
  60. module.exports = { updateGPTConfig, getGPTMessage }