File size: 4,830 Bytes
72ee6f0
0ee7b04
 
72ee6f0
0ee7b04
72ee6f0
 
 
 
 
 
 
 
 
0ee7b04
 
 
 
 
72ee6f0
0ee7b04
 
 
72ee6f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ee7b04
72ee6f0
 
0ee7b04
 
 
 
 
 
 
 
72ee6f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ee7b04
 
 
72ee6f0
0ee7b04
72ee6f0
 
0ee7b04
72ee6f0
 
 
 
 
 
 
0ee7b04
72ee6f0
 
 
 
 
0ee7b04
 
 
 
72ee6f0
 
 
0ee7b04
 
 
72ee6f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ee7b04
 
 
 
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
// command-handler.js
import fs from "fs";
import path from "path";
import { pathToFileURL } from "url";

/**

 * Load semua command dari folder (rekursif)

 * Struktur file command:

 * export default {

 *   command: ["ping", "p"],

 *   description: "...",

 *   run: async (m, { conn }) => {}

 * }

 */
export async function loadCommands(dir) {
  const commands = new Map();

  async function loadDir(folder) {
    const files = fs.readdirSync(folder);

    for (const file of files) {
      const full = path.join(folder, file);
      const stat = fs.statSync(full);

      if (stat.isDirectory()) {
        // masuk folder lagi (rekursif)
        await loadDir(full);
        continue;
      }

      if (!file.endsWith(".js")) continue;

      try {
        const fileUrl = pathToFileURL(full).href;
        const cmdModule = (await import(fileUrl)).default;

        if (!cmdModule || !cmdModule.command) continue;

        const aliases = Array.isArray(cmdModule.command)
          ? cmdModule.command
          : [cmdModule.command];

        for (const alias of aliases) {
          const key = String(alias).toLowerCase();
          commands.set(key, cmdModule);
        }
      } catch (err) {
        console.error(`❌ Gagal load command: ${full}`, err);
      }
    }
  }

  await loadDir(dir);
  return commands;
}

/**

 * Helper untuk ambil teks utama dari message

 */
function getMessageText(msg) {
  return (
    msg.message?.conversation ||
    msg.message?.extendedTextMessage?.text ||
    msg.message?.imageMessage?.caption ||
    msg.message?.videoMessage?.caption ||
    msg.message?.buttonsResponseMessage?.selectedButtonId ||
    msg.message?.listResponseMessage?.singleSelectReply?.selectedRowId ||
    ""
  );
}

/**

 * Handler utama command

 * - parsing prefix, command, args

 * - bikin wrapper "m" dengan m.reply, m.send, dll

 * - jalanin plugin.run(...)

 */
export async function handleCommand(sock, msg, commands) {
  try {
    const from = msg.key.remoteJid;
    const isGroup = from.endsWith("@g.us");
    const sender = msg.key.participant || msg.key.remoteJid;

    const body = getMessageText(msg);
    if (!body) return;

    // global.prefix bisa string / regex
    const prefixMatch =
      typeof global.prefix === "string"
        ? body.startsWith(global.prefix)
          ? [global.prefix]
          : null
        : body.match(global.prefix);

    if (!prefixMatch) return; // bukan command

    const prefix = prefixMatch[0];

    const [rawCmd, ...args] = body
      .slice(prefix.length)
      .trim()
      .split(/\s+/);

    if (!rawCmd) return;

    const command = rawCmd.toLowerCase();
    const plugin = commands.get(command);
    if (!plugin) return;

    // Data tambahan
    const quoted =
      msg.message?.extendedTextMessage?.contextInfo?.quotedMessage || null;
    const mentionedJid =
      msg.message?.extendedTextMessage?.contextInfo?.mentionedJid || [];

    // =========================================
    //  Wrapper "m" untuk dikirim ke plugin
    // =========================================
    const m = {
      ...msg,
      from,
      sender,
      isGroup,
      body,
      text: body,
      args,
      prefix,
      command,
      quoted,
      mentionedJid,

      /**

       * Reply text sederhana

       * @param {string} text

       * @param {object} options - opsi tambahan sendMessage

       */
      reply: async (text, options = {}) => {
        return sock.sendMessage(
          from,
          { text: String(text) },
          { quoted: msg, ...options }
        );
      },

      /**

       * Kirim pesan custom / media

       * contoh:

       *   m.send({ image: buffer, caption: "hai" })

       */
      send: async (content, options = {}) => {
        return sock.sendMessage(from, content, { quoted: msg, ...options });
      },

      /**

       * React ke pesan

       * @param {string} emoji

       */
      react: async (emoji) => {
        try {
          return sock.sendMessage(from, {
            react: { text: emoji, key: msg.key },
          });
        } catch (err) {
          console.error("❌ Gagal react:", err);
        }
      },

      /**

       * Reply error dengan format rapi

       */
      error: async (err) => {
        console.error("❌ Plugin error:", err);
        const message =
          typeof err === "string" ? err : err?.message || "Terjadi kesalahan";
        return m.reply("⚠️ Error: " + message);
      },
    };
    // =========================================

    // Jalankan plugin
    await plugin.run(m, { conn: sock, sock });
  } catch (e) {
    console.error("❌ Error handleCommand:", e);
  }
}