ChatGPT.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. const axios = require('axios')
  2. const config = require('../config')
  3. const sqlite3 = require('sqlite3')
  4. //sqlite数据库路径
  5. let sqliteDbPath = "./db/data.db"
  6. //打开数据库
  7. var db = new sqlite3.Database(sqliteDbPath)
  8. function getConfigValue(configName) {
  9. return new Promise((resolve, reject) => {
  10. const query = 'SELECT value FROM apiconfig WHERE config = ?';
  11. db.get(query, [configName], (err, row) => {
  12. if (err) {
  13. reject(err);
  14. } else {
  15. const configValue = row ? row.value : null;
  16. // 处理字符串 'null',如果是 'null' 则返回 null
  17. resolve(configValue === 'null' ? null : configValue)
  18. }
  19. });
  20. });
  21. }
  22. // 读取配置信息并设置相应的变量
  23. async function loadConfigValues() {
  24. try {
  25. apiKey = await getConfigValue('apiKey')
  26. apiUrl = await getConfigValue('apiUrl')
  27. app_code = await getConfigValue('app_code')
  28. suffix = await getConfigValue('suffix')
  29. model = await getConfigValue('model')
  30. console.log('api接口设置加载成功');
  31. } catch (error) {
  32. console.error('加载api接口设置失败!', error);
  33. }
  34. }
  35. // 调用函数加载配置信息
  36. loadConfigValues()
  37. async function sendMessageToAPI(message) {
  38. const requestData = {
  39. app_code: app_code,
  40. messages: [{ "role": "user", "content": message }],
  41. model: model
  42. }
  43. const token = "Bearer " + apiKey
  44. try {
  45. const responseData = await axios.post(apiUrl, requestData, {
  46. headers: { 'Content-Type': 'application/json', Authorization: token }
  47. })
  48. const apiData = responseData.data
  49. const apiMessage = apiData.choices[0].message.content
  50. return apiMessage
  51. } catch (error) {
  52. console.error("向api接口发送请求时出现错误")
  53. return error
  54. }
  55. }
  56. // 更新api设置到数据库
  57. function updateapiConfigValue(configName, configValue) {
  58. const query = 'REPLACE INTO apiconfig (config, value) VALUES (?, ?)';
  59. db.run(query, [configName, configValue], (err) => {
  60. if (err) {
  61. console.error('更新数据失败:', err);
  62. } else {
  63. console.log('更新数据成功');
  64. }
  65. });
  66. }
  67. // 设置是否自动回复
  68. function setApiKey(value) {
  69. apiKey = value;
  70. updateapiConfigValue('apiKey', value);
  71. }
  72. function setApiUrl(value) {
  73. apiUrl= value;
  74. updateapiConfigValue('apiUrl', value);
  75. }
  76. function setapp_code(value) {
  77. app_code = value;
  78. updateapiConfigValue('app_code', value);
  79. }
  80. function setmodel(value) {
  81. model = value
  82. updateapiConfigValue('model', value);
  83. }
  84. module.exports = { sendMessageToAPI, setApiKey, setApiUrl, setapp_code , setmodel}