Never Miss a Cardano NFT Sale Again: Automating Discord Notifications with JavaScript

Introduction

The world of Non-Fungible Tokens (NFTs) has gained immense popularity, with digital artworks, collectibles, and more being tokenized and traded on various platforms. Cardano, a blockchain network, has witnessed significant growth in the NFT space, particularly in the form of NFT sales. As a Cardano NFT enthusiast or collector, staying updated on the latest sales events is crucial. In this blog post, we will explore how to create a Discord bot using JavaScript that sends periodic notifications about Cardano NFT sales, ensuring you never miss an important opportunity.

Prerequisites

To follow along with this tutorial, you’ll need the following:

  1. Basic knowledge of JavaScript.
  2. A Discord account.
  3. Node.js and npm installed on your machine.
  4. A Discord server where you have administrative permissions to add a bot.

Setting up the Discord Bot

  1. Create a new Discord application by visiting the Discord Developer Portal.
  2. Click on “New application”
  3. Go to “Bot” and create your token

Setting up the Project

  1. Create a new folder on your local machine for the project.
  2. Open a terminal or command prompt and navigate to the project folder.
  3. Initialize a new Node.js project by running the following command:
npm init -y
  1. Install the discord.js library by executing the following command:
npm install -s discord.js

Writing the Code

Create a new JavaScript file, e.g., nftBot.js, and open it in your preferred code editor. Let’s begin by adding the necessary code to establish a connection with Discord and send a message every minute.

const Discord = require('discord.js');
const client = new Discord.Client();
const token = process.env.DISCORD_TOKEN;
const opencnftKey = process.env.OPENCNFT_KEY;
const policy = process.env.POLICY;

let lastTimeSent = undefined;
const opencnftURL = new URL(
    `https://api.opencnft.io/2/collection/${policy}/transaction`,
);

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

client.on('message', (message) => {
    // Start sending Cardano NFT sales notifications every minute
    setInterval(async () => {
        // Code to fetch and send Cardano NFT sales notifications
        opencnftURL.searchParams.set(
            'end_time',
            lastTimeSent ? Math.floor(lastTimeSent.getTime() / 1_000) : undefined,
        );
        const opencnftResponse = await fetch(opencnftURL.toString(), {
            headers: {
                'x-api-key': opencnftKey,
            },
        });
        if (opencnftResponse.ok) {
            const { transactions } = await opencnftResponse.json();

            const notification = `${transactions
                .map(
                (tx) =>
                    `New sale on ${tx.marketplace}: ${tx.name} at ₳${Math.floor(
                    tx.price / 1e6,
                    )}`,
                )
                .join('\n')}`;
            message.channel.send(notification);
            lastTimeSent = new Date();
        }
    }, 60000);
});

client.login(token);

In this code, we utilize the discord.js library to create a Discord bot client. The client.once('ready') event is triggered once the bot is connected and ready to be used. The client.on('message') event listens for messages sent to the Discord server and checks if the content is equal to !start. If it matches, the bot will start sending Cardano NFT sales notifications every minute.

Customizing Cardano NFT Sales Notifications

To fetch Cardano NFT sales events and customize the notifications, you can integrate with Cardano-specific APIs, platforms, or any other relevant data sources that provide sales information. Modify the code inside the setInterval function to suit your requirements. You can fetch the latest Cardano NFT sales events, filter based on specific criteria (such as price, collection, or rarity), format the message, and send it to the desired Discord channel.

Running the Bot

  1. Save the nftBot.js file.
  2. Open a terminal or command prompt and navigate to the project folder.
  3. Execute the following command to start the bot:
DISCORD_TOKEN=<discord-token> OPENCNFT_KEY=<opencnft-api-key> POLICY=<tracked-policy> node nftBot.js

Conclusion

By creating a Discord bot using JavaScript and the discord.js library, you can automate the process of receiving Cardano NFT sales notifications. This allows you to stay up-to-date with the latest sales events happening on the Cardano blockchain and seize potential opportunities in the NFT market.