summaryrefslogtreecommitdiff
path: root/packages/gateway/src/commands/deleteWebhook.ts
blob: 92fc89c6dbecd68a47aa4026904377522a6176a9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { Message } from "discord.js";
import { logUnexpectedDiscordAPIError, replyWithCleanup } from "../utilities";

export const handleDeleteWebhookCommand = async (
  message: Message,
): Promise<boolean> => {
  if (message.author.bot) return false;

  const application = await message.client.application?.fetch();
  const ownerId = application?.owner?.id;

  if (message.author.id !== ownerId) return false;

  const content = message.content.trim();
  const commandMatch = content.match(/^uma!delwh\s+(\d+)\s*,\s*(.+)$/s);

  if (!commandMatch) return false;

  const [, channelId, webhookName] = commandMatch;

  if (!webhookName.trim()) {
    await replyWithCleanup(
      message,
      "❌ You need to provide a webhook name to delete.",
    );

    return true;
  }

  try {
    const channel = await message.client.channels.fetch(channelId);

    if (!channel || !channel.isTextBased() || channel.isDMBased()) {
      await replyWithCleanup(
        message,
        "❌ Channel not found or is not a text channel.",
      );

      return true;
    }

    if (!("fetchWebhooks" in channel)) {
      await replyWithCleanup(
        message,
        "❌ This channel does not support webhooks.",
      );

      return true;
    }

    const webhooks = await channel.fetchWebhooks();
    const targetWebhook = webhooks.find(
      (webhook) => webhook.name === webhookName.trim(),
    );

    if (!targetWebhook) {
      await replyWithCleanup(
        message,
        `❌ No webhook found with name "${webhookName.trim()}" in <#${channelId}>.`,
      );

      return true;
    }

    await targetWebhook.delete();
    await replyWithCleanup(
      message,
      `✅ Successfully deleted webhook "${webhookName.trim()}" from <#${channelId}>.`,
    );

    return true;
  } catch (error) {
    logUnexpectedDiscordAPIError(error);
    await replyWithCleanup(
      message,
      "❌ Failed to delete webhook. Make sure I have permission to manage webhooks.",
    );

    return true;
  }
};