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

如何制作可查询运行所在虚拟服务器系统状态的Discord Bot?

开发可查询服务器运行状态的Discord Bot实现方案

前置要求

  • 已在Discord开发者平台创建Bot应用,获取到专属Bot Token(注意该Token禁止泄露给第三方,否则会导致你的Bot权限被盗用)
  • 运行Bot的虚拟服务器已安装Python 3.8及以上版本,网络可正常访问Discord API

依赖安装

执行以下命令安装所需的第三方库:
pip install discord.py psutil
其中discord.py为Discord Bot开发框架,psutil用于获取系统运行指标。

核心实现代码

import discord
from discord.ext import commands
import psutil
import platform

# 配置Bot权限,需提前在Discord开发者后台开启Message Content Intent权限
intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix='!', intents=intents)

@bot.event
async def on_ready():
    print(f'Bot已成功登录,当前身份:{bot.user}')

# 定义状态查询指令,触发命令为!status
@bot.command()
async def status(ctx):
    # 采集CPU使用率
    cpu_usage = psutil.cpu_percent(interval=1)
    # 采集内存指标
    mem = psutil.virtual_memory()
    mem_total = round(mem.total / 1024**3, 2)
    mem_used = round(mem.used / 1024**3, 2)
    mem_usage = mem.percent
    # 采集磁盘指标(默认读取根分区,可根据需要修改路径)
    disk = psutil.disk_usage('/')
    disk_total = round(disk.total / 1024**3, 2)
    disk_used = round(disk.used / 1024**3, 2)
    disk_usage = disk.percent
    # 采集操作系统信息
    os_info = f"{platform.system()} {platform.release()}"
    # 组装返回的嵌入式消息
    status_embed = discord.Embed(title="服务器运行状态详情", color=discord.Color.green())
    status_embed.add_field(name="操作系统", value=os_info, inline=False)
    status_embed.add_field(name="CPU使用率", value=f"{cpu_usage}%", inline=True)
    status_embed.add_field(name="内存占用", value=f"{mem_used}GB / {mem_total}GB ({mem_usage}%)", inline=True)
    status_embed.add_field(name="磁盘占用", value=f"{disk_used}GB / {disk_total}GB ({disk_usage}%)", inline=True)
    await ctx.send(embed=status_embed)

# 替换为你自己的Bot Token后启动
bot.run("YOUR_BOT_TOKEN_HERE")

部署使用说明

  • 将代码中的YOUR_BOT_TOKEN_HERE替换为你自己的Bot Token后,直接运行Python脚本即可启动Bot
  • 完成Bot到对应Discord服务器的邀请后,在频道内发送!status即可触发Bot返回当前服务器的状态信息
  • 如需后台常驻运行,可使用nohup命令或者systemd服务托管Bot进程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 06:15:03