main.js 9.3 KB

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