main - 副本.js 10.0 KB

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