main.js 9.4 KB

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