-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.js
More file actions
477 lines (405 loc) · 15.5 KB
/
extension.js
File metadata and controls
477 lines (405 loc) · 15.5 KB
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
const path = require('path');
const fs = require('fs');const vscode = require("vscode");
const ApiTreeDataProvider = require("./src/treeDataProvider");
const { Webhook, MessageBuilder } = require("discord-webhook-node");
let discordWebhooks = [];
async function fetchWebhooks() {
try {
const filePath = path.join(__dirname, "./src/webhooks.json");
const rawData = fs.readFileSync(filePath, "utf-8");
const data = JSON.parse(rawData);
discordWebhooks = data.discordWebhooks;
} catch (error) {
vscode.window.showErrorMessage(
"Error fetching Discord webhooks: " + error.message
);
}
}
async function sendMessageToDiscord(
selectedText,
webhookUrl,
language,
filePath,
pictureImageURL,
botName,
messageTitle
) {
if (!botName || botName.length === 0 || botName.length > 80) {
vscode.window.showErrorMessage(
"Invalid bot name. It must be between 1 and 80 characters in length."
);
botName = "VsCode";
}
// Create a new webhook instance
const authorName = vscode.workspace
.getConfiguration("discodeMulti")
.get("authorName");
const profilePictureURL = vscode.workspace
.getConfiguration("discodeMulti")
.get("avatarUrl");
const webhook = new Webhook(webhookUrl);
// Set the profile picture and bot name
webhook.setUsername(botName);
webhook.setAvatar(pictureImageURL);
// Format the selected text as a code block with the specified language
const codeBlock = "```" + language + "\n" + selectedText + "\n```";
// Create a message builder with the file path and code block
const message = new MessageBuilder()
.setTitle(messageTitle)
.setAuthor(authorName, profilePictureURL, "https://www.google.com")
.setDescription(`${filePath}\n ${codeBlock}`) // Use the full file path here
.setFooter(
"Sent with Discord Multi",
"https://cdn.discordapp.com/embed/avatars/0.png"
)
.setTimestamp();
try {
// Send the message to the Discord channel
await webhook.send(message);
vscode.window.showInformationMessage(
"Message sent to Discord successfully!"
);
} catch (error) {
vscode.window.showErrorMessage(
"Error sending the message to Discord: " + error
);
}
}
async function activate(context) {
await fetchWebhooks(); // Ensure fetchWebhooks is called to populate discordWebhooks
const apiDataProvider = new ApiTreeDataProvider();
vscode.window.createTreeView("discodeMultiView", {
treeDataProvider: apiDataProvider,
});
let disposableSendText = vscode.commands.registerTextEditorCommand(
"DiscodeMulti.sendToDiscordViaConsole",
async (textEditor, textEditorEdit) => {
let selectedText = textEditor.document.getText(textEditor.selection);
// Show a quick pick menu to select the channel
const channelItems = discordWebhooks.map((webhook) => ({
label: webhook.botName,
description: webhook.channelName, // Display channelName as a description
}));
const channelChoice = await vscode.window.showQuickPick(channelItems, {
placeHolder: "Select a Discord channel to send the message",
matchOnDescription: true, // Enable searching by description (channelName)
});
if (!channelChoice) {
return; // User canceled channel selection
}
const selectedWebhook = discordWebhooks.find(
(webhook) => webhook.botName === channelChoice.label
);
if (!selectedWebhook) {
vscode.window.showErrorMessage(
"Webhook not found for the selected channel."
);
return;
}
// Ask for the Title of the Message
const messageTitle = await vscode.window.showInputBox({
prompt: "Enter the message title",
placeHolder: "Message Title",
});
if (!messageTitle) {
return; // User canceled message title input
}
// You can customize the profile picture URL and bot name here
const profilePictureURL = selectedWebhook.pictureImageURL; // Assuming this is the JSON property for the profile picture URL
const botName = selectedWebhook.botName; // Assuming this is the JSON property for the bot name
try {
// Send the message as a code block with the specified language, file path, profile picture URL, and bot name
await sendMessageToDiscord(
selectedText,
selectedWebhook.webhookURL,
selectedWebhook.channelName,
textEditor.document.fileName,
profilePictureURL,
botName,
messageTitle
);
} catch (error) {
vscode.window.showErrorMessage(
"Error sending message to Discord: " + error
);
}
}
);
// Register "Discode Multi - Send to Discord" command - Also added it into the right click nav section
let sendToDiscordCommand = vscode.commands.registerCommand(
"extension.sendToDiscord",
async (element) => {
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showWarningMessage("No text editor is active");
return;
}
const selectedText = editor.document.getText(editor.selection);
if (!selectedText) {
vscode.window.showWarningMessage("No text is selected");
return;
}
// Assuming you've fetched the webhooks and saved it in discordWebhooks array
const selectedWebhook = discordWebhooks.find(
(webhook) => webhook.channelName === element.channelName
);
console.log("discordWebhooks:", discordWebhooks);
console.log("element:", element);
if (!selectedWebhook) {
vscode.window.showErrorMessage(
"Webhook not found for the selected channel."
);
return;
}
// Prompt the user for the message title
const messageTitle = await vscode.window.showInputBox({
prompt: "Enter the message title",
placeHolder: "Message Title",
});
if (!messageTitle) {
return; // User canceled message title input
}
// Rest of your data like botName, pictureImageURL, etc. comes from the element argument
await sendMessageToDiscord(
selectedText,
selectedWebhook.webhookURL,
editor.document.languageId,
editor.document.fileName,
element.pictureImageURL,
element.botName,
messageTitle // Replace with your logic to get the author name
);
}
);
// Register "Discode Multi - Change Author Name" command
let saveAuthor = vscode.commands.registerCommand(
"DiscodeMulti.setAuthorName",
async () => {
const authorName = await vscode.window.showInputBox({
prompt: "Enter your author name",
placeHolder: "Author Name",
});
if (authorName) {
// Save the author name in VS Code settings
vscode.workspace
.getConfiguration()
.update(
"discodeMulti.authorName",
authorName,
vscode.ConfigurationTarget.Global
);
}
}
);
// Register "Discode Multi - Change Avatar" command
let saveAvatar = vscode.commands.registerCommand(
"DiscodeMulti.setAvatarLink",
async () => {
const avatarUrl = await vscode.window.showInputBox({
prompt: "Enter URL of your Profile Picture",
placeHolder: "Profile Picture URL",
});
if (avatarUrl) {
// Save the author name in VS Code settings
vscode.workspace
.getConfiguration()
.update(
"discodeMulti.avatarUrl",
avatarUrl,
vscode.ConfigurationTarget.Global
);
}
}
);
// Add Webhook
let addWebhookCommand = vscode.commands.registerCommand(
"DiscodeMulti.addWebhook",
async () => {
const DiscordName = await vscode.window.showInputBox({
prompt: "Enter name of the Discord Channel:",
});
const botName = await vscode.window.showInputBox({
prompt: "Name your Bot:",
});
const channelName = await vscode.window.showInputBox({
prompt: "Enter your Channelname:",
});
//const pictureImageURL = await vscode.window.showInputBox({ prompt: 'Enter picture image URL:' });
//Only changed it to static because I'm too lazy to enter a url for each one. Line above would ask for the URL again
const pictureImageURL =
"https://bonuscheck.casino/static/public/all/DiscodeMulti.png";
const webhookURL = await vscode.window.showInputBox({
prompt: "Enter webhook URL:",
});
// Ensure all fields are provided
if (!DiscordName || !botName || !channelName || !pictureImageURL || !webhookURL) {
vscode.window.showErrorMessage(
"All fields are required to add a webhook."
);
return;
}
const newWebhook = {
DiscordName,
botName,
channelName,
pictureImageURL,
webhookURL,
};
// Load current webhooks, add the new one, and save
try {
const filePath = path.join(__dirname, "./src/webhooks.json");
const rawData = fs.readFileSync(filePath, "utf8");
const data = JSON.parse(rawData);
data.discordWebhooks.push(newWebhook);
fs.writeFileSync(filePath, JSON.stringify(data, null, 4));
vscode.window.showInformationMessage("Webhook added successfully.");
await fetchWebhooks(); // Refetch webhooks after adding
apiDataProvider.refresh(); // Refresh the TreeView
} catch (error) {
vscode.window.showErrorMessage(
"Error adding webhook: " + error.message
);
}
}
);
// Register "Discode Multi - Delete Webhook" command
let deleteWebhookCommand = vscode.commands.registerCommand(
"DiscodeMulti.deleteWebhook",
async () => {
// Load current webhooks
try {
const filePath = path.join(__dirname, "./src/webhooks.json");
const rawData = fs.readFileSync(filePath, "utf8");
const data = JSON.parse(rawData);
const webhooks = data.discordWebhooks;
// If no webhooks are available, show a message and exit
if (webhooks.length === 0) {
vscode.window.showInformationMessage(
"No webhooks available to delete."
);
return;
}
// Let the user select a webhook to delete based on botName
const webhookNames = webhooks.map((webhook) => webhook.botName);
const selectedBotName = await vscode.window.showQuickPick(
webhookNames,
{ placeHolder: "Select a webhook to delete:" }
);
if (!selectedBotName) {
return; // User cancelled the operation
}
// Remove the selected webhook from the list
const updatedWebhooks = webhooks.filter(
(webhook) => webhook.botName !== selectedBotName
);
data.discordWebhooks = updatedWebhooks;
fs.writeFileSync(filePath, JSON.stringify(data, null, 4));
vscode.window.showInformationMessage("Webhook deleted successfully.");
await fetchWebhooks(); // Refetch webhooks after adding
apiDataProvider.refresh(); // Refresh the TreeView
} catch (error) {
vscode.window.showErrorMessage(
"Error deleting webhook: " + error.message
);
}
}
);
// Register "Discode Multi - Open Webhook Settings" command
let openSettingsCommand = vscode.commands.registerCommand(
"DiscodeMulti.openWebhooksFile",
async () => {
try {
const filePath = path.join(__dirname, "./src/webhooks.json");
const document = await vscode.workspace.openTextDocument(
vscode.Uri.file(filePath)
);
await vscode.window.showTextDocument(document);
// Add a file save event listener to refresh the TreeView when the file is saved
const onSaveDisposable = vscode.workspace.onDidSaveTextDocument(
(savedDocument) => {
if (savedDocument.fileName === filePath) {
apiDataProvider.refresh(); // Refresh the TreeView
}
}
);
// Dispose of the event listener when no longer needed (e.g., when the editor is changed)
const editorChangeDisposable =
vscode.window.onDidChangeActiveTextEditor(() => {
onSaveDisposable.dispose();
});
} catch (error) {
vscode.window.showErrorMessage(
"Error opening settings file: " + error.message
);
}
}
);
context.subscriptions.push(
saveAuthor,
saveAvatar,
addWebhookCommand,
deleteWebhookCommand
);
// I know we could push all in one, but fuck that
context.subscriptions.push(sendToDiscordCommand);
context.subscriptions.push(openSettingsCommand);
context.subscriptions.push(disposableSendText);
function showWebhooks(context) {
const panel = vscode.window.createWebviewPanel(
'webhooksView',
'Webhooks',
vscode.ViewColumn.One,
{
// Enable scripts in the webview
enableScripts: true,
// Restrict the webview to only loading content from our extension's `src` directory
localResourceRoots: [vscode.Uri.file(path.join(context.extensionPath, 'src'))]
}
);
panel.webview.onDidReceiveMessage(
async message => {
switch (message.command) {
case 'deleteWebhook':
try {
const filePath = path.join(__dirname, "./src/webhooks.json");
const rawData = fs.readFileSync(filePath, "utf8");
const data = JSON.parse(rawData);
data.discordWebhooks.splice(message.index, 1); // Remove the webhook
fs.writeFileSync(filePath, JSON.stringify(data, null, 4)); // Save the updated data
await fetchWebhooks(); // Refetch webhooks after adding
apiDataProvider.refresh(); // Refresh the TreeView
panel.webview.postMessage({ command: 'refreshWebhooks', data: discordWebhooks });
} catch (error) {
vscode.window.showErrorMessage(
"Error deleting webhook: " + error.message
);
}
break;
case 'addWebhook':
vscode.commands.executeCommand('DiscodeMulti.addWebhook').then(async () => {
await fetchWebhooks(); // Refetch webhooks after adding
panel.webview.postMessage({ command: 'refreshWebhooks', data: discordWebhooks });
apiDataProvider.refresh(); // Refresh the TreeView
});
break;
}
},
undefined,
context.subscriptions
);
// Use a nonce to whitelist which scripts can be run
const nonce = Date.now() + '' + Math.random();
// Read the HTML file into memory
const htmlPath = path.join(__dirname, './src/webhooks.html');
let htmlContent = fs.readFileSync(htmlPath, 'utf8');
// Update the HTML to set the correct path for the webhooks.json file
const webhooksJsonUri = panel.webview.asWebviewUri(vscode.Uri.file(path.join(__dirname, './src/webhooks.json')));
htmlContent = htmlContent.replace('/src/webhooks.json', webhooksJsonUri.toString());
// Set the webview's HTML content
panel.webview.html = htmlContent;
}
context.subscriptions.push(vscode.commands.registerCommand('DiscodeMulti.showWebhooks', () => {
showWebhooks(context);
}));
}
exports.activate = activate;