X, in any other case higher acknowledged as Twitter, is among the main platforms the place the crypto group is most engaged. Serving as a hub for real-time updates, Twitter is usually the place the newest blockchain developments and information break. The emergence of crypto Twitter bots (X bots) have additional enriched the person expertise and play an important function in preserving customers knowledgeable and engaged – providing a spread of functionalities from monitoring cryptocurrency value modifications to delivering personalised content material.
In as we speak’s tutorial, we’ll cowl methods to construct your personal Twitter bot (X bot) that tweets crypto value updates. Particularly, we’ll design a bot that may tweet the high 5 NFTs by buying and selling quantity, their respective flooring value and 24-hour share change.
We’ll be utilizing the next APIs:
- CoinGecko API – We might be leveraging NFT knowledge endpoints to get NFT collections’ flooring costs.
- Twitter API v2 library – That is the required code library that permits us to hook up with Twitter and tweet.
How one can Construct A Crypto Worth Twitter Bot (4 Steps)
We’ll be making a Twitter bot utilizing Javascript, with minimal coding information wanted. This is a fast overview of the steps:
- Get NFT knowledge from CoinGecko API.
- Create a tweet operate.
- Consolidate in a single fundamental() operate.
- Deploy on server and schedule automation.
Let’s dive in!
For the benefit of demonstration, we’ll be referencing the platform Twitter and X interchangeably.
Conditions and Packages to Set up
For this tutorial, you’ll require the next libraries put in:
- axios
- twitter-api-v2
- cron
You’ll be able to set up them by typing the next command in your terminal after you will have created an npm repository.
npm set up axios twitter-api-v2
Step 1: Get NFT Information from CoinGecko API
We’ll first navigate to the CoinGecko API documentation. The next two endpoints will permit us to retrieve the related NFT knowledge factors:
- /nft/record – Get the highest 5 NFT collections based mostly on 24-hour buying and selling quantity in USD.
- /nfts/{id} – Get the person flooring value and share (%) change for every NFT, utilizing the ids of the NFTs from (1).
First, we outline an array NftData which is able to retailer all of the required knowledge (resembling value, % change, and title) in a worldwide scope in order that different capabilities can entry it.
let NftData = [];
The array ought to appear to be this as soon as populated.
[
{
name: 'Bored Ape Yacht Club',
floor_price: 26.7,
native_currency_symbol: 'ETH',
floor_price_24h_change: 1.3282732447817835
},
{
name: 'Pudgy Penguins',
floor_price: 10.67,
native_currency_symbol: 'ETH',
floor_price_24h_change: -0.6335010247810696
}
]
Then, we create a getTopNFT operate to execute the API calls. Right here’s a walkthrough of the code.
- We outline an area array topNFT to retailer our high 5 NFTs in order that we will loop by way of to get every NFT’s value knowledge.
- The primary name is to /nfts/record to acquire the present high 5 NFTs by USD buying and selling quantity. To filter this we go within the parameters
- order=h24_volume_usd_desc
- per_page=5
- web page=1
- We then save the 5 NFT ids within the topNFT array.
- The second name is made to /nfts/{id} to get the title, value, image, and 24H change of every NFT. We nest this in a for loop in order that we will get the info for all 5 NFTs.
- We then save them into the NftData array.
async operate getTopNFT() {
let topNFT = [];
const url="https://api.coingecko.com/api/v3/nfts/record?order=h24_volume_usd_desc&per_page=5&web page=1";
await axios.get(url)
.then(operate (response) {
topNFT = topNFT.concat(response.knowledge.map(key => key.id));
})
.catch(operate (error) { console.log(error) })
console.log(topNFT);
for (let i = 0; i < topNFT.size; i++) {
const url2 = 'https://api.coingecko.com/api/v3/nfts/' + topNFT[i];
await axios.get(url2)
.then(operate (response) {
var x = response.knowledge;
NftData.push({
"title": x.title,
"floor_price": x.floor_price.native_currency,
"native_currency_symbol": x.native_currency_symbol,
"floor_price_24h_change": x.floor_price_24h_percentage_change.native_currency
});
})
.catch(operate (error) { console.log(error) })
}
}
Step 2: Create A Tweet Perform
Let’s begin with initializing a Twitter consumer, utilizing the next code:
const twitterApi = require('twitter-api-v2');
// Initialize Twitter API consumer
const twitterClient = new twitterApi.TwitterApi({
appKey:'your-app-key',
appSecret:'your-app-secret',
accessToken: 'your-access-token',
accessSecret:'your-access-secret',
});
// Learn+Write degree
const rwClient = twitterClient.readWrite;
To tweet programmatically you will have to create a Twitter developer account, which provides you with the credentials like appKey.
When you enter the portal, create a mission and an app beneath the mission. Click on on the mission web page and you will note the ‘App’ part. Merely click on on the important thing icon right here.
Within the subsequent web page, copy the next credentials (we have now moreover indicated which area they need to be mapped to as properly).
- Client keys
- API credentials – that is appKey
- API secret – that is appSecret
- Authentication keys
- Entry token – that is accessToken
- Entry secret – that is accessSecret
After getting maintain of the credentials, it’s time to create our tweet operate! Right here’s a fast explainer for the code:
All of the motion occurs within the attempt block. The operate ought to settle for an enter logMessages which comprises an array with every ingredient representing a line of NFT value knowledge.
async operate tweetNFTPrices(logMessages) {
attempt {
} catch (error) {
console.error('Error posting tweet:', error);
}
}
We first examine if logMessages is being handed in and it comprises not less than one ingredient.
if (logMessages && logMessages.size > 0) {
}
Subsequent, we format the tweet by including a header and footer.
For reference, right here’s the ultimate message we might be developing, and in brackets are their references within the code.
Prime 5 NFT flooring costs
(logMessageArray)
Bored Ape Yacht Membership -> 26.7 ETH | 🟢↑ 1.1%
Pudgy Penguins -> 11.37 ETH | 🟢↑ 6.2%
Azuki -> 6.39 ETH | 🟢↑ 1.4%
Mutant Ape Yacht Membership -> 5.09 ETH | 🟢↑ 2.3%
DeGods -> 3.31 ETH | 🟢↑ 6.0%
(Footer)
24H %
#Coingecko #NFT
const header="Prime 5 NFT flooring costs"; // Outline your header right here
const footer="nn24H %n#Coingecko #NFT "; // Outline your footer right here
The next code constructs the tweet in a for loop, including each line of NFT knowledge to the tweet and stops if it exceeds the tweet character restrict. If it stops, the code continues and the tweet textual content might be up till the purpose earlier than it stops.
// Be a part of log messages whereas contemplating character restrict
let combinedLogMessages = `${header}nn`;
let currentLength = combinedLogMessages.size;
const maxTweetLength = 280; // Most characters for a tweet
for (const message of logMessages) {
if (currentLength + message.size + footer.size <= maxTweetLength) {
combinedLogMessages += `${message}n`;
currentLength += message.size;
} else {
break; // Break loop if exceeding character restrict
}
}
It then combines with the footer.
combinedLogMessages += footer;
Lastly, it sends out the tweet with the rwClient.v2.tweet operate. The message must be handed within the textual content area within the object. Keep in mind so as to add await as it’s an asynchronous operate.
await rwClient.v2.tweet({
textual content: combinedLogMessages,
});
Placing every little thing collectively, the tweetNFTPrices operate ought to appear to be the next.
async operate tweetNFTPrices(logMessages) {
attempt {
if (logMessages && logMessages.size > 0) {
const header="Prime 5 NFT flooring costs"; // Outline your header right here
const footer="nn24H %n#Coingecko #NFT "; // Outline your footer right here
// Be a part of log messages whereas contemplating character restrict
let combinedLogMessages = `${header}nn`;
let currentLength = combinedLogMessages.size;
const maxTweetLength = 280; // Most characters for a tweet
for (const message of logMessages) {
if (currentLength + message.size + footer.size <= maxTweetLength) {
combinedLogMessages += `${message}n`;
currentLength += message.size;
} else {
break; // Break loop if exceeding character restrict
}
}
combinedLogMessages += footer;
await rwClient.v2.tweet({
textual content: combinedLogMessages,
});
console.log('Tweeted the put up:', combinedLogMessages); //You'll be able to print it in console for cross checking
} else {
console.error('Error: logMessages array is empty or undefined.');
}
} catch (error) {
console.error('Error posting tweet:', error);
}
}
With that, you’re one step away from having the ability to tweet your crypto value updates from the code!
Step 3: Consolidate in One Essential() Perform
The fundamental() operate consolidates and executes all of the steps above, specifically, it will get the required value knowledge, codecs it, after which tweets it out. Let’s break it down, step-by-step.
First, we name getTopNFT() to fetch the NFT knowledge.
//Get the info
await getTopNFT();
Then, with the required NFT knowledge now populated within the NftData array, we’ll additional format it and put it aside right into a logMessagesArray array.
For every NFT (utilizing a for loop), trim the 24H flooring value change to 1 decimal place.
const formattedChange = parseFloat(floor_price_24h_change).toFixed(1);
Relying on the 24H change, add inexperienced/pink/black emoji and up/down arrow for higher visualization.
if (floor_price_24h_change > 0) {
changeSymbol="🟢u{2191}"; // Inexperienced arrow up emoji
} else if (floor_price_24h_change < 0) {
changeSymbol="🔴u{2193}"; // Crimson arrow down emoji
} else {
changeSymbol="⚫️"; // Black circle emoji for no change
}
Assemble the ultimate type of every NFT value knowledge line into ‘Bored Ape Yacht Membership -> 26.7 ETH | 🟢↑ 1.13%’ and add it to the logMessagesArray array.
const logMessage = `${title} -> ${floor_price} ${native_currency_symbol} | ${changeSymbol} ${formattedChange}%`;
logMessagesArray.push(logMessage); // Push every log message to the array
Lastly, go logMessagesArray into the tweetNFTPrices operate that we created in step 2. It’s going to then fireplace the tweet out and violà – you will have made your twitter bot tweet!
attempt {
await tweetNFTPrices(logMessagesArray);
} catch (error) {
console.error('Error posting tweet:', error);
}
Right here’s the amalgamation of the operate.
async operate fundamental() {
//Get the info
await getTopNFT();
//Format tweet
const logMessagesArray = [];
for (let i = 0; i < NftData.size; i++) {
const { title, floor_price, native_currency_symbol, floor_price_24h_change } = NftData[i];
let changeSymbol="";
// Limiting floor_price_24h_change to 1 decimal place
const formattedChange = parseFloat(floor_price_24h_change).toFixed(1);
if (floor_price_24h_change > 0) {
changeSymbol="🟢u{2191}"; // Inexperienced arrow up emoji
} else if (floor_price_24h_change < 0) {
changeSymbol="🔴u{2193}"; // Crimson arrow down emoji
} else {
changeSymbol="⚫️"; // Black circle emoji for no change
}
const logMessage = `${title} -> ${floor_price} ${native_currency_symbol} | ${changeSymbol} ${formattedChange}%`;
logMessagesArray.push(logMessage); // Push every log message to the array
}
console.log(logMessagesArray); // Log your complete array after the loop finishes
//Tweet it out
attempt {
await tweetNFTPrices(logMessagesArray);
} catch (error) {
console.error('Error posting tweet:', error);
}
}
Step 4: Deploy on Server and Schedule Automation
Lastly, to run the script often at a set interval with out having to manually set off it each time, we might want to deploy it to a server and arrange a scheduler.
Set up the node-cron bundle if you have not already:
npm set up node-cron
To run this script each 00:00 of the day, we will merely wrap this round fundamental().
// Schedule the script to run each 24 hours
cron.schedule('0 0 * * *', async () => {
console.log('Operating script each 24 hours...');
attempt {
await fundamental(); // Name your fundamental operate right here
} catch (error) {
console.error('Error working fundamental operate:', error.message);
}
});
Right here is one other instance if you wish to run it each 5 minutes, though this isn’t advisable, as a result of we shouldn’t be posting duplicate content material on Twitter/X.
// Wrap your fundamental operate name in a cron job that runs each 5 minutes
cron.schedule('*/5 * * * *', async () => {
console.log('Operating script each 5 minutes');
attempt {
await fundamental(); // Name your fundamental operate right here
} catch (error) {
console.error(error.message);
}
});
}
To run the script remotely, you may deploy this script to any cloud server based mostly in your preferences. There are a number of choices out there, from self-managed servers resembling AWS EC2, GCP, Digital Ocean, and Linode to Platform as a Service PaaS like Heroku, Azure or AWS Elastic Beanstalk that provide simplified deployment workflows. Furthermore, you may also use display screen session to run your script on the background of your Digital Non-public Server.
To run the script domestically, merely enter the next command in your terminal:
node your_script_name.js
Right here’s the script placing every little thing collectively from the beginning on your reference.
const axios = require('axios');
const twitterApi = require('twitter-api-v2');
const cron = require('node-cron');
// Initialize Twitter API consumer
const twitterClient = new twitterApi.TwitterApi({
appKey:'your-app-key',
appSecret:'your-app-secret',
accessToken: 'your-access-token',
accessSecret:'your-access-secret',
});
// Learn+Write degree
const rwClient = twitterClient.readWrite;
// Json array to retailer NFT knowledge resembling value, % change
let NftData = [];
async operate getTopNFT() {
let topNFT = [];
const url="https://api.coingecko.com/api/v3/nfts/record?order=h24_volume_usd_desc&per_page=5&web page=1";
await axios.get(url)
.then(operate (response) {
topNFT = topNFT.concat(response.knowledge.map(key => key.id));
})
.catch(operate (error) { console.log(error) })
console.log(topNFT);
for (let i = 0; i < topNFT.size; i++) {
const url2 = 'https://api.coingecko.com/api/v3/nfts/' + topNFT[i];
await axios.get(url2)
.then(operate (response) {
var x = response.knowledge;
NftData.push({
"title": x.title,
"floor_price": x.floor_price.native_currency,
"native_currency_symbol": x.native_currency_symbol,
"floor_price_24h_change": x.floor_price_24h_percentage_change.native_currency
});
})
.catch(operate (error) { console.log(error) })
}
}
async operate tweetNFTPrices(logMessages) {
attempt {
if (logMessages && logMessages.size > 0) {
const header="Prime 5 NFT flooring costs"; // Outline your header right here
const footer="nn24H %n#Coingecko #NFT "; // Outline your footer right here
// Be a part of log messages whereas contemplating character restrict
let combinedLogMessages = `${header}nn`;
let currentLength = combinedLogMessages.size;
const maxTweetLength = 280; // Most characters for a tweet
for (const message of logMessages) {
if (currentLength + message.size + footer.size <= maxTweetLength) {
combinedLogMessages += `${message}n`;
currentLength += message.size;
} else {
break; // Break loop if exceeding character restrict
}
}
combinedLogMessages += footer;
await rwClient.v2.tweet({
textual content: combinedLogMessages,
});
console.log('Tweeted the put up:', combinedLogMessages);
} else {
console.error('Error: logMessages array is empty or undefined.');
}
} catch (error) {
console.error('Error posting tweet:', error);
}
}
async operate fundamental() {
//Get the info
await getTopNFT();
//Format tweet
const logMessagesArray = [];
for (let i = 0; i < NftData.size; i++) {
const { title, floor_price, native_currency_symbol, floor_price_24h_change } = NftData[i];
let changeSymbol="";
// Limiting floor_price_24h_change to 1 decimal place
const formattedChange = parseFloat(floor_price_24h_change).toFixed(1);
if (floor_price_24h_change > 0) {
changeSymbol="🟢u{2191}"; // Inexperienced arrow up emoji
} else if (floor_price_24h_change < 0) {
changeSymbol="🔴u{2193}"; // Crimson arrow down emoji
} else {
changeSymbol="⚫️"; // Black circle emoji for no change
}
const logMessage = `${title} -> ${floor_price} ${native_currency_symbol} | ${changeSymbol} ${formattedChange}%`;
logMessagesArray.push(logMessage); // Push every log message to the array
}
console.log(logMessagesArray); // Log your complete array after the loop finishes
//Tweet it out
attempt {
await tweetNFTPrices(logMessagesArray);
} catch (error) {
console.error('Error posting tweet:', error);
}
}
// Schedule the script to run each 24 hours
cron.schedule('0 0 * * *', async () => {
console.log('Operating script each 24 hours...');
attempt {
await fundamental(); // Name your fundamental operate right here
} catch (error) {
console.error('Error working fundamental operate:', error.message);
}
});
The Remaining Product: Crypto Worth Twitter Bot
In 4 straightforward steps, we have now created an automatic crypto value Twitter or X bot that tweets the present high 5 NFT Collections by buying and selling quantity, with every of their flooring costs and share value change (see it in motion on Twitter/X: https://twitter.com/nft_listing_bot).
Potential Enhancements & Professional-Suggestions
For ease of this tutorial, we have created a simplified crypto value Twitter/X bot. Nonetheless listed below are some potential enchancment areas:
-
Work round Twitter/X’s character restrict by assemble a tweet thread. The character restrict for a single tweet may be busted within the occasion of 1 or a number of lengthy NFT names ensuing within the tweet being lower off. As a possible enhancement, you may also examine the character restrict and use the tweetThread methodology to put up it as a thread. This ensures that you just all the time get to put up your complete NFT knowledge with out the inhibition of character restrict.
- Use a paid unique CoinGecko API endpoint to make API calls extra environment friendly. This tutorial makes 6 calls to 2 totally different API endpoints which are publicly accessible. Alternatively, you may really get the identical knowledge utilizing the /nfts/markets endpoint, out there on our paid plan.
Conclusion
With the best APIs, constructing a Twitter bot or X bot is rather a lot easier than it sounds – even for people with minimal coding information. To sum, the method entails retrieving crypto value knowledge from the CoinGecko API, establishing a tweet operate, consolidating functionalities inside a fundamental() operate, and at last, deploying the bot on a server with the aptitude to schedule automation. This course of might be additional replicated with different endpoints to create several types of Twitter or X bots that tweet various knowledge.
This text was co-written by Alan and Tiong Woon.
#Construct #Crypto #Twitter #Bot #Simple #Steps
Read full Article