-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbot.js
99 lines (85 loc) · 2.71 KB
/
bot.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Require dependencies
const { Client } = require('discord.js');
const dotenv = require('dotenv');
const axios = require('axios');
// Load environment variables
dotenv.config();
// Create a bot instance
const bot = new Client();
// Log our bot in
bot.login(process.env.DISCORD_BOT_TOKEN);
// Log to console when bot is ready
bot.on('ready', () => {
console.log(`${bot.user.username} is up and running!`);
});
// Reply to user messages
bot.on('message', async (message) => {
// Do not reply if message was sent by bot
if (message.author.bot) return;
// Reply to !ping
if (message.content.startsWith('!ping')) {
return message.reply('I am working!');
}
// Reply to !price
if (message.content.startsWith('!price')) {
// Get the params
const [command, ...args] = message.content.split(' ');
// Check if there are two arguments present
if (args.length !== 2) {
return message.reply(
'You must provide the crypto and the currency to compare with!'
);
} else {
const [coin, vsCurrency] = args;
try {
// Get crypto price from coingecko API
const { data } = await axios.get(
`https://api.coingecko.com/api/v3/simple/price?ids=${coin}&vs_currencies=${vsCurrency}`
);
// Check if data exists
if (!data[coin][vsCurrency]) throw Error();
return message.reply(
`The current price of 1 ${coin} = ${data[coin][vsCurrency]} ${vsCurrency}`
);
} catch (err) {
return message.reply(
'Please check your inputs. For example: !price bitcoin usd'
);
}
}
}
// Reply to !news
if (message.content.startsWith('!news')) {
try {
const { data } = await axios.get(
`https://newsapi.org/v2/everything?q=crypto&apiKey=${process.env.NEWS_API_KEY}&pageSize=1&sortBy=publishedAt`
);
// Destructure useful data from response
const {
title,
source: { name },
description,
url,
} = data.articles[0];
return message.reply(
`Latest news related to crypto:\n
Title: ${title}\n
Description:${description}\n
Source: ${name}\n
Link to full article: ${url}`
);
} catch (err) {
return message.reply('There was an error. Please try again later.');
}
}
// Reply to !help
if (message.content.startsWith('!help')) {
return message.reply(
`I support 4 commands:\n
!ping - To check if I am working\n
!price <coin_name> <compare_currency> - To get the price of a coin with respect to another coin or currency\n
!news - To get the latest news article related to crypto\n
!help - For checking out what commands are available`
);
}
});