You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron+Discord.js本地文件上传Discord论坛异常求助

问题:Electron + Discord.js 文件上传至Discord论坛频道失败

运行程序时出现无法读取undefined的属性'MessageAttachment'错误,Bot可正常上线但未执行上传操作,renderer指定的文件夹未被抓取,IPC主进程无任何动作。预期功能为遍历指定文件夹内所有文件,逐个上传至指定ID的Discord论坛频道。

核心问题分析

  • Discord.js 导入错误:MessageAttachment未正确导入,原代码错误地从Discord对象中获取,Discord.js v14+无需此包裹
  • 异步操作未处理:client.channels.fetch是异步方法,直接赋值会得到Promise而非实际频道对象
  • 文件发送逻辑错误:错误调用MessageAttachment.channel.send,实际应通过频道对象直接发送文件
  • IPC 回复机制错误:ipcMain.handle需通过Promise的resolve/reject回复,而非event.reply
  • 相对路径解析问题:renderer中使用的相对路径可能无法被主进程正确识别

修复步骤

1. main.js 代码修正

// main.js

const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path')
// 正确导入Discord.js核心模块,v14+无需Discord包裹对象
const { Client, GatewayIntentBits, MessageAttachment } = require('discord.js')
const fs = require('fs')

const client = new Client({
     intents: [
      GatewayIntentBits.Guilds,
      GatewayIntentBits.GuildMessages,
      GatewayIntentBits.MessageContent,
      GatewayIntentBits.GuildMembers,
    ]
})

const createWindow = () => {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      enableRemoteModule: true,
      contextIsolation: false,
    }
  })

  mainWindow.loadFile('index.html')
  mainWindow.webContents.openDevTools()
}

app.whenReady().then(() => {
  // 确保Bot登录完成后再创建窗口,避免IPC调用时client未就绪
  client.login('你的Bot令牌')
    .then(() => {
      console.log(`Logged in as ${client.user.tag}!`)
      createWindow()
    })
    .catch(err => console.error('Bot登录失败:', err))

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

// 重构IPC处理器,处理异步操作并通过Promise回复
ipcMain.handle('upload-folder', async (event, folderPath) => {
  try {
    // 等待频道获取完成,确保拿到实际频道对象
    const channel = await client.channels.fetch('你的目标频道ID')
    if (!channel) throw new Error('无效的频道ID')

    // 用Promise方式读取文件夹,避免回调嵌套
    const files = await fs.promises.readdir(folderPath)
    for (const file of files) {
      const filePath = path.join(folderPath, file)
      // 直接通过频道对象发送文件,discord.js会自动处理附件
      await channel.send({
        files: [filePath]
      })
      await channel.send(`上传完成: ${file}`)
      console.log(`已上传文件: ${file}`)
    }
    const finishMsg = `全部上传完成,共处理 ${files.length} 个文件`
    await channel.send(finishMsg)
    return finishMsg
  } catch (error) {
    console.error('上传过程出错:', error)
    throw error // 抛出错误让renderer的catch捕获
  }
})

2. renderer.js 路径修正

const { ipcRenderer } = require('electron');
const path = require('path');

// 使用绝对路径,确保主进程能正确定位文件夹
const folderPath = path.join(__dirname, 'Navcom/aar/');

ipcRenderer.invoke('upload-folder', folderPath)
  .then((msg) => console.log(msg))
  .catch((error) => console.error('上传失败:', error))

3. 额外注意事项

  • Discord.js 版本:确保使用v14及以上版本,不同版本的导入和API调用逻辑存在差异
  • Bot 权限:确认Bot拥有目标频道的SendMessages和AttachFiles权限
  • 路径验证:可在IPC处理器中添加文件夹存在性校验,避免读取不存在的路径
  • 错误捕获:完善每个异步操作的错误处理,避免单个文件上传失败导致整个流程中断

内容的提问来源于stack exchange,提问作者Bale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 03:25:06