xunfei.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. const crypto = require('crypto')
  2. const ws = require("ws")
  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 xfconfig 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. xf_url = await getConfigValue('APIUrl')
  26. xf_APIKey = await getConfigValue('APIKey')
  27. xf_APISecret = await getConfigValue('APISecret')
  28. xf_app_id = await getConfigValue('app_id')
  29. xf_temperatureStr = await getConfigValue('temperature')
  30. xf_maxTokensStr = await getConfigValue('max_tokens')
  31. xf_domain = await getConfigValue('domain')
  32. xf_temperature = parseFloat(xf_temperatureStr)
  33. xf_max_tokens = parseInt(xf_maxTokensStr)
  34. } catch (error) {
  35. console.error('加载讯飞接口设置失败!', error)
  36. }
  37. }
  38. // 调用函数加载配置信息
  39. (async () => {
  40. try {
  41. await loadConfigValues();
  42. } catch (error) {
  43. console.error('加载讯飞接口设置失败!', error);
  44. }
  45. })()
  46. async function getXunfeiMessage(message) {
  47. const dateString = new Date().toGMTString()
  48. const parsedUrl = new URL(xf_url)
  49. const host = parsedUrl.hostname
  50. const path = parsedUrl.pathname
  51. let tmp = `host: ${host}
  52. date: ${dateString}
  53. GET ${path} HTTP/1.1`
  54. let signature = crypto.createHmac('sha256', xf_APISecret)
  55. .update(tmp)
  56. .digest('base64')
  57. const authorization_origin =
  58. `api_key="${xf_APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`
  59. let buff = Buffer.from(authorization_origin)
  60. const authorization = buff.toString('base64')
  61. const signUrl =
  62. `wss://${host}${path}?authorization=${authorization}&date=${encodeURIComponent(dateString)}&host=${host}`
  63. return new Promise((resolve, reject) => {
  64. const sock = new ws(signUrl)
  65. sock.on("open", function () {
  66. sock.send(JSON.stringify({
  67. "header": {
  68. "app_id": xf_app_id,
  69. },
  70. "parameter": {
  71. "chat": {
  72. "domain": xf_domain,
  73. "temperature": xf_temperature,
  74. "max_tokens": xf_max_tokens,
  75. }
  76. },
  77. "payload": {
  78. "message": {
  79. "text": [{
  80. "role": "user",
  81. "content": message
  82. },]
  83. }
  84. }
  85. }))
  86. })
  87. let apiMessage = ''
  88. sock.on("error", function (err) {
  89. let errMessage = '获取消息失败!'+err.message
  90. reject(errMessage)
  91. })
  92. sock.on("close", function () {
  93. resolve(apiMessage)
  94. })
  95. sock.on("message", function (data) {
  96. let recMessage = JSON.parse(data.toString())
  97. if (recMessage.payload && recMessage.payload.choices && recMessage.payload.choices.text) {
  98. apiMessage += recMessage.payload.choices.text[0].content
  99. } else {
  100. console.log("无法识别的消息",recMessage)
  101. }
  102. })
  103. })
  104. }
  105. // 更新api设置到数据库
  106. function updateXunfeiConfig(configName, configValue) {
  107. const query = 'REPLACE INTO xfconfig (config, value) VALUES (?, ?)'
  108. db.run(query, [configName, configValue], (err) => {
  109. if (err) {
  110. console.error('更新数据失败:', err)
  111. }
  112. loadConfigValues()
  113. })
  114. }
  115. module.exports = { updateXunfeiConfig, getXunfeiMessage }