-
Notifications
You must be signed in to change notification settings - Fork 157
/
discord_bot.js
55 lines (50 loc) · 1.54 KB
/
discord_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
// discord.js import
const Discord = require('discord.js');
// node-fetch for making HTTP requests
const fetch = require('node-fetch');
// initialize client
const client = new Discord.Client();
// my model URL
API_URL = 'https://api-inference.huggingface.co/models/r3dhummingbird/DialoGPT-medium-joshua';
// log out some info
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
// when the bot receives a message
// need async message because we are making HTTP requests
client.on('message', async message => {
// ignore messages from the bot itself
if (message.author.bot) {
return;
}
// form the payload
const payload = {
inputs: {
text: message.content
}
};
// form the request headers with Hugging Face API key
const headers = {
'Authorization': 'Bearer ' + process.env.HUGGINGFACE_TOKEN
};
// set status to typing
message.channel.startTyping();
// query the server
const response = await fetch(API_URL, {
method: 'post',
body: JSON.stringify(payload),
headers: headers
});
const data = await response.json();
let botResponse = '';
if (data.hasOwnProperty('generated_text')) {
botResponse = data.generated_text;
} else if (data.hasOwnProperty('error')) { // error condition
botResponse = data.error;
}
// stop typing
message.channel.stopTyping();
// send message to channel as a reply
message.reply(botResponse);
})
client.login(process.env.DISCORD_TOKEN);