main.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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 if(usemodel === 'chatgpt') {
  55. const response = await getGPTMessage(message)
  56. const content = prefix + response + suffix
  57. return content
  58. } else {
  59. return
  60. }
  61. }
  62. //获取时间
  63. function getCurrentTime() {
  64. const options = {
  65. year: 'numeric',
  66. month: '2-digit',
  67. day: '2-digit',
  68. hour: '2-digit',
  69. minute: '2-digit',
  70. second: '2-digit',
  71. }
  72. const currentTime = new Date().toLocaleString('zh-CN', options)
  73. return currentTime
  74. }
  75. //停止函数运行
  76. let isRunning = false
  77. async function stopWx() {
  78. if (isRunning) {
  79. isRunning = false
  80. await wechaty.stop()
  81. Status.status = 0
  82. }
  83. }
  84. let Status = { status: null }
  85. let User = {name: null}
  86. async function wxlogin() {
  87. if (isRunning) {
  88. isRunning = false
  89. await wechaty.stop()
  90. Status.status = 0
  91. }
  92. isRunning = true
  93. return new Promise((resolve, reject) => {
  94. let qrcodeUrl
  95. // 解除之前绑定的所有事件处理程序
  96. wechaty.removeAllListeners()
  97. wechaty
  98. .on('scan', (qrcode, status) => {
  99. qrcodeUrl = `https://my.tv.sohu.com/user/a/wvideo/getQRCode.do?text=${encodeURIComponent(qrcode)}`
  100. Status.status = status
  101. // 将 qrcodeUrl 提前返回
  102. resolve(qrcodeUrl)
  103. })
  104. .on('login', async (user) => {
  105. Status.status = 200
  106. // 获取登录用户的信息
  107. const contact = await wechaty.Contact.find({ id: user.id })
  108. const name = contact.name()
  109. const avatarFileBox = await contact.avatar()
  110. User.name = name
  111. // 将头像保存到本地
  112. await avatarFileBox.toFile(`./wechat/avatar/avatar.jpg`,true)
  113. })
  114. .on('logout', async () => {
  115. Status.status = null
  116. isRunning = false
  117. await wechaty.stop()
  118. })
  119. .on('message',async (message) => {
  120. if (message.self()) {
  121. return
  122. } else {
  123. if (message.type() === wechaty.Message.Type.Text) {
  124. const content = message.text()
  125. const room = message.room()
  126. const talker = message.talker()
  127. const talkername = message.talker().payload.name
  128. const foundWords = keyWords.filter(word => content.includes(word))
  129. if (room) {
  130. const roomname = message.room().payload.topic
  131. if (whiteRoom.length === 0 || whiteRoom.includes(roomname)) {
  132. //在群聊中被@
  133. if (await message.mentionSelf()) {
  134. if (atReply) {
  135. const apiMessage = await sendMessageToAPI(content)
  136. const senmsg = '@' + talkername + ' ' + apiMessage
  137. room.say(senmsg)
  138. //写入数据库
  139. writeToDatabase({
  140. time: getCurrentTime(),
  141. type: '群聊',
  142. recmsg: content,
  143. senmsg: senmsg,
  144. name: talkername,
  145. roomname: roomname,
  146. })
  147. return
  148. }
  149. } else if (foundWords.length > 0) {
  150. console.log('发现关键字')
  151. const apiMessage = await sendMessageToAPI(content)
  152. const senmsg = '@' + talkername + ' ' + apiMessage
  153. room.say(senmsg)
  154. //写入数据库
  155. writeToDatabase({
  156. time: getCurrentTime(),
  157. type: '群聊',
  158. recmsg: content,
  159. senmsg: senmsg,
  160. name: talkername,
  161. roomname: roomname,
  162. })
  163. return
  164. }
  165. } else {
  166. return
  167. }
  168. } else {
  169. if (autoReplySingle) {
  170. if (blackName.includes(talkername)) {
  171. return
  172. } else {
  173. const apiMessage = await sendMessageToAPI(content)
  174. talker.say(apiMessage)
  175. writeToDatabase({
  176. time: getCurrentTime(),
  177. type: '私聊',
  178. recmsg: content,
  179. senmsg: apiMessage,
  180. name: message.talker().payload.name,
  181. roomname: null,
  182. })
  183. return
  184. }
  185. }
  186. }
  187. } else {
  188. return
  189. }
  190. }
  191. }
  192. )
  193. wechaty.start()
  194. wechaty.on('error', (error) => {
  195. reject(error)
  196. })
  197. })
  198. }
  199. //向数据库写入数据
  200. function writeToDatabase(data) {
  201. const { time, type, recmsg, senmsg, name, roomname } = data
  202. const insertQuery = `INSERT INTO message (time, type, recmsg, senmsg, name, roomname) VALUES (?, ?, ?, ?, ?, ?)`
  203. db.run(insertQuery, [time, type, recmsg, senmsg, name, roomname], (error) => {
  204. if (error) {
  205. console.error('数据库写入失败:', error)
  206. }
  207. })
  208. }
  209. // 更新设置到数据库
  210. function updateConfigValue(configName, configValue) {
  211. const query = 'INSERT OR REPLACE INTO wxconfig (config, value) VALUES (?, ?)'
  212. db.run(query, [configName, configValue], (err) => {
  213. if (err) {
  214. console.error('数据库写入失败:', err)
  215. }
  216. })
  217. }
  218. function setWx(key,value) {
  219. updateConfigValue(key,value)
  220. }
  221. module.exports = {
  222. wxlogin,
  223. Status,
  224. setWx,
  225. stopWx,
  226. loadConfigValues,
  227. User,
  228. sendMessageToAPI
  229. }