2부: Eris와 Yuuko로 더 많은 명령 만들기 - Embeds

2 부



다음 부분을 건너뛰려면 here 을 클릭하십시오.

이전 게시물의 코드



약속한 대로 그냥 잡고 싶은 사람들을 위해 여기에 코드를 넣을 것입니다.
프로젝트 디렉토리:

│   .env
│   index.js
│   package-lock.json
│   package.json
│
├───commands
│       owo.js
│
├───events
│       ready.js
│
└───node_modules
    │   ...

./.env
TOKEN=<your-token-here>
PREFIX=<your-bot-prefix>

./index.js
const { Client } = require('yuuko');
const path = require('path');
const dotenv = require('dotenv');
var env = dotenv.config();
env = process.env;

const bot = new Client({
    token: env.TOKEN,
    prefix: env.PREFIX,
    ignoreBots: true,
});

bot.extendContext({
    variableOne: 'Variable number 1!',
});
bot.editStatus('dnd'); // edits bot status

bot.on('error', (err) => {
    console.error(err);
});

bot.globalCommandRequirements = {
    guildOnly: true,
};

bot
    .addDir(path.join(__dirname, 'commands'))
    .addDir(path.join(__dirname, 'events'))
    .connect();

./package.json + ./package-lock.json이것을 보여주지는 않겠지만 yuuko , eris , dotenv 가 설치되어 있어야 합니다../commands/owo.js
const { Command } = require('yuuko');
module.exports = new Command('owo', (message, args, context) => {
  message.channel.createMessage('OwO');
});

./events/ready.js
const { EventListener } = require('yuuko');
module.exports = new EventListener('ready', ({client}) => {
  console.log(`Logged in as ${client.user.usename}`);
});


지금은 이것이 모든 코드여야 합니다.

밈 명령

Now, for the Meme command! For this, we will need to get the memes from reddit. For that, we will be using got to get the JSON from https://www.reddit.com/r/memes/random/.json .
Install got first:

npm i got --save

Create a file in ./commands and name it meme.js .
Put the following code inside (I will be explaining it later):

const { Command } = require('yuuko');
const got = require('got');
module.exports = new Command('meme', (message) => {
    got('https://www.reddit.com/r/memes/random/.json')
        .then((response) => {
            const [list] = JSON.parse(response.body);
            const [post] = list.data.children;

            const permalink = post.data.permalink;
            const memeUrl = `https://reddit.com${permalink}`;
            const memeImage = post.data.url;
            const memeTitle = post.data.title;
            const memeUpvotes = post.data.ups;
            const memeNumComments = post.data.num_comments;
            message.channel.createMessage({
                embed: {
                    title: memeTitle,
                    url: memeUrl,
                    image: {
                        url: memeImage,
                    },
                    color: 15267908,
                    footer: {
                        text: `👍 ${memeUpvotes} 💬 ${memeNumComments}`,
                    },
                },
            });
        })
        .catch(err => {
            console.error(err);
        });
});

Now start the project by navigating to the root folder of the project and running

node index.js

or if you have nodemon installed

nodemon index.js

Let me break the code up into smaller pieces to explain it.

const { Command } = require('yuuko');
const got = require('got');
module.exports = new Command('meme', (message) => {
  // code here
})

So, we first import the modules as usual, and create a command as we did before. Easy.

got('https://www.reddit.com/r/memes/random/.json').then((response) => {
  // code here
}).catch(err => {
            console.error(err);
});

Now, we use got to get the JSON from reddit (the subreddit r/memes actually), and save the response as the response variable. Note that we are using Promises here, thus the .then().catch() in the code. You can, however, use the async/await in ES6.

Good?

const [list] = JSON.parse(response.body);
const [post] = list.data.children;

Now, we parse the response body by using JSON.parse (Note: You will get an error if you just use JSON.parse(response) ), and get the information about the reddit post which we saved inside the post variable. Understand? Excellent.

const permalink = post.data.permalink;
const memeUrl = `https://reddit.com${permalink}`;
const memeImage = post.data.url;
const memeTitle = post.data.title;
const memeUpvotes = post.data.ups;
const memeNumComments = post.data.num_comments;

Now we save the post url as memeUrl , the meme image url as memeImage , the meme title as memeTitle , the number of meme upvotes as memeUpvotes , and the number of comments as memeNumComments .

message.channel.createMessage({
                embed: {
                    title: memeTitle,
                    url: memeUrl,
                    image: {
                        url: memeImage,
                    },
                    color: 15267908,
                    footer: {
                        text: `👍 ${memeUpvotes} 💬 ${memeNumComments}`,
                    },
                },
});

We then send the embed object. That's the end of it. Easy, right?

결론



이번 포스트에서는 REST API를 사용하여 Eris에서 Embed를 보내는 방법을 배웠습니다. 다음 포스팅에서는 whois 명령어를 작성하겠습니다. 다음 시간까지 만나요!

좋은 웹페이지 즐겨찾기