/[sudobot]/branches/7.x/src/commands/settings/RestartCommand.ts
ViewVC logotype

Contents of /branches/7.x/src/commands/settings/RestartCommand.ts

Parent Directory Parent Directory | Revision Log Revision Log


Revision 577 - (show annotations)
Mon Jul 29 18:52:37 2024 UTC (8 months ago) by rakinar2
File MIME type: application/typescript
File size: 6262 byte(s)
chore: add old version archive branches (2.x to 9.x-dev)
1 /**
2 * This file is part of SudoBot.
3 *
4 * Copyright (C) 2021-2023 OSN Developers.
5 *
6 * SudoBot is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * SudoBot is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
15 *
16 * You should have received a copy of the GNU Affero General Public License
17 * along with SudoBot. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20 import {
21 ActionRowBuilder,
22 ButtonBuilder,
23 ButtonStyle,
24 CacheType,
25 ChatInputCommandInteraction,
26 Interaction,
27 SlashCommandBuilder,
28 Snowflake
29 } from "discord.js";
30 import { writeFile } from "fs/promises";
31 import path from "path";
32 import Command, { AnyCommandContext, CommandMessage, CommandReturn, ValidationRule } from "../../core/Command";
33 import { GatewayEventListener } from "../../decorators/GatewayEventListener";
34 import { HasEventListeners } from "../../types/HasEventListeners";
35 import { logError } from "../../utils/logger";
36 import { sudoPrefix } from "../../utils/utils";
37
38 export default class RestartCommand extends Command implements HasEventListeners {
39 public readonly name = "restart";
40 public readonly validationRules: ValidationRule[] = [];
41 public readonly aliases = ["reboot"];
42 public readonly systemAdminOnly = true;
43 public readonly slashCommandBuilder = new SlashCommandBuilder().addStringOption(option =>
44 option.setName("credential_key").setDescription("The key to authenticate with the credentials server, if needed")
45 );
46
47 public readonly description = "Restarts the bot.";
48
49 @GatewayEventListener("interactionCreate")
50 async onInteractionCreate(interaction: Interaction<CacheType>) {
51 if (!interaction.isButton()) {
52 return;
53 }
54
55 const { customId } = interaction;
56
57 if (!customId.startsWith("restart__yes__") && !customId.startsWith("restart__no__")) {
58 return;
59 }
60
61 const [, , guildId, channelId, userId, ...keyParts] = customId.split("__");
62 const key = keyParts?.join("__") ?? "";
63
64 if (!guildId || !channelId || !userId) {
65 return;
66 }
67
68 if (interaction.guildId !== guildId || interaction.channelId !== channelId) {
69 return;
70 }
71
72 if (interaction.user.id !== userId) {
73 await interaction
74 .reply({
75 ephemeral: true,
76 content: "That's not under your control!"
77 })
78 .catch(logError);
79 return;
80 }
81
82 if (customId.startsWith("restart__yes__")) {
83 const buttons = this.buildButtons(guildId, channelId, userId).map(button => button.setDisabled(true));
84
85 await interaction.update({
86 embeds: [
87 {
88 color: 0x007bff,
89 title: "System Restart",
90 description: `${this.emoji("loading")} Restarting...`
91 }
92 ],
93 components: [new ActionRowBuilder<ButtonBuilder>().addComponents(...buttons)]
94 });
95
96 const json = JSON.stringify(
97 {
98 guildId,
99 channelId,
100 messageId: interaction.message.id,
101 time: Date.now(),
102 key
103 },
104 null,
105 4
106 );
107
108 await writeFile(path.join(sudoPrefix("tmp", true), "restart.json"), json);
109 process.exit(this.client.configManager.systemConfig.restart_exit_code);
110 }
111
112 if (customId.startsWith("restart__no__")) {
113 const buttons = this.buildButtons(guildId, channelId, userId).map(button => button.setDisabled(true));
114
115 await interaction.update({
116 embeds: [
117 {
118 color: 0xf14a60,
119 title: "System Restart",
120 description: `Operation cancelled.`
121 }
122 ],
123 components: [new ActionRowBuilder<ButtonBuilder>().addComponents(...buttons)]
124 });
125 }
126 }
127
128 async execute(message: CommandMessage, context: AnyCommandContext): Promise<CommandReturn> {
129 if (
130 process.env.CREDENTIAL_SERVER &&
131 (!(message instanceof ChatInputCommandInteraction) || !message.options.getString("credential_key"))
132 ) {
133 await this.error(message, "Please enter the credentials server key to restart the bot!");
134 return;
135 }
136
137 return {
138 __reply: true,
139 embeds: [
140 {
141 color: 0x007bff,
142 title: "System Restart",
143 description: "Are you sure you want to restart the entire system? The bot might go offline for some time."
144 }
145 ],
146 components: [
147 new ActionRowBuilder<ButtonBuilder>().addComponents(
148 ...this.buildButtons(
149 message.guildId!,
150 message.channelId!,
151 message.member!.user.id,
152 message instanceof ChatInputCommandInteraction ? message.options.getString("credential_key") : ""
153 )
154 )
155 ]
156 };
157 }
158
159 buildButtons(guildId: Snowflake, channelId: Snowflake, userId: Snowflake, key?: string | null) {
160 return [
161 new ButtonBuilder()
162 .setCustomId(`restart__yes__${guildId}__${channelId}__${userId}__${key}`)
163 .setLabel("Restart")
164 .setStyle(ButtonStyle.Success),
165 new ButtonBuilder()
166 .setCustomId(`restart__no__${guildId}__${channelId}__${userId}__${key}`)
167 .setLabel("Cancel")
168 .setStyle(ButtonStyle.Danger)
169 ];
170 }
171 }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26