Retrieve the top Twitter trends for a specific location and displays them in an embed message on Discord. Inside the main function, it first initializes a variable show to 20, which will be used later to determine how many trends to display in the message. It then makes a request to the Twitter API to get a list of available locations for trends, and filters the list to find the location specified in the message. It then makes a request to the Twitter API to get the list of trends for that location, sorts the trends by tweet volume, and slices the list to get the top show number of trends. Finally, it creates an embed message with the sorted and sliced trend list and sends it to the Discord channel.
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
// Define the 'main' function that will be called by the stdlib function runner
async function main() {
try {
// Set the number of trends to show in the embed message
const show = 20;
// Get the list of available trends
const list = await lib.twitter.trends['@1.1.0'].available.list();
// Get the trend search query from the Discord command input
let city = context.params.event.data.options[0].value;
// Capitalize the first letter of each word in the query
city = city.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
// Find the trend search result in the list of available trends
const searchResult = list.find(o => o.name === city);
// Get the list of trends for the location corresponding to the search result
const trendList = await lib.twitter.trends['@1.1.0'].place.list({id: `${searchResult.woeid}`});
// Get the list of trends
const trendsResults = trendList[0].trends;
// Sort the list of trends by tweet volume (most tweets first)
const sorted = trendsResults.sort((prev, next) => next.tweet_volume - prev.tweet_volume);
// Create the list of fields for the Discord embed message
const fields = sorted.slice(0, show).map((trend, i) => ({
name: `${i + 1}. ${trend.name}`,
value: `Tweets: ${trend.tweet_volume.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')} [show tweets](${trend.url})`,
}));
// Send the Discord embed message with the list of trends
await lib.discord.channels['@0.3.2'].messages.create({
channel_id: context.params.event.channel_id,
embeds: [{
type: 'rich',
title: `Trends for ${searchResult.name}, ${searchResult.country}`,
description: `Showing ${show} most famous trends in ${searchResult.name}`,
color: 0x00ffff,
fields,
}],
});
} catch (error) {
console.error("error on twitter slash command", error);
}
}
await main();
/**
create this slash command on your server:
await lib.discord.commands['@0.1.1'].create({
"name": "twitter_trends",
"description": "search for a city and show twitter trends",
"options": [
{
"type": 3,
"name": "city",
"description": "",
"required": true
}
]
});
*/