From 0952b045ed8c789a09bdfca01e985c40024e0c3f Mon Sep 17 00:00:00 2001
From: Cristiano Pires <cpires@labsxd.com>
Date: Sat, 5 Aug 2023 16:58:07 +0100
Subject: [PATCH] All searches are actual searches now

---
 commands/search/searchAnime.js |   8 +-
 commands/search/searchChar.js  | 100 ++++++++++++++++++-----
 commands/search/searchManga.js |  89 +++++++++++++++++----
 lib.js                         | 140 +++++++++++++++++++++++++++++++--
 4 files changed, 289 insertions(+), 48 deletions(-)

diff --git a/commands/search/searchAnime.js b/commands/search/searchAnime.js
index 283d978..6cbdd7c 100644
--- a/commands/search/searchAnime.js
+++ b/commands/search/searchAnime.js
@@ -27,10 +27,10 @@ class anime extends Command{
                 .setImage(data[0].coverImage)
                 .setTimestamp()  
                 .addFields(
-                    {name:data[0].title.romaji+' ['+data[0].title.english+']', value:'1', inline:true},
-                    {name:data[1].title.romaji+' ['+data[0].title.english+']', value:'2', inline:true},
-                    {name:data[2].title.romaji+' ['+data[0].title.english+']', value:'3', inline:true},
-                    {name:data[3].title.romaji+' ['+data[0].title.english+']', value:'4', inline:true},
+                    {name:data[0].title.romaji+' ['+data[0].title.english+']', value:'1'},
+                    {name:data[1].title.romaji+' ['+data[0].title.english+']', value:'2'},
+                    {name:data[2].title.romaji+' ['+data[0].title.english+']', value:'3'},
+                    {name:data[3].title.romaji+' ['+data[0].title.english+']', value:'4'},
                     );
             var embeds = [embed]
             embeds.push(new EmbedBuilder().setImage(data[1].coverImage).setURL('https://www.rem.wordfights.com'));
diff --git a/commands/search/searchChar.js b/commands/search/searchChar.js
index 6743f1c..fdc7316 100644
--- a/commands/search/searchChar.js
+++ b/commands/search/searchChar.js
@@ -15,34 +15,92 @@ class char extends Command{
         }
         async run(message, args)
         {
+            if(!args[0]) return  new ErrorMessage(this.client).send(ErrorType.Arguments, message)
             const data = await new aniList().searchChar(args.join(' '));
+            if(data=='Error') return new ErrorMessage(this.client).send(ErrorType.Arguments, message, [`Couldn't find any character with the search argument you provided.`])
             const embed = new EmbedBuilder()
-                .setTitle(`${data.name.full} (${data.name.native})`)
+                .setTitle('First 4 results of search:')
                 .setAuthor({name:"Rem-chan", iconURL:"https://i.imgur.com/g6FSNhL.png",url:'https://rem.wordfights.com/addtodiscord'})
                 .setColor(0x003284)
-                .setDescription(data.description)//.split('~! ')[1].replaceAll('<br>', ' ').substring(0, 1500) + "...")
+                .setURL('https://www.rem.wordfights.com')
                 .setFooter({ text: 'Rem-Chan on', iconURL: 'https://i.imgur.com/g6FSNhL.png' })
-                .setImage(data.image)
-                .setThumbnail(data.image)
+                .setImage(data[0].image)
                 .setTimestamp()  
                 .addFields(
-                    {name:'Gender:', value:data.gender, inline:true});
-                const randomID = Random();
-                const row = new ActionRowBuilder()
-                .addComponents(
-                    new ButtonBuilder()
-                        .setCustomId(randomID)
-                        .setLabel('Remove this.')
-                        .setStyle(ButtonStyle.Primary),
-                );
-                const filter = i => i.customId === randomID;
-                await message.channel.send({ephemeral: true, embeds: [embed], components: [row] }); 
-                const collector = message.channel.createMessageComponentCollector({ filter, time: 60000 });
-                collector.on('collect', async m => 
-                {
-                    message.delete();
-                    m.message.delete();
-                });
+                    {name:data[0].name.full+' ['+data[0].name.native+']', value:'1'},
+                    {name:data[1].name.full+' ['+data[0].name.native+']', value:'2'},
+                    {name:data[2].name.full+' ['+data[0].name.native+']', value:'3'},
+                    {name:data[3].name.full+' ['+data[0].name.native+']', value:'4'},
+                    );
+            var embeds = [embed]
+            embeds.push(new EmbedBuilder().setImage(data[1].image).setURL('https://www.rem.wordfights.com'));
+            embeds.push(new EmbedBuilder().setImage(data[2].image).setURL('https://www.rem.wordfights.com'));
+            embeds.push(new EmbedBuilder().setImage(data[3].image).setURL('https://www.rem.wordfights.com'));
+            //${data.title.romaji} (${data.title.native} / ${data.title.english})
+            
+            const randomID = Random();
+            const row = new ActionRowBuilder()
+            .addComponents(
+                new ButtonBuilder()
+                    .setCustomId(randomID+1)
+                    .setLabel('1')
+                    .setStyle(ButtonStyle.Success),
+                new ButtonBuilder()
+                    .setCustomId(randomID+2)
+                    .setLabel('2')
+                    .setStyle(ButtonStyle.Success),
+                new ButtonBuilder()
+                    .setCustomId(randomID+3)
+                    .setLabel('3')
+                    .setStyle(ButtonStyle.Success),
+                new ButtonBuilder()
+                    .setCustomId(randomID+4)
+                    .setLabel('4')
+                    .setStyle(ButtonStyle.Success),
+
+            );
+            const filter = i => i.customId.slice(0,-1) === randomID;
+            await message.channel.send({ephemeral: true, embeds, components: [row] }); 
+            const collector = message.channel.createMessageComponentCollector({ filter, time: 60000 });
+            collector.on('collect', async m => 
+            {
+                message.delete();
+                m.message.delete();
+                sendMessage(data[m.customId[m.customId.length-1]-1].id);
+            });
+            /**
+             * @param {Number} id  
+             */
+            async function sendMessage(id)
+            {
+                const data = await new aniList().getCharInfo(id);
+                const embed = new EmbedBuilder()
+                    .setTitle(`${data.name.full} (${data.name.native})`)
+                    .setAuthor({name:"Rem-chan", iconURL:"https://i.imgur.com/g6FSNhL.png",url:'https://rem.wordfights.com/addtodiscord'})
+                    .setColor(0x003284)
+                    .setDescription(data.description)//.split('~! ')[1].replaceAll('<br>', ' ').substring(0, 1500) + "...")
+                    .setFooter({ text: 'Rem-Chan on', iconURL: 'https://i.imgur.com/g6FSNhL.png' })
+                    .setImage(data.image)
+                    .setThumbnail(data.image)
+                    .setTimestamp()  
+                    .addFields(
+                        {name:'Gender:', value:data.gender, inline:true});
+                    const randomID = Random();
+                    const row = new ActionRowBuilder()
+                    .addComponents(
+                        new ButtonBuilder()
+                            .setCustomId(randomID)
+                            .setLabel('Remove this.')
+                            .setStyle(ButtonStyle.Primary),
+                    );
+                    const filter = i => i.customId === randomID;
+                    await message.channel.send({ephemeral: true, embeds: [embed], components: [row] }); 
+                    const collector = message.channel.createMessageComponentCollector({ filter, time: 60000 });
+                    collector.on('collect', async m => 
+                    {
+                        m.message.delete();
+                    });
+            }
         }
       
 
diff --git a/commands/search/searchManga.js b/commands/search/searchManga.js
index e949a76..e02e858 100644
--- a/commands/search/searchManga.js
+++ b/commands/search/searchManga.js
@@ -15,31 +15,88 @@ class manga extends Command{
     }
     async run(message, args)
     {
-        const data = await new aniList().searchManga(args.join(' '));
-        const embed = new EmbedBuilder()
-            .setTitle(`${data.title.romaji} (${data.title.native} / ${data.title.english})`)
-            .setAuthor({name:"Rem-chan", iconURL:"https://i.imgur.com/g6FSNhL.png",url:'https://rem.wordfights.com/addtodiscord'})
-            .setColor(0x003284)
-            .setDescription(data.description)//.replaceAll('<br>', ' ').substring(0, 1500) + "...")
-            .setFooter({ text: 'Rem-Chan on', iconURL: 'https://i.imgur.com/g6FSNhL.png' })
-            .setImage(data.coverImage)
-            .setThumbnail(data.coverImage)
-            .setTimestamp()  
+        if(!args[0]) return  new ErrorMessage(this.client).send(ErrorType.Arguments, message)
+            const data = await new aniList().searchManga(args.join(' '));
+            if(data=='Error') return new ErrorMessage(this.client).send(ErrorType.Arguments, message, [`Couldn't find any character with the search argument you provided.`])
+            const embed = new EmbedBuilder()
+                .setTitle('First 4 results of search:')
+                .setAuthor({name:"Rem-chan", iconURL:"https://i.imgur.com/g6FSNhL.png",url:'https://rem.wordfights.com/addtodiscord'})
+                .setColor(0x003284)
+                .setURL('https://www.rem.wordfights.com')
+                .setFooter({ text: 'Rem-Chan on', iconURL: 'https://i.imgur.com/g6FSNhL.png' })
+                .setImage(data[0].image)
+                .setTimestamp()  
+                .addFields(
+                    {name:data[0].title.romaji+(data[0].title.english?"("+data.title.english+")":''), value:'1'},
+                    {name:data[1].title.romaji+(data[1].title.english?"("+data.title.english+")":''), value:'2'},
+                    {name:data[2].title.romaji+(data[2].title.english?"("+data.title.english+")":''), value:'3'},
+                    {name:data[3].title.romaji+(data[3].title.english?"("+data.title.english+")":''), value:'4'},
+                    );
+            var embeds = [embed]
+            embeds.push(new EmbedBuilder().setImage(data[1].image).setURL('https://www.rem.wordfights.com'));
+            embeds.push(new EmbedBuilder().setImage(data[2].image).setURL('https://www.rem.wordfights.com'));
+            embeds.push(new EmbedBuilder().setImage(data[3].image).setURL('https://www.rem.wordfights.com'));
+
             const randomID = Random();
             const row = new ActionRowBuilder()
             .addComponents(
                 new ButtonBuilder()
-                    .setCustomId(randomID)
-                    .setLabel('Remove this.')
-                    .setStyle(ButtonStyle.Primary),
+                    .setCustomId(randomID+1)
+                    .setLabel('1')
+                    .setStyle(ButtonStyle.Success),
+                new ButtonBuilder()
+                    .setCustomId(randomID+2)
+                    .setLabel('2')
+                    .setStyle(ButtonStyle.Success),
+                new ButtonBuilder()
+                    .setCustomId(randomID+3)
+                    .setLabel('3')
+                    .setStyle(ButtonStyle.Success),
+                new ButtonBuilder()
+                    .setCustomId(randomID+4)
+                    .setLabel('4')
+                    .setStyle(ButtonStyle.Success),
+
             );
-            const filter = i => i.customId === randomID;
-            await message.channel.send({ephemeral: true, embeds: [embed], components: [row] }); 
+            const filter = i => i.customId.slice(0,-1) === randomID;
+            await message.channel.send({ephemeral: true, embeds, components: [row] }); 
             const collector = message.channel.createMessageComponentCollector({ filter, time: 60000 });
             collector.on('collect', async m => 
             {
                 message.delete();
                 m.message.delete();
-            });   
+                sendMessage(data[m.customId[m.customId.length-1]-1].id);
+            });
+            /**
+             * @param {Number} id  
+             */
+            async function sendMessage(id)
+            {
+                const data = await new aniList().getMangaInfo(id);
+                const embed = new EmbedBuilder()
+                    .setTitle(`${data.title.romaji} (${data.title.native} / ${data.title.english})`)
+                    .setAuthor({name:"Rem-chan", iconURL:"https://i.imgur.com/g6FSNhL.png",url:'https://rem.wordfights.com/addtodiscord'})
+                    .setColor(0x003284)
+                    .setDescription(data.description)//.replaceAll('<br>', ' ').substring(0, 1500) + "...")
+                    .setFooter({ text: 'Rem-Chan on', iconURL: 'https://i.imgur.com/g6FSNhL.png' })
+                    .setImage(data.coverImage)
+                    .setThumbnail(data.coverImage)
+                    .setTimestamp()  
+                    const randomID = Random();
+                    const row = new ActionRowBuilder()
+                    .addComponents(
+                        new ButtonBuilder()
+                            .setCustomId(randomID)
+                            .setLabel('Remove this.')
+                            .setStyle(ButtonStyle.Primary),
+                    );
+                    const filter = i => i.customId === randomID;
+                    await message.channel.send({ephemeral: true, embeds: [embed], components: [row] }); 
+                    const collector = message.channel.createMessageComponentCollector({ filter, time: 60000 });
+                    collector.on('collect', async m => 
+                    {
+                        m.message.delete();
+                    }); 
+            }
     }
 }module.exports = manga;
diff --git a/lib.js b/lib.js
index 9a5d9e5..3bf3373 100644
--- a/lib.js
+++ b/lib.js
@@ -574,13 +574,78 @@ class aniListCli {
      * @returns {CharInfo}
      */
     async searchChar(ss)
+    {
+        var variables = {
+            ss,
+            "page": 0,
+            "perPage": 4
+        };
+        var query = `query ($ss: String, $page: Int, $perPage: Int) {
+            Page(page: $page, perPage: $perPage) {
+              characters(search: $ss, sort: SEARCH_MATCH) {
+                id
+                name {
+                  full
+                  native
+                }
+                gender
+                image {
+                  medium
+                }
+              }
+            }
+          }
+          `;
+        var url = 'https://graphql.anilist.co',
+        options = {
+            method: 'POST',
+            headers: {
+                'Content-Type': 'application/json',
+                'Accept': 'application/json',
+            },
+            body: JSON.stringify({
+                query,
+                variables
+            })
+        };
+        return await fetch(url, options).then(handleResponse)
+                   .then(handleData)
+                   .catch(handleError);
+        function handleResponse(response) 
+        {
+            return response.json().then(function (json) 
+            {
+                return response.ok ? json : Promise.reject(json);
+            });
+        }
+        function handleError(error) {
+            return error;
+        }
+        function handleData(data) {
+            var chars = data.data.Page.characters
+            var aux = [];
+            if(!chars[0]) return 'Error'
+            for(var char of chars)
+            {
+                aux.push({
+                    id:char.id,
+                    name:char.name,
+                    gender:char.gender,
+                    image:char.image.medium
+                })
+            }
+            return aux;
+        }
+        
+    }
+    async getCharInfo(id)
     {
         
         var variables = {
-            ss
+            id
         };
-        var query = `query ($ss: String) {
-            Character(search: $ss, sort:SEARCH_MATCH) {
+        var query = `query ($id: Int) {
+            Character(id: $id, ) {
               id
               name {
                 full
@@ -636,12 +701,73 @@ class aniListCli {
      */
     async searchManga(ss)
     {
-        
+        var variables = 
+        {
+            ss,
+            "page": 0,
+            "perPage": 4
+        }
+        var query = `query ($ss: String, $page: Int, $perPage: Int) {
+            Page(page: $page, perPage: $perPage) {
+              media(search: $ss, type: MANGA) {
+                id
+                title {
+                  romaji
+                  english
+                }
+                coverImage {
+                  medium
+                }
+              }
+            }
+          }`
+        var url = 'https://graphql.anilist.co',
+        options = {
+            method: 'POST',
+            headers: {
+                'Content-Type': 'application/json',
+                'Accept': 'application/json',
+            },
+            body: JSON.stringify({
+                query,
+                variables
+            })
+        };
+        return await fetch(url, options).then(handleResponse)
+                    .then(handleData)
+                    .catch(handleError);
+        function handleResponse(response) 
+        {
+            return response.json().then(function (json) 
+            {
+                return response.ok ? json : Promise.reject(json);
+            });
+        }
+        function handleError(error) {
+            return error;
+        }
+        function handleData(data) {
+            var mangas = data.data.Page.media;
+            var aux = [];
+            if(!mangas[0]) return 'Error'
+            for(var manga of mangas)
+            {
+                aux.push({
+                    id:manga.id,
+                    title:manga.title,
+                    image:manga.coverImage.medium
+                })
+            }
+            return aux;
+        }
+    }   
+    async getMangaInfo(id)
+    {  
         var variables = {
-            ss
+            id
         };
-        var query = `query ($ss: String) {
-            Media(search: $ss, type: MANGA) {
+        var query = `query ($id: Int) {
+            Media(id: $id) {
               title {
                 romaji
                 english