/[sudobot]/trunk/commands/cat.js
ViewVC logotype

Contents of /trunk/commands/cat.js

Parent Directory Parent Directory | Revision Log Revision Log


Revision 10 - (show annotations)
Mon Jul 29 17:28:12 2024 UTC (8 months, 1 week ago) by rakin
File MIME type: text/javascript
File size: 3731 byte(s)
Added new features
1 const MessageEmbed = require("../src/MessageEmbed");
2 const Axios = require('axios');
3 const { default: axios } = Axios;
4 const fs = require('fs');
5 const { Attachment } = require('discord.js');
6 const path = require("path");
7
8 module.exports = {
9 async download(url, path) {
10 const writer = fs.createWriteStream(path);
11
12 const response = await Axios({
13 url,
14 method: 'GET',
15 responseType: 'stream',
16 headers: {
17 "x-api-key": process.env.CAT_API_TOKEN
18 }
19 });
20
21 response.data.pipe(writer);
22
23 if (response.status !== 200) {
24 reject();
25 }
26
27 return new Promise((resolve, reject) => {
28 writer.on('finish', resolve);
29 writer.on('error', reject);
30 });
31 },
32 async delete(path) {
33 fs.rm(path, err => {
34 if (err) {
35 throw new Error(err);
36 }
37 });
38 },
39 async handle(msg, cm) {
40 axios.get("https://api.thecatapi.com/v1/images/search", {
41 headers: {
42 "x-api-key": process.env.CAT_API_TOKEN
43 }
44 })
45 .then(res => {
46 if (res && res.status === 200) {
47 let name = res.data[0].url;
48 const pos = name.indexOf('?');
49
50 if (pos !== -1) {
51 name = name.substring(0, pos);
52 }
53
54 name = name.split(/\/+/);
55 name = name[name.length - 1];
56
57 console.log(name);
58 const filename = path.join(__dirname, '..', 'tmp', name);
59
60 if (filename.endsWith('.false')) {
61 filename = filename.replace(/\.false$/, '.png');
62 }
63
64 this.download(res.data[0].url, filename)
65 .then(() => {
66 msg.reply({
67 files: [
68 {
69 attachment: filename,
70 name
71 }
72 ]
73 });
74
75 this.delete(filename);
76 })
77 .catch(err => {
78 console.log("DL error: " + err.message);
79
80 this.delete(filename);
81
82 msg.reply({
83 embeds: [
84 new MessageEmbed()
85 .setColor('#f14a60')
86 .setDescription('Internal API error occured (download-time error), please try again.')
87 ]
88 });
89 });
90 }
91 else if (res?.status === 429) {
92 msg.reply({
93 embeds: [
94 new MessageEmbed()
95 .setColor('#f14a60')
96 .setDescription('Too many requests at the same time, please try again after some time.')
97 ]
98 });
99 }
100 else {
101 msg.reply({
102 embeds: [
103 new MessageEmbed()
104 .setColor('#f14a60')
105 .setDescription('Internal API error occured (pre-download time error), please try again.')
106 ]
107 });
108 }
109 })
110 .catch(err => {
111 msg.reply({
112 embeds: [
113 new MessageEmbed()
114 .setColor('#f14a60')
115 .setDescription('Too many requests at the same time, please try again after some time.')
116 ]
117 });
118 });
119 }
120 };

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26