Skip to content

Instantly share code, notes, and snippets.

@iamnotacoder-djs
Created April 13, 2019 02:02
Show Gist options
  • Save iamnotacoder-djs/82b75860a6d05c357a43ff0b919e2ae4 to your computer and use it in GitHub Desktop.
Save iamnotacoder-djs/82b75860a6d05c357a43ff0b919e2ae4 to your computer and use it in GitHub Desktop.
const Discord = require('discord.js');
const client = new Discord.Client();
const request = require('request');
const config = require("./config.json");
var messageId = ""; // В этой переменной храним уникальны ID отслеживаемого ботом сообщения на получение Реакций.
client.login(config.token).catch((err) => {
// Если Node.JS поймал ошибку с текстом err просто выключаем скрипт
// process.exit(0);
});
client.on("ready", () => {
// первый попавшийся канал от метода channels.first() вернул голосовой
// Давай лучше подключимся к нужному нам каналу напрямую!?
client.guilds.first().channels.get("539101775567781913").send("Hello World!");
// Искать в коллекции JavaScript можно при помощи метода .find(). В скобках имя переменной для быстрой проверки. После => сама проверка условия. client.guilds.find(i => i.id > 0)
/*
// Печатаем сообщение для отслеживания Реакций. Сохраняем ID
client.channels.get("539101775567781913").send(`Нажми на эмодзи, чтобы получить/убрать роль!`)
.then((message) => {
message.react("1⃣");
messageId = message.id;
});
*/
// Запускаем функцию, которая загрузит сразу актуальные данные и отобразит, а также запустит отсчет до следующей проверки.
checkTime();
});
// Рекурсивная функция (вызывает сама себя)
function checkTime() {
// Загружаем данные с сервера
getHTTPResponce('https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22')
.then((body) => { // Если сервер вернул ответ, что данные успешно загружены, сохраняет сообщение в body
var result = JSON.parse(body); // Преобразовываем строку с данными оформленными как JSON, в объект.
var temp = parseInt(result.main.temp) - 273.15; // На всякий случай уточняем температура возвращается строкой или числом и вычитаем 273.15 для конвертирования градусов Кельвина в Цельсия
client.channels.get("566371077333450762").setName(`Погода в Лондоне: ${temp}`); // Находим нужный голосовой канал и устанавливаем ему имя.
console.log(`200 Result: ${body}`) // Печатаем в консоль лог, что данные загружены
})
.catch((error) => { // Если сервер вернул код ошибки, сразу её и печатаем в консоль.
console.log(`error: ${error}`);
})
var now = new Date(); // Получаем актуальную дату/время
client.setTimeout(checkTime, (59 - now.getUTCMinutes()) * 60 * 1000); // Запускаем обратный отсчет по истечению которого запустится функция checkTime(). 1000 мс чтобы получить 1 секунду. 1000 * 60, чтобы получить одну минуту. (59 - now.getUTCMinutes()) - кол-во минут осталось до наступления следующего часа.
}
// Наша функция, которая сокращает кол-во печатаемого текста при каждом запросе к серверу.
function getHTTPResponce (url) {
return new Promise((resolve, reject) => { // Конструкция, без которой невозможно воспользоваться слушателями отслеживающими выполнение асинхронной задачи
var options = { // Опции для самого запроса
method: "GET", // GET, POST и проч. Для сохранения данных на своём сервере можно использовать и GET при помощи параметров ?param1=что-то&param2=что-то-другое. Единственное, стоит шифровать такую передачу данных т.к. кириллица может деформироваться. Можно использовать что-то вроде ?param1=${Base64.encode(что-то)}&...
url: url, // url ссылка передаваемая в функцию
headers: { // Заголовки
'User-Agent': 'nodejs request',
'X-Key': "9qpRc8M55pFb8qDN94jH"
}
}
request(options, (error, responce, body) => { // Запуск самого запроса. Возвращает error (null, если ошибок нет). Responce - Объект. Body - сам исходный текст страницы.
if (responce.statusCode != 200) {
reject(error); // Вызов .catch(error)
} else {
resolve(body); // Вызов .then(body)
}
})
});
}
client.on("message", (message) => {
// тут код при получении сообщения в переменную message
// Делаем так, чтобы наш бот не отвечал сам себе!
if (!message.author.bot) {
message.reply("Ответ"); // Напечатает: @author, Ответ
client.channels.get(message.channel.id).send("Ответ");
client.channels.get(message.channel.id).send("*Курсив*");
client.channels.get(message.channel.id).send("||Спойлер||");
client.channels.get(message.channel.id).send("`Блок кода`");
client.channels.get(message.channel.id).send("```Многострочный блок кода```");
var answer = "Ответ";
client.channels.get(message.channel.id).send(`-${answer}-`); // Печать: -Ответ-
client.channels.get(message.channel.id).send("-"+answer+"-"); // Печать: -Ответ-
client.channels.get(message.channel.id).send(`-\`${answer}\`-`);
client.channels.get(message.channel.id).send(`Новое emoji \`:hack:\`: ${client.emojis.find(emoji => emoji.name === "hack")}`);
// Не забываем про NEW Discord.RichEmbed()
const embed = new Discord.RichEmbed()
.setTitle("This is your title, it can hold 256 characters")
.setAuthor("Author Name", "https://i.imgur.com/lm8s41J.png")
/*
* Alternatively, use "#00AE86", [0, 174, 134] or an integer number.
*/
.setColor(0x00AE86)
.setDescription("This is the main body of text, it can hold 2048 characters.")
.setFooter("This is the footer text, it can hold 2048 characters", "http://i.imgur.com/w1vhFSR.png")
.setImage("http://i.imgur.com/yVpymuV.png")
.setThumbnail("http://i.imgur.com/p2qNFag.png")
/*
* Takes a Date object, defaults to current date.
*/
.setTimestamp()
.setURL("https://discord.js.org/#/docs/main/indev/class/RichEmbed")
.addField("This is a field title, it can hold 256 characters",
"This is a field value, it can hold 1024 characters.")
/*
* Inline fields may not display as inline if the thumbnail and/or image is too big.
*/
.addField("Inline Field", "They can also be inline.", true)
/*
* Blank field, useful to create some space.
*/
.addBlankField(true)
.addField("Inline Field 3", "You can have a maximum of 25 fields.", true);
client.channels.get(message.channel.id).send(embed);
client.channels.get(message.channel.id).send({
embed: {
"title": "title ~~(did you know you can have markdown here too?)~~",
"description": "this supports [named links](https://discordapp.com) on top of the previously shown subset of markdown. ```\nyes, even code blocks```",
"url": "https://discordapp.com",
"color": 11750632,
"timestamp": "2019-03-26T13:33:29.282Z",
"footer": {
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png",
"text": "footer text"
},
"thumbnail": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"image": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"author": {
"name": "author name",
"url": "https://discordapp.com",
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"fields": [
{
"name": "🤔",
"value": "some of these properties have certain limits..."
},
{
"name": "😱",
"value": "try exceeding some of them!"
},
{
"name": "🙄",
"value": "an informative error should show up, and this view will remain as-is until all issues are fixed"
},
{
"name": "<:thonkang:219069250692841473>",
"value": "these last two",
"inline": true
},
{
"name": "<:thonkang:219069250692841473>",
"value": "are inline fields",
"inline": true
}
]
}
});
//https://image.ibb.co/hXHFqL/image.jpg
client.channels.get(message.channel.id).send("Картинка", {file: "https://image.ibb.co/hXHFqL/image.jpg"});
}
});
client.on("guildMemberAdd", (member) => {
// тут код при подключении нового участника на сервере в переменную member
});
client.on("error", (error) => {
});
client.on("warn", (warn) => {
});
client.on("debug", (debug) => {
});
const events = {
MESSAGE_REACTION_ADD: 'messageReactionAdd',
MESSAGE_REACTION_REMOVE: 'messageReactionRemove',
};
client.on('raw', async event => {
if (!events.hasOwnProperty(event.t)) return;
const { d: data } = event;
const user = client.users.get(data.user_id);
const channel = client.channels.get(data.channel_id) || await user.createDM();
if (channel.messages.has(data.message_id)) return;
const message = await channel.fetchMessage(data.message_id);
const emojiKey = (data.emoji.id) ? `${data.emoji.name}:${data.emoji.id}` : data.emoji.name;
const reaction = message.reactions.get(emojiKey);
client.emit(events[event.t], reaction, user);
});
client.on('messageReactionAdd', (reaction, user) => {
let member = client.guilds.first().members.find(x => x.id == user.id);
if (member.roles.some(r => ["Вип"].includes(r.name))) {
if (reaction.message.id == messageId) {
if (reaction.emoji.name === "1⃣") {
let role = client.guilds.first().roles.find(x => x.name === "Цвет");
member.addRole(role)
.catch((e)=>{});
}
}
}
})
client.on('messageReactionRemove', (reaction, user) => {
let member = client.guilds.first().members.find(x => x.id == user.id);
if (member.roles.some(r => ["Вип"].includes(r.name))) {
if (reaction.message.id == messageId) {
if (reaction.emoji.name === "1⃣") {
let role = client.guilds.first().roles.find(x => x.name === "Цвет");
member.removeRole(role)
.catch((e)=>{});
}
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment