Deep Mind AI
  • Introduction
  • Examples
    • Getting Started with NextJS
    • Telegram Agent
    • Persistent Agent with PostgreSQL
    • AI Guided Market Making Agent
    • Discord Agent Integration
  • Guides
    • Add your own tool
    • Setup locally
    • Test it out
  • Features
    • Transfer Tokens
    • Stake SOL
    • Deploy SPL Token
    • Check Token Balances
    • Token Data Retrieval
    • Deploy NFT Collection
    • Mint NFT
    • Tensor NFT Marketplace
    • Jupiter Exchange Swaps
    • Solana Name Service (SNS)
    • Launch Token on Pump.fun
Powered by GitBook
On this page
  • Core Features
  • ​Quick Start
  • ​Implementation Details
  • ​Chat History Management
  • ​Agent Configuration
  • ​Error Handling
  • ​Best Practices
  • ​Common Issues
  • ​Development Tips
  • ​Resources
  • ​Support
  1. Examples

Discord Agent Integration

Create a Discord Agent powered by Solana Agent Kit

PreviousAI Guided Market Making AgentNextAdd your own tool

Last updated 3 months ago

Build a Discord Agent that leverages Solana Agent Kit capabilities to interact with the Solana blockchain through Discord messages. This integration enables natural language interactions with blockchain functionality.

Core Features

  1. Bot Infrastructure

    • Direct message handling

    • Typing indicators

    • Chat history management

    • Stream processing

  2. AI Integration

    • LangChain React agent

    • GPT-4 language model

    • Memory persistence

    • Tool integration

Quick Start

1. Prerequisites

# Required versions
Node.js >= v20
pnpm >= v9

# Installation
pnpm install
# .env file
DISCORD_BOT_TOKEN=your_discord_bot_token
SOLANA_PRIVATE_KEY=your_solana_private_key
SOLANA_RPC_URL=your_rpc_url
OPENAI_API_KEY=your_openai_key
  1. Create Application

1. Visit Discord Developer Portal
2. Create New Application
3. Add Bot to Application
4. Copy Bot Token
  1. Enable Intents

const client = new Client({
  intents: [
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.DirectMessages
  ],
  partials: [
    Partials.Message,
    Partials.Channel
  ]
});
async function initializeAgent() {
  // Initialize Language Model
  const llm = new ChatOpenAI({
    modelName: 'gpt-4-mini',
    temperature: 0.3
  });

  // Setup Solana Agent
  const solanaAgent = new SolanaAgentKit(
    process.env.SOLANA_PRIVATE_KEY!,
    process.env.SOLANA_RPC_URL!,
    {
      OPENAI_API_KEY: process.env.OPENAI_API_KEY!
    }
  );

  // Create Tools and Agent
  const tools = createSolanaTools(solanaAgent);
  const memory = new MemorySaver();
  
  return createReactAgent({
    llm,
    tools,
    checkpointSaver: memory,
    messageModifier: customPrompt
  });
}
client.on(Events.MessageCreate, async (message) => {
  // Check for DM
  if (message.channel.type !== ChannelType.DM) return;
  
  // Process Message
  const { agent, config } = await initializeAgent();
  
  // Handle Response Stream
  const stream = await agent.stream({
    messages: userChatHistory
  }, config);
  
  // Process Chunks
  for await (const chunk of stream) {
    if ('agent' in chunk) {
      await message.reply(chunk.agent.messages[0].content);
    }
  }
});
const chatHistory = new Map();

// Add message to history
const userChatHistory = chatHistory.get(userId) || [];
userChatHistory.push(new HumanMessage(message.content));
const replyIfNotEmpty = async (content: string) => {
  if (content.trim() !== '') {
    await message.reply(content);
  }
};
const messageModifier = `
  You are a helpful agent that can interact onchain using the Solana Agent Kit.
  You are empowered to interact onchain using your tools.
  If you ever need funds, you can request them from the faucet.
  Be concise and helpful with your responses.
`;
const tools = createSolanaTools(solanaAgent);
// Available tools:
// - Token operations
// - NFT management
// - DeFi integration
// - Blockchain queries
try {
  await processMessage(message);
} catch (error) {
  console.error('Error handling message:', error);
  await message.reply('An error occurred. Please try again later.');
}
  1. Message Processing

    • Validate inputs

    • Handle timeouts

    • Manage rate limits

    • Track errors

  2. Agent Management

    • Cache initialization

    • Monitor memory

    • Handle disconnects

    • Log interactions

  3. Security

    • Validate permissions

    • Secure keys

    • Monitor usage

    • Rate limit users

  1. Discord API

    • Rate limits

    • Token expiration

    • Permission issues

    • Connection drops

  2. Agent Integration

    • Initialization failures

    • Memory leaks

    • Tool errors

    • Stream interrupts

  3. Blockchain Operations

    • RPC errors

    • Transaction failures

    • Network congestion

    • Balance issues

  1. Local Testing

    • Use test bot

    • Monitor memory

    • Check responses

    • Log everything

  2. Production Deploy

    • Use PM2/similar

    • Monitor resources

    • Set up alerts

    • Regular backups

  3. Maintenance

    • Update dependencies

    • Monitor logs

    • Check performance

    • Update prompts

For assistance:

  • Discord Community

  • GitHub Issues

  • Documentation

  • Stack Overflow

2. Environment Setup

3. Discord Bot Setup

Implementation Details

Agent Initialization

Message Handling

Chat History Management

Memory Structure

Stream Processing

Agent Configuration

Custom Prompt

Tool Integration

Error Handling

Best Practices

Common Issues

Development Tips

Resources

Support

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
Discord.js Guide
Solana Agent Kit Docs
LangChain Documentation
OpenAI Documentation
​