main.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. const { WechatyBuilder } = require("wechaty")
  2. const { getGPTMessage } = require('../API/ChatGPT')
  3. const { getXunfeiMessage } = require('../API/xunfei')
  4. const sqlite3 = require('sqlite3')
  5. //sqlite数据库路径
  6. let sqliteDbPath = "./db/data.db"
  7. //打开数据库
  8. let db = new sqlite3.Database(sqliteDbPath)
  9. const wechaty = WechatyBuilder.build()
  10. function getConfigValue(configName) {
  11. return new Promise((resolve, reject) => {
  12. const query = 'SELECT value FROM wxconfig WHERE config = ?'
  13. db.get(query, [configName], (err, row) => {
  14. if (err) {
  15. reject(err)
  16. } else {
  17. const configValue = row ? row.value : null
  18. // 处理字符串 'null',如果是 'null' 则返回 null
  19. resolve(configValue === 'null' ? null : configValue)
  20. }
  21. })
  22. })
  23. }
  24. // 读取配置信息并设置相应的变量
  25. async function loadConfigValues() {
  26. try {
  27. autoReplySingle = await getConfigValue('autoReplySingle') === 'true'
  28. prefix = await getConfigValue('prefix')
  29. suffix = await getConfigValue('suffix')
  30. usemodel = await getConfigValue('usemodel')
  31. whiteRoomString = await getConfigValue('whiteRoom')
  32. keyWordsString = await getConfigValue('keyWords')
  33. blackNameString = await getConfigValue('blackName')
  34. atReply = await getConfigValue('atReply') === 'true'
  35. // 处理转义符
  36. suffix = suffix !== null ? suffix.replace(/\\n/g, '\n') : ''
  37. prefix = prefix !== null ? prefix.replace(/\\n/g, '\n') : ''
  38. // 处理用逗号分隔的字符串形式的数组
  39. whiteRoom = whiteRoomString !== null ? whiteRoomString.split(",").map(item => item.trim()) : []
  40. keyWords = keyWordsString !== null ? keyWordsString.split(",").map(item => item.trim()) : []
  41. blackName = blackNameString !== null ? blackNameString.split(",").map(item => item.trim()) : []
  42. } catch (error) {
  43. console.error('Error loading config values:', error)
  44. }
  45. }
  46. // 调用函数加载配置信息
  47. loadConfigValues()
  48. //选择模型
  49. async function sendMessageToAPI(message) {
  50. if (usemodel==='xunfei'){
  51. const response = await getXunfeiMessage(message)
  52. const content = prefix + response + suffix
  53. return content
  54. } else {
  55. const response = await getGPTMessage(message)
  56. const content = prefix + response + suffix
  57. return content
  58. }
  59. }
  60. //获取时间
  61. function getCurrentTime() {
  62. const options = {
  63. year: 'numeric',
  64. month: '2-digit',
  65. day: '2-digit',
  66. hour: '2-digit',
  67. minute: '2-digit',
  68. second: '2-digit',
  69. }
  70. const currentTime = new Date().toLocaleString('zh-CN', options)
  71. return currentTime
  72. }
  73. //停止函数运行
  74. let isRunning = false
  75. async function stopWx() {
  76. if (isRunning) {
  77. isRunning = false
  78. await wechaty.stop()
  79. Status.status = 0
  80. }
  81. }
  82. let Status = { status: null }
  83. let User = {name: null}
  84. async function wxlogin() {
  85. if (isRunning) {
  86. isRunning = false
  87. await wechaty.stop()
  88. Status.status = 0
  89. }
  90. isRunning = true
  91. return new Promise((resolve, reject) => {
  92. let qrcodeUrl
  93. // 解除之前绑定的所有事件处理程序
  94. wechaty.removeAllListeners()
  95. wechaty
  96. .on('scan', (qrcode, status) => {
  97. qrcodeUrl = `https://my.tv.sohu.com/user/a/wvideo/getQRCode.do?text=${encodeURIComponent(qrcode)}`
  98. Status.status = status
  99. // 将 qrcodeUrl 提前返回
  100. resolve(qrcodeUrl)
  101. })
  102. .on('login', async (user) => {
  103. Status.status = 200
  104. // 获取登录用户的信息
  105. const contact = await wechaty.Contact.find({ id: user.id })
  106. const name = await contact.name()
  107. const avatarFileBox = await contact.avatar()
  108. User.name = name
  109. // 将头像保存到本地
  110. const avatarFilePath = `./wechat/avatar/avatar.jpg`
  111. await avatarFileBox.toFile(avatarFilePath,true)
  112. })
  113. .on('logout', async () => {
  114. Status.status = null
  115. isRunning = false
  116. await wechaty.stop()
  117. })
  118. .on('message',async (message) => {
  119. if (message.self()) {
  120. return
  121. } else {
  122. if (message.type() === wechaty.Message.Type.Text) {
  123. const content = message.text()
  124. const room = message.room()
  125. const talker = message.talker()
  126. const talkername = message.talker().payload.name
  127. const foundWords = keyWords.filter(word => content.includes(word))
  128. if (room) {
  129. const roomname = message.room().payload.topic
  130. if (whiteRoom.length === 0 || whiteRoom.includes(roomname)) {
  131. //在群聊中被@
  132. if (await message.mentionSelf()) {
  133. if (atReply) {
  134. const apiMessage = await sendMessageToAPI(content)
  135. const senmsg = '@' + talkername + ' ' + apiMessage
  136. room.say(senmsg)
  137. //写入数据库
  138. writeToDatabase({
  139. time: getCurrentTime(),
  140. type: '群聊',
  141. recmsg: content,
  142. senmsg: senmsg,
  143. name: talkername,
  144. roomname: roomname,
  145. })
  146. return
  147. }
  148. } else if (foundWords.length > 0) {
  149. console.log('发现关键字')
  150. const apiMessage = await sendMessageToAPI(content)
  151. const senmsg = '@' + talkername + ' ' + apiMessage
  152. room.say(senmsg)
  153. //写入数据库
  154. writeToDatabase({
  155. time: getCurrentTime(),
  156. type: '群聊',
  157. recmsg: content,
  158. senmsg: senmsg,
  159. name: talkername,
  160. roomname: roomname,
  161. })
  162. return
  163. }
  164. } else {
  165. return
  166. }
  167. } else {
  168. if (autoReplySingle) {
  169. if (blackName.includes(talkername)) {
  170. return
  171. } else {
  172. const apiMessage = await sendMessageToAPI(content)
  173. talker.say(apiMessage)
  174. writeToDatabase({
  175. time: getCurrentTime(),
  176. type: '私聊',
  177. recmsg: content,
  178. senmsg: apiMessage,
  179. name: message.talker().payload.name,
  180. roomname: null,
  181. })
  182. return
  183. }
  184. }
  185. }
  186. } else {
  187. return
  188. }
  189. }
  190. }
  191. )
  192. wechaty.start()
  193. wechaty.on('error', (error) => {
  194. reject(error)
  195. })
  196. })
  197. }
  198. //向数据库写入数据
  199. function writeToDatabase(data) {
  200. const { time, type, recmsg, senmsg, name, roomname } = data
  201. const insertQuery = `INSERT INTO message (time, type, recmsg, senmsg, name, roomname) VALUES (?, ?, ?, ?, ?, ?)`
  202. db.run(insertQuery, [time, type, recmsg, senmsg, name, roomname], (error) => {
  203. if (error) {
  204. console.error('数据库写入失败:', error)
  205. }
  206. })
  207. }
  208. // 更新设置到数据库
  209. function updateConfigValue(configName, configValue) {
  210. const query = 'INSERT OR REPLACE INTO wxconfig (config, value) VALUES (?, ?)'
  211. db.run(query, [configName, configValue], (err) => {
  212. if (err) {
  213. console.error('数据库写入失败:', err)
  214. }
  215. })
  216. }
  217. function setWx(key,value) {
  218. updateConfigValue(key,value)
  219. }
  220. module.exports = {
  221. wxlogin,
  222. Status,
  223. setWx,
  224. stopWx,
  225. loadConfigValues,
  226. User,
  227. sendMessageToAPI
  228. }