使用Discord.py开发机器人遇问题:无法触发$start命令启动Exaroton服务器
Discord机器人实现$start命令调用Exaroton API启动MC服务器的修复方案
现有代码的问题
- 未实现
$start命令的处理逻辑,当前仅响应99!指令 - 机器人启动方式错误:
discord.Client.run(client, TOKEN)是非法用法,会导致运行异常 - 缺少Exaroton API调用的核心代码
- Intents配置不完整:discord.py v2.x及以上版本,必须开启
message_content权限才能读取消息内容
修复步骤与完整代码
1. 补充依赖安装
在Replit的终端执行以下命令,安装API请求所需的aiohttp:
pip install aiohttp
2. 调整Intents配置
开启message_content权限,确保机器人能读取消息内容:
intents = Intents.default() intents.messages = True intents.guilds = True intents.message_content = True # 新增该行,必须开启
3. 修复机器人启动逻辑
替换错误的启动代码,使用标准异步启动方式:
if __name__ == '__main__': import asyncio asyncio.run(main())
4. 添加$start命令与Exaroton API调用
在on_message事件中新增命令处理逻辑,同时在.env中配置Exaroton密钥和服务器ID:
完整修复代码
import os import random import aiohttp import discord from discord import Intents from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') # 新增Exaroton配置项 EXAROTON_API_KEY = os.getenv('EXAROTON_API_KEY') EXAROTON_SERVER_ID = os.getenv('EXAROTON_SERVER_ID') intents = Intents.default() intents.messages = True intents.guilds = True intents.message_content = True client = discord.Client(intents=intents) @client.event async def on_ready(): print(f'{client.user} 已连接到Discord!') @client.event async def on_message(message): print(f"收到消息:{message.content}") if message.author == client.user: return brooklyn_99_quotes = [ 'I\'m the human form of the 💯 emoji.', 'Bingpot!', ( 'Cool. Cool cool cool cool cool cool cool, ' 'no doubt no doubt no doubt no doubt.' ), ] if '99!' in message.content: response = random.choice(brooklyn_99_quotes) await message.channel.send(response) # 处理$start命令 if message.content == '$start': # 检查配置是否完整 if not EXAROTON_API_KEY or not EXAROTON_SERVER_ID: await message.channel.send('请先在.env中配置Exaroton API密钥和服务器ID!') return try: # 调用Exaroton API启动服务器 async with aiohttp.ClientSession() as session: url = f'https://api.exaroton.com/v1/servers/{EXAROTON_SERVER_ID}/start/' headers = {'Authorization': f'Bearer {EXAROTON_API_KEY}'} async with session.post(url, headers=headers) as response: if response.status == 200: await message.channel.send('Minecraft服务器正在启动中!') else: data = await response.json() await message.channel.send(f'启动失败:{data.get("error", "未知错误")}') except Exception as e: await message.channel.send(f'请求API时出错:{str(e)}') async def start_bot(): await client.start(TOKEN) async def main(): await start_bot() if __name__ == '__main__': import asyncio asyncio.run(main())
5. 配置.env文件
在Replit的.env文件中添加以下内容:
DISCORD_TOKEN=你的Discord机器人令牌 EXAROTON_API_KEY=你的Exaroton API密钥 EXAROTON_SERVER_ID=你的Exaroton服务器ID
6. 开启Discord门户权限
前往Discord开发者门户的机器人页面,在"Privileged Gateway Intents"下开启"Message Content Intent",否则机器人无法读取消息内容。
内容的提问来源于stack exchange,提问作者Gregory Scales
相关产品推荐
相关产品推荐

