Как создать чат-бота Discord с помощью IBM Watson Conversation API!
Загрузите любой текстовый редактор или IDE, который вы хотите {я использую Vs Code}
Сначала вам нужно будет зайти на IBM CLOUD SERVER и создать учетную запись IBM. IBM предлагает уровень бесплатного пользования, в который входит все, что вам нужно.
Затем выполните следующие действия, чтобы создать API преобразования:
1. Перейдите на панель инструментов и создайте приложение
2. Выберите Watson Assistant для типа ресурсов.
3. Теперь сохраните все свои учетные данные в файле JSON, который мы будем использовать позже.
4. Теперь загрузите Node JS {Мы используем JavaScript}
5. Создайте папку и назовите ее как хотите.
6. Откройте командную строку в этом каталоге.
7. Сначала проверьте правильность установки узла, набравNode -v
8. Теперь, если он не показывает никаких ошибок, следуйте инструкциям или если какие-либо ошибки перезагрузите компьютер.
9. Теперь нам нужно установить Watson SDK и Discord.js
10. Тип npm install watson-developer-cloud
Чтобы установить Watson SDK
11. После этого типа npm install discord.js
Чтобы установить Discord API
12. Перейдите на портал разработчиков Discord и создайте учетную запись Discord или войдите в систему, если она у вас уже есть.
13. Создайте новое приложение. Перейдите в раздел ботов и включите кнопку с надписью «Это приложение станет ботом».
14. Теперь заполните все детали, и он даст вам токен. Сохраните его в безопасном месте, не делитесь им ни с кем …
15. Теперь перейдите к OAuth2 и в разделе Scope выберите Bot, а затем выберите разрешение Bot для этого руководства. Выберите Admin…
16. Теперь перейдите по ссылке, которую она сгенерировала выше, и выберите сервер для своего бота.
17. Теперь давайте начнем кодировать…
Создайте файл Main.js в папке, которую мы создали ранее
And Paste This Code In That File:
```
// Main Files Import
//This is The JSON File With The Bot Token In It..
const botConf = require("./botConfig.json");
//This is the Disocord.js API we download before..
const Discord = require("discord.js");
// Custom Files Import
//We will be making this file after this one
const Comm = require("./Commands");
// We will now using Watson SDK now but it's important to load it first
const Wat = require('./Watson API');
// Destructuring Modules And Classes
const {
Client,
ClientUser
} = Discord;
// Bot Initialiser
const Bot = new Client();
// Bot Starting Message
Bot.on("ready", () => {
console.log("INITIALISING SKYNET SECURITY SYSTEMS PLEASE WAIT.........")
setTimeout(() => {
console.log("SKYNET ACTIVE");
}, 1000);
});
/*
This Space is for Commands Customisations
*/
const Main = new Comm.Main();
Main.Com1();
const PoP = new Wat.Wat();
PoP.Bot();
// Logging in bot into the server
Bot.login(botConf.token); //Use the bot token here
```
Теперь создайте файл Commands.js в том же каталоге
and paste this code in that file...
const botConf = require("./botConfig.json");
const Discord = require("discord.js");
const request = require('request');
const {
Client,
ClientUser,
Role
} = Discord;
// Bot Initialiser
const Bot = new Client();
class Main {
Main() {
}
Com1() {
Bot.on("message", (mess) => {
console.log(mess.content)
let Mess = mess.content.split(" ");
switch (Mess[0]) {
case `${botConf.prefix}Hello`:
mess.channel.send(`Hello! ${mess.author} I'm SKYNET I'm new to human world and still observing every action for some amazing stuff I will controll everything in Year 3000 see you in future`);
setTimeout(() => {
mess.channel.send("Hope You're Having A Great Day ; )");
}, 2000);
break;
case `${botConf.prefix}Who`:
mess.channel.send("Cyber Expert is a good person and a happy software developer as well. He likes people with some differnent kind of personalities");
mess.guild.members.first().sendMessage("Hope you enjoy your stay as we enjoy your welcome into our fold thanks for joining us");
break;
case `${botConf.prefix}so`:
let userMess = Mess[1];
console.log(userMess);
mess.channel.send(`Hey guys a big fat shout out for ${userMess}`);
break;
case `${botConf.prefix}addrole`:
if (mess.guild.members.first().hasPermissions("ADMINISTRATOR")) {
let addrole = mess.content.split(" ");
let Roll = mess.guild.roles.find(r => r.name === addrole[1]);
console.log(Roll.id);
mess.mentions.users.forEach((e) => {
mess.guild.members.find(r => r.id === e.id).addRole(Roll.id);
});
} else {
mess.guild.members.first().sendMessage("You Dont Have Permission Required To Use This Command { Contact Mod's To Do This }!")
}
break;
case `${botConf.prefix}Commands`:
mess.channel.sendCode("", "1. !Who : Tell Us About Cyber Expert Who He Is And What He Likes \n2. !Hello : Say Hello To Cyber Expert \n3. !Commands : Tells All The Commands Can Be Used By Everyone");
break;
}
setInterval(() => {
request(' (error, response, body) => {
mess.channel.sendCode(`${response.body}`);
});
}, 1000 * 60 * 60);
});
}
}
Bot.login(botConf.token);
module.exports = {
Main
};
Сейчас последний раз сделайте Watson API.js
и вставьте этот код внутри
// All Module Imports For Watson Conversation API
const Watson = require("watson-developer-cloud/assistant/v2");
const watson = require('watson-developer-cloud');
const Cred = require("./ibm-credentials.json");
const botConf = require("./botConfig.json");
const Discord = require("discord.js");
const {
Client,
ClientUser,
Role
} = Discord;
// Global Variable For Seesion and Etc
var Sess_ID;
var Res;
// Initialising Watson Assisstant
const Ass = new Watson({
version: '2018-11-08',
username: 'Put Your Watson Login Username',
password: 'Put Your Watson Login Password',
url: Cred.URL
}, (err, res) => {
console.log(err);
console.log(res);
});
// Initialising Watson Services
const service = new watson.AssistantV2({
iam_apikey: Cred.API, //Put Your API key from the credential JSON file we created earlier
version: '2018-11-08',
url: Cred.URL //Put your Url From that credentials JSON file we created earlier
});
// Section For Invoking All Watson API Services And Sending Messages To Conversational Bot And Receiving The Response Back
class Main {
Start_Sessions() {
// Session Starting
service.createSession({
assistant_id: Cred.Ass_ID, //Put your Assistant ID from the watson website
}, function (err, response) {
if (err) {
console.error(err);
} else {
Sess_ID = response.session_id;
console.log(Sess_ID);
}
});
}
Sending_Messages(mess, callback) {
// Sending Messages With a Delay Of 5 Sec
setTimeout(() => {
service.message({
assistant_id: Cred.Ass_ID, //Put your Assistant ID from the watson website
session_id: Sess_ID,
input: {
'message_type': 'text',
'text': `${mess}`
}
}, function (err, response) {
if (err)
console.log('Error: Sorry For Some Trouble');
else
Res = response.output.generic[0].text.replace( /!/gi ,"");
callback(Res);
});
}, 5000);
}
// Removing Sessions Explicitly Instead Of Session Time Out For API On A Delay Of 9 Sec
Removing_Sessions() {
setTimeout(() => {
service.deleteSession({
assistant_id: Cred.Ass_ID, //Put your Assistant ID from the watson website
session_id: `${Sess_ID}`,
}, function (err, response) {
if (err) {
console.error("Sorry Some Error's Need To Be Fixed");
} else {
console.log(JSON.stringify(response, null, 2));
}
});
}, 9000);
}
Bot() {
const Ses = new Main();
const Bot = new Client();
Bot.on("message", (mess) => {
if (mess.content.includes("!")) {
Ses.Start_Sessions();
let mess1 = mess.content.replace("!", "");
Ses.Sending_Messages(mess1, Bot_Call);
//setTimeout(() => { Ses.Removing_Sessions(); }, 1000);
}
function Bot_Call(Result) {
// Bot Initialiser
mess.channel.send(Result);
}
});
Bot.login(botConf.token);
}
}
module.exports.Wat = Main;
Теперь запустите своего бота в NodeJS
1. Open a console inside your project dir
2. type ``` Node ./Main.js ```
3. And It Should Be Working Perfectly ; )
4. Using watson online tools you can make Dialogs and more { Need To Do Some Research YourSelf I don't waana spoil everything ; ) Good Luck This is just for Demo }