eliza
eliza copied to clipboard
Docs: Add Discord token resolution guide to documentation | Error [TokenInvalid]: An invalid token was provided
Description
While setting up Discord bots with multiple characters, I encountered and resolved an issue with Discord token resolution. This could be valuable documentation for other developers.
Problem
The Discord client was failing with the following error:
Error [TokenInvalid]: An invalid token was provided.
at WebSocketManager.connect (/Users/.../eliza/node_modules/discord.js/src/client/websocket/WebSocketManager.js:136:26)
at Client.login (/Users/.../eliza/node_modules/discord.js/src/client/Client.js:228:21)
This was happening even though the tokens were correctly set in the .env file. The issue was in how the tokens were being resolved from environment variables.
Solution
I fixed this by:
- Ensuring proper token resolution in
eliza/packages/client-discord/src/index.ts:
// Get the token using runtime's getSecret
const token = this.character?.settings?.secrets?.DISCORD_API_TOKEN;
// If it's a variable reference (${...}), resolve it from environment
if (token?.startsWith('${') && token?.endsWith('}')) {
const envVarName = token.slice(2, -1);
this.apiToken = process.env[envVarName] || '';
} else {
this.apiToken = token || '';
}
- Adding debug logging to track token resolution:
elizaLogger.debug('Token resolution debug:', {
characterName: this.character.name,
rawToken: token,
isEnvVar: token?.startsWith('${') && token?.endsWith('}'),
envVarName: token?.startsWith('${') ? token.slice(2, -1) : null,
envValue: token?.startsWith('${') ? process.env[token.slice(2, -1)] : null
});
Key Points
- Character files should reference environment variables using
${VAR_NAME}syntax:
{
"settings": {
"secrets": {
"DISCORD_API_TOKEN": "${DISCORD_API_TOKEN_JULIE}"
}
}
}
- The
.envfile should contain the actual tokens:
DISCORD_API_TOKEN_JULIE=actual_token_here
DISCORD_API_TOKEN_JUAN=actual_token_here
(where Julie and Juan are agents names)
- The token resolution process:
- First checks character's settings.secrets
- If the value is a variable reference (${...}), resolves it from environment
- Otherwise uses the raw value
Testing
To verify the fix:
- Ensure tokens are correctly set in
.env - Run the bot with both characters:
pnpm start --characters="characters/julie.character.json,characters/juan.character.json"
- Check debug logs for token resolution process
Proposal
I suggest:
- Adding this documentation to the main repository
- Possibly including it in the official docs under a "Troubleshooting" or "Configuration" section
- Adding debug logs to help other developers diagnose similar issues
Let me know if you'd like me to create a PR with these changes.