如何在Express应用的index.js中集成运行外部文件夹的函数?
重构Discord短信通知机器人代码结构方案
当前代码存在核心问题:personalSMS.js中重复初始化Discord Client实例,且将messageCreate事件监听逻辑封装在独立文件内,导致多客户端实例冲突,同时不符合"在index.js中调用外部函数"的重构目标。以下是优化后的实现方案:
1. 优化主入口index.js
保留唯一的Discord Client实例,统一管理事件监听,将消息处理逻辑委托给外部模块:
require('dotenv').config(); require('events').EventEmitter.defaultMaxListeners = 25; const { Client, GatewayIntentBits } = require('discord.js'); const twilio = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN); const express = require('express') // 导入外部处理函数 const { handleCyberSuccessMessage } = require("./Text Functions/personalSMS"); // 初始化全局唯一的Discord客户端 const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildPresences, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers ] }); // Express服务初始化 const app = express(); app.use(express.urlencoded({ extended: true })); app.listen(3000, () => { console.log('Listening on port 3000'); }); // 统一监听messageCreate事件,分发到对应处理函数 client.on("messageCreate", (message) => { // 根据频道ID判断是否交给Cybersole消息处理逻辑 if (message.channel.id === process.env.CYBER_SUCCESS_CHANNEL_ID && message.author.id !== process.env.MY_USER_ID) { handleCyberSuccessMessage(message); } // 可在此添加其他频道的消息处理分支,调用对应外部函数 }); client.login(process.env.BOT_TOKEN);
2. 重构personalSMS.js
移除重复的Client初始化,仅保留业务逻辑函数并导出,依赖外部传入的参数完成处理:
const twilio = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN); // 发送短信的核心函数 function sendCyberSuccess(sms) { twilio.messages.create({ body: sms, to: process.env.PERSONAL_NUMBER, from: process.env.TWILIO_NUMBER, }); } // 处理Cybersole频道消息的逻辑函数,接收message对象作为参数 function handleCyberSuccessMessage(message) { const author = message.author.username.toString(); message.embeds.forEach((embed) => { const description = embed.description; const title = embed.title.toString(); if (author.includes('Cybersole') && title.includes("Successfully checked out!")) { const updatedAuthor = author.replace("Cybersole", 'Senpai Notifier'); const updatedTitle = title.replace("Successfully checked out!", "Checked Out! 🧪"); const sms6 = `Status: ${updatedTitle}\n\nDescription: ${description}\n\nHey Brandon, it looks like you checked out something on Cybersole. Amazing job! Onto the next drop 🧪\n\nNotified By ${updatedAuthor}`; sendCyberSuccess(sms6); } else if (author.includes('Cybersole') && title.includes("Your card was declined!")) { const updatedAuthor = author.replace("Cybersole", 'Senpai Notifier'); const updatedTitle = title.replace("Your card was declined!", "Declined ❌"); const sms7 = `Status: ${updatedTitle}\n\nHey you just got a decline.That's not 4PF 💔\n\nNotified By ${updatedAuthor}`; sendCyberSuccess(sms7); } }); } // 导出需要被index.js调用的函数 module.exports = { handleCyberSuccessMessage };
额外优化建议
- 将频道ID、用户ID等硬编码值移到
.env文件中,避免代码耦合 - 为Twilio的消息发送操作添加错误捕获,避免静默失败:
async function sendCyberSuccess(sms) { try { await twilio.messages.create({ body: sms, to: process.env.PERSONAL_NUMBER, from: process.env.TWILIO_NUMBER, }); console.log('短信发送成功'); } catch (error) { console.error('短信发送失败:', error); } } - 后续添加更多消息类型处理时,可继续在
Text Functions下创建独立文件,保持职责单一
内容的提问来源于stack exchange,提问作者JediSZN
相关产品推荐
相关产品推荐

