main.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. const { WechatyBuilder } = require("wechaty")
  2. const { sendMessageToAPI } = require('./getmessage')
  3. const sqlite3 = require('sqlite3')
  4. //sqlite数据库路径
  5. let sqliteDbPath = "./db/data.db"
  6. //打开数据库
  7. let db = new sqlite3.Database(sqliteDbPath)
  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. whiteRoomString = await getConfigValue('whiteRoom')
  30. keyWordsString = await getConfigValue('keyWords')
  31. blackNameString = await getConfigValue('blackName')
  32. atReply = await getConfigValue('atReply') === 'true'
  33. // 处理转义符
  34. suffix = suffix !== null ? suffix.replace(/\\n/g, '\n') : ''
  35. prefix = prefix !== null ? prefix.replace(/\\n/g, '\n') : ''
  36. // 处理用逗号分隔的字符串形式的数组
  37. whiteRoom = whiteRoomString !== null ? whiteRoomString.split(",").map(item => item.trim()) : []
  38. keyWords = keyWordsString !== null ? keyWordsString.split(",").map(item => item.trim()) : []
  39. blackName = blackNameString !== null ? blackNameString.split(",").map(item => item.trim()) : []
  40. console.log('Config values loaded successfully.')
  41. } catch (error) {
  42. console.error('Error loading config values:', error)
  43. }
  44. }
  45. // 调用函数加载配置信息
  46. loadConfigValues()
  47. //获取时间
  48. function getCurrentTime() {
  49. const options = {
  50. year: 'numeric',
  51. month: '2-digit',
  52. day: '2-digit',
  53. hour: '2-digit',
  54. minute: '2-digit',
  55. second: '2-digit',
  56. }
  57. const currentTime = new Date().toLocaleString('zh-CN', options)
  58. return currentTime
  59. }
  60. //停止函数运行
  61. let isRunning = false
  62. async function stopWx() {
  63. if (isRunning) {
  64. isRunning = false
  65. await wechaty.stop();
  66. Status.status = 0;
  67. console.log('Wechaty stopped.');
  68. } else {
  69. console.log('Wechaty is not running.');
  70. }
  71. }
  72. let Status = { status: null }
  73. let User = {name: null}
  74. async function wxlogin() {
  75. if (isRunning) {
  76. isRunning = false
  77. await wechaty.stop();
  78. Status.status = 0;
  79. console.log('Wechaty stopped.');
  80. } else {
  81. console.log('Wechaty is not running.');
  82. }
  83. isRunning = true
  84. return new Promise((resolve, reject) => {
  85. let qrcodeUrl
  86. // 解除之前绑定的所有事件处理程序
  87. wechaty.removeAllListeners();
  88. wechaty
  89. .on('scan', (qrcode, status) => {
  90. qrcodeUrl = `https://my.tv.sohu.com/user/a/wvideo/getQRCode.do?text=${encodeURIComponent(qrcode)}`
  91. console.log('Scan QR Code to log in:', status)
  92. Status.status = status
  93. // 将 qrcodeUrl 提前返回
  94. resolve(qrcodeUrl)
  95. })
  96. .on('login', async (user) => {
  97. console.log(`User ${user} logged in`);
  98. Status.status = 200
  99. // 获取登录用户的信息
  100. const contact = await wechaty.Contact.find({ id: user.id });
  101. const name = await contact.name();
  102. const avatarFileBox = await contact.avatar();
  103. User.name = name
  104. // 将头像保存到本地
  105. const avatarFilePath = `./wechat/avatar/avatar.jpg`
  106. await avatarFileBox.toFile(avatarFilePath,true)
  107. // 有程序运行后配置未加载的问题,这里重新加载一遍
  108. loadConfigValues()
  109. })
  110. .on('logout', async () => {
  111. Status.status = null
  112. isRunning = false
  113. await wechaty.stop()
  114. })
  115. .on('message',async (message) => {
  116. if (message.self()) {
  117. console.log('自己发送消息:'+message.text())
  118. return
  119. } else {
  120. if (message.type() === wechaty.Message.Type.Text) {
  121. const content = message.text()
  122. console.log(content)
  123. const room = message.room()
  124. const talker = message.talker()
  125. const talkername = message.talker().payload.name
  126. const foundWords = keyWords.filter(word => content.includes(word))
  127. if (room) {
  128. const roomname = message.room().payload.topic
  129. if (whiteRoom.length === 0 || whiteRoom.includes(roomname)) {
  130. //在群聊中被@
  131. if (await message.mentionSelf()) {
  132. console.log('机器人被@')
  133. if (atReply) {
  134. const apiMessage = await sendMessageToAPI(content)
  135. const senmsg = '@' + talkername + ' ' + prefix + apiMessage + suffix
  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 + ' ' + prefix + apiMessage + suffix
  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. console.log('发送者在黑名单中')
  171. return
  172. } else {
  173. const apiMessage = await sendMessageToAPI(content)
  174. const senmsg = prefix + apiMessage + suffix
  175. talker.say(senmsg)
  176. //向数据库写入消息
  177. writeToDatabase({
  178. time: getCurrentTime(),
  179. type: '私聊',
  180. recmsg: content,
  181. senmsg: senmsg,
  182. name: message.talker().payload.name,
  183. roomname: null,
  184. })
  185. return
  186. }
  187. }
  188. }
  189. } else {
  190. console.log('不受支持的消息类型')
  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. } else {
  210. console.log('数据库写入成功')
  211. }
  212. })
  213. }
  214. // 更新设置到数据库
  215. function updateConfigValue(configName, configValue) {
  216. const query = 'INSERT OR REPLACE INTO wxconfig (config, value) VALUES (?, ?)'
  217. db.run(query, [configName, configValue], (err) => {
  218. if (err) {
  219. console.error('数据库写入失败:', err)
  220. } else {
  221. console.log('数据库写入成功')
  222. }
  223. })
  224. }
  225. // 设置是否自动回复
  226. function setAutoReplySingle(value) {
  227. updateConfigValue('autoReplySingle', value)
  228. }
  229. function setatReply(value) {
  230. updateConfigValue('atReply', value)
  231. }
  232. function setblackName(value) {
  233. updateConfigValue('blackName', value)
  234. }
  235. function setkeyWords(value) {
  236. updateConfigValue('keyWords', value)
  237. }
  238. function setwhiteRoom(value) {
  239. updateConfigValue('whiteRoom', value)
  240. }
  241. // 修改前缀
  242. function setSuffix(value) {
  243. updateConfigValue('suffix', value)
  244. }
  245. // 修改后缀
  246. function setPrefix(value) {
  247. updateConfigValue('prefix', value)
  248. }
  249. module.exports = {
  250. wxlogin,
  251. Status,
  252. setAutoReplySingle,
  253. setwhiteRoom,
  254. setatReply,
  255. setkeyWords,
  256. setblackName,
  257. setSuffix,
  258. setPrefix,
  259. stopWx,
  260. loadConfigValues,
  261. User
  262. }