/[sudobot]/trunk/setup.js
ViewVC logotype

Diff of /trunk/setup.js

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 442 by rakin, Mon Jul 29 17:30:15 2024 UTC revision 462 by rakin, Mon Jul 29 17:30:21 2024 UTC
# Line 24  Line 24 
24  const path = require('path');  const path = require('path');
25  const fs = require('fs/promises');  const fs = require('fs/promises');
26  const readline = require('readline');  const readline = require('readline');
27    const bcrypt = require('bcrypt');
28    
29  const CONFIG_DIR = path.resolve(__dirname, 'config');  const CONFIG_DIR = path.resolve(__dirname, 'config');
30  const { version } = require('./package.json');  const { version } = require('./package.json');
31    const { existsSync } = require('fs');
32  const SAMPLE_CONFIG_PATH = path.resolve(CONFIG_DIR, 'sample-config.json');  const SAMPLE_CONFIG_PATH = path.resolve(CONFIG_DIR, 'sample-config.json');
33    const CONFIG_PATH = path.resolve(CONFIG_DIR, 'config.json');
 let prefix = '-', homeGuild = '';  
34    
35  const isSnowflake = text => /^\d+$/.test(text);  const isSnowflake = text => /^\d+$/.test(text);
36    
# Line 56  const promptLoop = async (text, validato Line 57  const promptLoop = async (text, validato
57          fn = prompt;          fn = prompt;
58      }      }
59    
60      const input = await fn(text);      const input = await fn(text, defaultValue);
61    
62      if (!(await validator(input ?? ''))) {      if (!(await validator(input ?? ''))) {
63          return promptLoop(text, validator, defaultValue);          return promptLoop(text, validator, defaultValue);
# Line 78  const snowflakeValidator = input => { Line 79  const snowflakeValidator = input => {
79      console.log(`SudoBot version ${version}`);      console.log(`SudoBot version ${version}`);
80      console.log(`Copyright (C) OSN Inc 2022`);      console.log(`Copyright (C) OSN Inc 2022`);
81      console.log(`Thanks for using SudoBot! We'll much appreciate if you star the repository on GitHub.\n`);      console.log(`Thanks for using SudoBot! We'll much appreciate if you star the repository on GitHub.\n`);
82    
83        let prefix = '-', homeGuild = '', owners = [];
84        let config = Object.entries(JSON.parse((await fs.readFile(SAMPLE_CONFIG_PATH)).toString()));
85            
86      prefix = (await promptLoop(`What will be the bot prefix? [${prefix}]: `, input => {      config[1][1].prefix = (await promptLoop(`What will be the bot prefix? [${prefix}]: `, input => {
87          if (input.trim().includes(' ')) {          if (input.trim().includes(' ')) {
88              console.log(`Prefixes must not contain spaces!`);              console.log(`Prefixes must not contain spaces!`);
89              return false;              return false;
90          }          }
91    
92          return true;          return true;
93      }, prefix)).trim();      }, "-")).trim();
94    
95      homeGuild = await promptLoop(`What will be the Home/Support Guild ID?: `, snowflakeValidator);      homeGuild = await promptLoop(`What will be the Home/Support Guild ID?: `, snowflakeValidator);
96        config[1][0] = homeGuild;
97    
98      rl.close();      config = Object.fromEntries(config);
99    
100        config.global.id = homeGuild;
101        config.global.owners = (await promptLoop(`Who will be the owner? Specify the owner user IDs separated with comma (,): `, input => {
102            const splitted = input.split(',');
103    
104            for (const snowflake of splitted) {
105                if (!snowflakeValidator(snowflake)) {
106                    console.log(`Invalid snowflake given! Make sure that the IDs are correctly given!`);
107                    return false;
108                }
109            }
110    
111            return true;
112        })).split(',').map(s => s.trim());
113    
114        // config[1][0] = homeGuild;
115        // config[1][1].prefix = prefix;
116    
117        // config.global.owners = owners;
118    
119        const guildConfig = {...config[homeGuild]};
120    
121        guildConfig.mod_role = await promptLoop(`What will be the moderator role ID?: `, snowflakeValidator);
122        guildConfig.admin = await promptLoop(`What will be the safe role ID?: `, snowflakeValidator);
123        guildConfig.mute_role = await promptLoop(`What will be the muted role ID?: `, snowflakeValidator);
124        guildConfig.gen_role = await promptLoop(`What will be the general role ID? [${homeGuild}]: `, snowflakeValidator, homeGuild);
125        guildConfig.logging_channel = await promptLoop(`What will be the main logging channel ID?: `, snowflakeValidator);
126        guildConfig.logging_channel_join_leave = await promptLoop(`What will be the join/leave logging channel ID?: `, snowflakeValidator);
127    
128        config[homeGuild] = guildConfig;
129    
130        console.log(config);
131    
132        if (existsSync(CONFIG_PATH)) {
133            const input = await promptDefault("The config file (config/config.json) already exists. Do you want to overwrite the file? [y/N]: ", "n");
134    
135            if (input.trim().toLowerCase() !== "y" && input.trim().toLowerCase() !== "yes") {
136                console.log("Aborting setup.");
137                rl.close();
138                process.exit(1);
139            }
140        }
141    
142        if (existsSync(CONFIG_PATH))
143            await fs.rename(CONFIG_PATH, path.join(CONFIG_DIR, 'config-old-' + Math.round(Math.random() * 100000) + '.json'));
144    
145        await fs.writeFile(CONFIG_PATH, JSON.stringify(config, undefined, ' '));
146    
147      console.log("Setup complete!");      console.log("Config File Created!");
148      console.table([      console.table([
149          {          {
150              prefix,              prefix,
151              homeGuild              homeGuild
152          }          }
153      ]);      ]);
154    
155        if (!existsSync(path.join(__dirname, ".env"))) {
156            const input = (await promptDefault("Generate a `.env' file? [y/N]: ", "n")).toLowerCase();
157    
158            if (input !== 'yes' && input !== 'y') {
159                return;
160            }
161    
162            const token = await promptLoop("What's your bot token? ", input => {
163                if (input.trim() !== '' && input.indexOf(' ') === -1) {
164                    return true;
165                }
166    
167                console.log("That's not a valid token.");
168                return false;
169            });
170    
171            const clientID = await promptLoop("What's your bot's client ID? ", snowflakeValidator);
172    
173            const mongoURI = await promptLoop("Enter the MongoDB URI for the bot to connect: ", input => {
174                if (input.trim() !== '' && input.indexOf(' ') === -1) {
175                    return true;
176                }
177    
178                console.log("That's not a valid MongoDB URI.");
179                return false;
180            });
181    
182            const jwtSecret = (await promptLoop("Enter a JWT secret key (hit enter to generate automatically): ", input => {
183                if (input.trim() !== '') {
184                    return true;
185                }
186    
187                console.log("That's not a valid secret.");
188                return false;
189            }, null)) ?? bcrypt.hashSync(Math.random() + '', bcrypt.genSaltSync());
190    
191            const webhook = await promptLoop("Enter a webhook URL for sending debug logs: ", input => {
192                if (input.trim() !== '' && input.indexOf(' ') === -1) {
193                    return true;
194                }
195    
196                console.log("That's not a valid webhook URL.");
197                return false;
198            });
199    
200            await fs.writeFile(path.join(__dirname, ".env"), `# Environment Configuration
201            
202            TOKEN=${token}
203            ENV=dev
204            CLIENT_ID=${clientID}
205            GUILD_ID=${homeGuild}
206            MONGO_URI=${mongoURI}
207            JWT_SECRET=${jwtSecret}
208            DEBUG_WEBHOOK_URL=${webhook}
209            `);
210        }
211    
212        rl.close();
213  })().catch(console.error);  })().catch(console.error);

Legend:
Removed from v.442  
changed lines
  Added in v.462

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26