Mobula API enables the integration of real-time token prices into a Discord server, enhancing engagement and providing immediate value to its members. This guide will detail how to set up a Discord bot using Mobula API to display token prices.

What you’ll need

  1. Knowledge in Python and Node.js programming languages.
  2. Knowledge of the Discord API.
  3. A database like MySQL, PostgreSQL, or MongoDB to store user data and transaction histories.
  4. A web cloud server to host the bot, ensuring its availability and responsiveness.
  5. An API key from the Dashboard (required for production; optional in development mode).

Walkthrough

1

Set up your bot on Discord

  • Go to the Discord Developer Portal
  • Click New Application, name your bot, and create it
  • In the Bot tab, click Add Bot and confirm by clicking Yes, do it!
  • Save the token provided for later use
2

Invite Your Bot to Your Server

  • In the OAuth2 tab, under Scopes, check bot
  • Under Bot Permissions, select permissions like Send Messages and Read Message History
  • Open the generated URL in your browser to invite the bot to your server
3

Set Up Your Development Environment

  • Install Node.js and npm if not already installed
  • Create a new directory for your bot and navigate into it.
  • Run npm init -y to create a package.json file.
  • Install necessary packages:
npm install discord.js axios dotenv
4

Create the Bot Script

  • Create a file named bot.js.
  • Use the following script, replacing your_bot_token_here with your Discord bot token and your_api_key_here with your Mobula API key:
require('dotenv').config();
const { Client, GatewayIntentBits } = require('discord.js');
const axios = require('axios');

const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });

client.once('ready', () => {
console.log('Ready!');
});

client.on('messageCreate', async message => {
if (!message.content.startsWith('!price') || message.author.bot) return;

const asset = message.content.split(' ')[1]; // Assumes command format is "!price Bitcoin"
if (!asset) {
    message.channel.send('Please specify an asset.');
    return;
}

try {
    const response = await axios.get(`https://api.mobula.io/api/1/market/data?asset=${asset}`, {
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'YOUR_API_KEY_HERE'
        }
    });
    const price = response.data.data.market_data.price_usd; // Adjust according to your API response structure
    message.channel.send(`The current price of ${asset} is $${price}`);
} catch (error) {
    console.error(error);
    message.channel.send('Failed to fetch price.');
}
});

client.login('YOUR_BOT_TOKEN_HERE');
5

Run Your Bot

  • Create a .env file in the same directory with your bot token and API key:
DISCORD_TOKEN=YOUR_BOT_TOKEN_HERE
MOBULA_API_KEY=YOUR_API_KEY_HERE
  • Start your bot by running:
node bot.js
6

Deploy the Bot

Choose a hosting service such as Heroku for easy setup and a free tier suitable for small projects, AWS (Amazon Web Services) for robust services like EC2 or Elastic Beanstalk that are scalable, or DigitalOcean for affordable and scalable Droplets for larger deployments.

Deployment Process

  • For Heroku:
    1. Install Heroku CLI: https://devcenter.heroku.com/articles/heroku-cli
    2. Login to your Heroku account in the terminal: heroku login
    3. Create a new Heroku app: heroku create
    4. Push your code to Heroku: git push heroku master
    5. Scale your dyno: heroku ps:scale web=0 worker=1
  • Ensure you have a Procfile in your project root that looks like this: worker: node bot.js
7

Perform Functional Testing

  • Local Testing: Before deploying, test the bot locally by running it and using commands in Discord to ensure it responds correctly.
  • Staging Environment: If possible, use a staging environment on your hosting service to mimic production conditions.
8

Continuous Monitoring and Maintenance

  • Logging: Implement logging in your bot’s code to track errors and unusual behaviors. Tools like Winston or Morgan can be useful.
  • Error Handling: Make sure your bot has error handling for failed API calls or unexpected inputs.
  • Performance Monitoring: Use tools provided by your hosting service or third-party services like Datadog or New Relic to monitor your application’s performance.
  • Updates: Regularly update your bot’s dependencies and adjust to changes in the Discord API or Mobula API.

Need help?

Having issue integrating your API key? Reach out to us, response times < 1h.