Claude Code实战:从零构建Electron桌面应用+Telegram Bot

Claude Code真实项目实战:Electron桌面应用+Telegram Bot

先看第一个坑:Electron + Claude Code的配置地狱

官方文档这段文档不够清晰,配置了半天才发现是版本问题。我的环境配置:

  • Node.js: 18.18.0
  • npm: 9.6.7
  • Electron: 28.0.0

直接上代码,先建项目结构:

javascript
// package.json
{
"name": "server-monitor",
"version": "1.0.0",
"main": "main.js",
"scripts": {
"start": "electron .",
"build": "electron-builder"
},
"dependencies": {
"electron": "^28.0.0",
"node-telegram-bot-api": "^0.64.0",
"systeminformation": "^5.21.0"
}
}
`

为什么要这么写?因为systeminformation这个库能直接获取CPU、内存、磁盘信息,省得自己写底层接口。node-telegram-bot-api则是Telegram Bot的官方Node.js库。

开篇展示Electron桌面应用的主界面设计,包含系统监控面板和实时数据展示

核心逻辑:主进程与渲染进程的通信

Electron这设计真的反人类,主进程和渲染进程完全隔离。我的解决思路:用IPC通信,但得用安全的方式——预加载脚本。

`javascript
// preload.js - 预加载脚本
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
invoke: (channel, ...args) => ipcRenderer.invoke(channel, ...args)
});
`

`javascript
// main.js - 主进程
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const si = require('systeminformation');
const TelegramBot = require('node-telegram-bot-api');

let mainWindow;
const TELEGRAM_TOKEN = 'YOUR_BOT_TOKEN'; // 记得替换

// 初始化Telegram Bot,注意polling只用于接收消息(如用户发的命令),发送通知不需要
const bot = new TelegramBot(TELEGRAM_TOKEN, { polling: false }); // 如果不需要接收用户消息,就关掉polling

function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true
}
});
mainWindow.loadFile('index.html');
}

// 系统监控数据获取
ipcMain.handle('get-system-stats', async () => {
const cpu = await si.currentLoad();
const mem = await si.mem();
const disk = await si.fsSize();
return {
cpuLoad: cpu.currentLoad.toFixed(2),
memoryUsed: (mem.used / 1024 / 1024 / 1024).toFixed(2),
memoryTotal: (mem.total / 1024 / 1024 / 1024).toFixed(2),
diskUsed: disk[0].used
};
});

// 发送Telegram通知,加个try-catch防止崩溃
async function sendTelegramAlert(message) {
try {
await bot.sendMessage('YOUR_CHAT_ID',
⚠️ 服务器告警: ${message});
} catch (err) {
console.error('Telegram发送失败:', err.message);
}
}

// 每30秒检查一次
setInterval(async () => {
try {
const stats = await si.currentLoad();
if (stats.currentLoad > 80) { // CPU超过80%告警
await sendTelegramAlert(
CPU负载异常: ${stats.currentLoad.toFixed(2)}%);
}
} catch (err) {
console.error('监控检查出错:', err.message);
}
}, 30000);

app.whenReady().then(createWindow);
`

这个设计真的反人类,但不得不承认IPC的分离机制让应用更安全。渲染进程拿不到Node.js的底层API,只能通过预加载脚本暴露的window.electronAPI.invoke请求数据。另外提醒一句:生产环境千万别开nodeIntegration: true`和`contextIsolation: false`,那是给黑客留后门。

渲染进程:做好看一点

UI方面,我用原生HTML+CSS,没上框架。为什么?因为Electron本身就够重了,再加框架性能会从3秒降到5秒。

`html




<style>
body {
background: #1a1a2e;
color: #e0e0e0;
font-family: 'Segoe UI', sans-serif;
}
.stat-card {
background: #16213e;
border-radius: 10px;
padding: 20px;
margin: 10px;
transition: transform 0.3s;
}
.stat-card:hover {
transform: scale(1.05);
}
.alert-badge {
background: #e74c3c;
color: white;
padding: 5px 10px;
border-radius: 5px;
font-size: 12px;
}
</style>

服务器监控面板

CPU 负载

加载中...

内存使用

加载中...

磁盘使用

加载中...

<script>
// 通过预加载脚本暴露的API,不用require('electron')了
async function updateStats() {
const stats = await window.electronAPI.invoke('get-system-stats');
document.getElementById('cpu-load').textContent =
${stats.cpuLoad}%;
docume

本文仅供参考,不构成医疗建议。
本文由AI辅助创作,仅供参考。

滚动至顶部