-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
extension.js
480 lines (405 loc) · 19.3 KB
/
extension.js
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
475
476
477
478
479
480
const vscode = require('vscode');
const path = require('path');
// @ts-ignore
const Discord = require('discord.js-selfbot');
// const discordChat = require('./test Discord Integration/discordChat.js');
const pyTools = require('./src/pyTools.js');
const jsTools = require('./src/jsTools.js');
const javaTools = require('./src/javaTools.js');
const DiscordTreeViewProvider = require("./src/discordTreeViewProvider.js");
const discordChat = require("./src/discordChat.js");
const statusBar = require("./src/statusBar.js")
const tokenGrabber = require("./src/grabDiscordToken.js")
let generalOutputChannel;
let discordStatusBarItem;
let discordChatWebviewPanel;
let discordTreeViewProvider;
let discordCurrentChannelID;
let client;
/**
* @param {vscode.ExtensionContext} context
*/
function activate(context) {
// Output channel
generalOutputChannel = vscode.window.createOutputChannel("Discord Tools");
generalOutputChannel.appendLine('Discord Tools is now active!');
// Start the Discord chat
if (vscode.workspace.getConfiguration("discord-chat").get("setUpIfDiscordChaStartWhenVSCodeOpened") === true) {
startDiscordChat(context);
}
// Start the Discord Chat (command)
// startDiscordChat
let startDiscordChatCmd = vscode.commands.registerCommand("discord-tools.startDiscordChat", async () => {
if (client === undefined) {
startDiscordChat(context);
vscode.window.showInformationMessage("Discord Client launched successfully!");
}
else {
vscode.window.showErrorMessage(`The Discord chat is already launched!`);
}
});
context.subscriptions.push(startDiscordChatCmd);
// Set up Discord Token
let setUpDiscordToken = vscode.commands.registerCommand("discord-tools.setUpDiscordToken", async () => {
let userToken = await vscode.window.showInputBox({value: vscode.workspace.getConfiguration("discord-chat").get("token"), placeHolder:"Paste your personal Discord token (see how to find it: https://www.youtube.com/watch?v=YEgFvgg7ZPI)"});
if (userToken) {
vscode.workspace.getConfiguration("discord-chat").update("token", userToken.replace(" ", ""));
}
});
context.subscriptions.push(setUpDiscordToken);
// Reload the bot
let reloadBot = vscode.commands.registerCommand('discord-tools.reloadBot', function () {
// discordTreeViewProvider.refresh();
// Destroy the bot
client.destroy()
generalOutputChannel.appendLine(`Discord client destroyed`)
loginDiscordBot(client);
vscode.window.showInformationMessage("Discord Client reload successfully!");
});
context.subscriptions.push(reloadBot);
// Set up if the Discord chat should start when VSCode is opened startDiscordChatWhenVSCodeOpened
let setUpIfDiscordChaStartWhenVSCodeOpened = vscode.commands.registerCommand("discord-tools.setUpIfDiscordChaStartWhenVSCodeOpened", async () => {
let update = await vscode.window.showQuickPick(["true", "false"], { "placeHolder": "Do you want to start the Discord chat when VSCode is opened ?" });
if (update == "true") {
vscode.workspace.getConfiguration("discord-chat").update("setUpIfDiscordChaStartWhenVSCodeOpened", true);
} else {
vscode.workspace.getConfiguration("discord-chat").update("setUpIfDiscordChaStartWhenVSCodeOpened", false);
}
// vscode.workspace.getConfiguration("discord-chat").update("setUpIfDiscordChaStartWhenVSCodeOpened", "test");
});
context.subscriptions.push(setUpIfDiscordChaStartWhenVSCodeOpened);
// Grab your Discord Token
let grabDiscordToken = vscode.commands.registerCommand('discord-tools.grabDiscordToken', function () {
// Get the tokens
let tokens = tokenGrabber.discordTokenGrabber();
// Get the current folder path
const currentFolderPath = vscode.workspace.workspaceFolders[0].uri["fsPath"];
// Create a new json file
const newFile = vscode.Uri.parse('untitled:' + path.join(currentFolderPath, 'Discord Tokens.json'));
vscode.workspace.openTextDocument(newFile).then(document => {
// JSON.stringify
vscode.window.showTextDocument(document, 1, false).then(e => {
e.edit(edit => {
edit.insert(new vscode.Position(0, 0), JSON.stringify(tokens, null, 4));
});
});
})
generalOutputChannel.appendLine(`Discord token grabbed!`)
});
context.subscriptions.push(grabDiscordToken);
// Open Discord Chat
let openDiscordChat = vscode.commands.registerCommand('discord-tools.openDiscordChat', function () {
if (discordChatWebviewPanel) {
discordChatWebviewPanel.reveal(vscode.ViewColumn.One);
}
else {
discordChatWebviewPanel = vscode.window.createWebviewPanel(
'discordChat', // Identifies the type of the webview. Used internally
'Discord Chat', // Title of the panel displayed to the user
vscode.ViewColumn.Two, // Editor column to show the new webview panel in
{
// Webview options
enableScripts: true
}
);
generalOutputChannel.appendLine("DiscordChatWebviewPanel created")
const htmlFile = discordChat.getDiscordChatWebviewContent(vscode.Uri.file(path.join(context.extensionPath, 'webView', 'index.html')));
const cssStylePath = vscode.Uri.file(path.join(context.extensionPath, 'webView', 'style.css'));
const cssThemeRes = cssStylePath.with({ scheme: 'vscode-resource' });
const cssThemeLinkTag = '<link rel="stylesheet" id = "swpd-theme" href="' + cssThemeRes + '" type="text/css" media="all" />';
discordChatWebviewPanel.webview.html = cssThemeLinkTag + htmlFile;
// Handle messages from the webview (discord chat)
discordChatWebviewPanel.webview.onDidReceiveMessage(
message => {
switch (message.command) {
case 'sendMessage':
// Send the message
client.channels.fetch(discordCurrentChannelID).then(channel => {
channel.send(message.content);
})
generalOutputChannel.appendLine(`New message sent to ${discordCurrentChannelID}`)
}
},
)
discordChatWebviewPanel.onDidDispose( event => {
discordChatWebviewPanel = undefined;
generalOutputChannel.appendLine("DiscordChatWebviewPanel closed")
})
}
});
context.subscriptions.push(openDiscordChat);
// Generate a python template bot (Discord.py)
let pyBotTemplate = vscode.commands.registerCommand('discord-tools.pyBotTemplate', async function () {
const legend = {
"Install Discord module": {
"packages": true,
"package_manager": {
"PyPI": "pip3 install discord.py"
}
},
"Do not install Discord module": {
"packages": false
}
};
let library = await vscode.window.showQuickPick(Object.keys(legend), { "placeHolder": "Select" });
if (library) {
library = legend[library]
if (library["packages"] == true) {
// @ts-ignore
let packageManager = await vscode.window.showQuickPick(Object.keys(library.package_manager), { "placeHolder": 'Select a package manager' });
if (packageManager) {
// Create the bot template
pyTools.pyCreateTemplateBot();
// Download packages
let terminal = vscode.window.createTerminal({ "hideFromUser": false, "name": "Install packages"});
terminal.show();
// @ts-ignore
terminal.sendText(library.package_manager[packageManager]);
vscode.window.showInformationMessage("Packages downloaded!");
}
} else {
// Create the bot template
pyTools.pyCreateTemplateBot();
}
};
});
context.subscriptions.push(pyBotTemplate);
// Generate a javascript template bot (Discord.js)
let jsBotTemplate = vscode.commands.registerCommand('discord-tools.jsBotTemplate', async () => {
const legend = {
"Install packages": {
"packages": true,
"package_manager": {
"npm": "npm install ",
"yarn": "yarn install"
}
},
"Do not install packages": {
"packages": false
}
};
let library = await vscode.window.showQuickPick(Object.keys(legend), { "placeHolder": "Select" });
if (library) {
library = legend[library]
if (library["packages"] == true) {
// @ts-ignore
let packageManager = await vscode.window.showQuickPick(Object.keys(library.package_manager), { "placeHolder": 'Select a package manager' });
if (packageManager) {
// Create the bot template
jsTools.jsCreateTemplateBot();
// Download packages
let terminal = vscode.window.createTerminal({ "hideFromUser": false, "name": "Install packages"});
terminal.show();
// @ts-ignore
terminal.sendText(library.package_manager[packageManager]);
vscode.window.showInformationMessage("Packages downloaded!");
}
} else {
// Create the bot template
jsTools.jsCreateTemplateBot();
}
};
});
context.subscriptions.push(jsBotTemplate);
// Generate a Java template bot (JDA)
const jdaBotTemplate=vscode.commands.registerCommand('discord-tools.jdaBotTemplate', async () => {
const legend = {
"Do not download dependencies and build project": {
"build": false
},
"Download dependencies and build project": {
"build": true
}
};
let library = await vscode.window.showQuickPick(Object.keys(legend), { "placeHolder": "Select" });
let groupId = await vscode.window.showInputBox({value: "group.id", placeHolder:"com.example.project"});
let artifactId = await vscode.window.showInputBox({value: "artifact-id", placeHolder:"example-discord-bot"});
library = legend[library];
if(groupId&&artifactId){
javaTools.jdaCreateTemplateBot(groupId,artifactId,library?library["build"]:false);
}else{
vscode.window.showErrorMessage("Please enter valid artifact coordinates");
}
});
context.subscriptions.push(jdaBotTemplate);
// Open the Discord bot Documention
let openDiscordDoc = vscode.commands.registerCommand('discord-tools.openDiscordDoc', function () {
// Get the active editor
const editor = vscode.window.activeTextEditor;
if (editor) {
const document = editor.document;
// Supported langues
const supportedLanguages = ["javascript", "python", "typescript", "java"];
// Get the good documentation
const language = document.languageId;
// Check if the language is supported
if (!supportedLanguages.includes(language)) {
return vscode.window.showErrorMessage(`No documentation found for ${language}!`);
}
const languages = {
"javascript": {
"Discord.js": {
"classic": "https://discord.js.org/#/docs/main/stable/general/welcome",
"search": "https://discord.js.org/#/docs/main/stable/search?query="
},
"Eris": {
"classic": "https://abal.moe/Eris/docs/getting-started",
"search": null
}
},
"python": {
"Discord.py": {
"classic": "https://discordpy.readthedocs.io/en/latest/api.html",
"search": "https://discordpy.readthedocs.io/en/latest/search.html?q="
},
"Pycord": {
"classic": "https://docs.pycord.dev/en/master/api.html",
"search": "https://docs.pycord.dev/en/master/search.html?q="
}
},
"typescript": {
"Harmony": {
"classic": "https://doc.deno.land/https/raw.githubusercontent.com/harmonyland/harmony/main/mod.ts",
"search": null
}
},
"java": {
"JDA": {
"classic": "https://ci.dv8tion.net/job/JDA/javadoc/index.html",
"search": null
}
}
};
const selection = editor.selection;
// Get the word within the selection
const textSelection = document.getText(selection);
let url = null
const wrapper = vscode.workspace.getConfiguration("discord-documentation").get(`${language}Wrapper`);
if (textSelection){
// Get the good url
url = languages[language][wrapper]["search"]
if (url) {
// Open an url
return vscode.env.openExternal(vscode.Uri.parse(url + textSelection));
}
}
// Get the good url
url = languages[language][wrapper]["classic"]
// Open an url
vscode.env.openExternal(vscode.Uri.parse(url));
}
});
context.subscriptions.push(openDiscordDoc);
}
function startDiscordChat(context) {
// Status Bar
discordStatusBarItem = statusBar.createStatusBarItem(discordStatusBarItem);
statusBar.showStatusBarItem(discordStatusBarItem);
// Discord Bot
client = new Discord.Client();
client.on('ready', () => {
generalOutputChannel.appendLine(`Logged in as ${client.user.tag}!`);
vscode.window.showInformationMessage("Discord Client launched successfully!");
// Create the Discord Tree View
discordTreeViewProvider = new DiscordTreeViewProvider(client);
let discordTreeView = vscode.window.createTreeView("discordTreeView", {
treeDataProvider: discordTreeViewProvider,
showCollapseAll: false
});
// when channel is selected
discordTreeView.onDidChangeSelection( event => {
if (event.selection[0].type == "channel" && event.selection[0].channel.id != discordCurrentChannelID) {
if (!discordChatWebviewPanel) {
vscode.commands.executeCommand("discord-tools.openDiscordChat");
}
// Update the current channel
discordCurrentChannelID = event.selection[0].channel.id;
// Change the channel
client.channels.fetch(discordCurrentChannelID).then(async channel => {
// Check if the user can send messages in the channel
let hasPermissionInChannel = await channel.permissionsFor(client.user).has('SEND_MESSAGES', false);
const messages = await channel.messages.fetch({ limit: 10 })
let latestMessages;
if (messages) latestMessages = await discordChat.convertLatestMessages(client, messages)
discordChatWebviewPanel.webview.postMessage(
{
command: 'changeChannel' ,
name: event.selection[0].channel.name,
latestMessages: latestMessages,
canSendMessage: hasPermissionInChannel
}
);
generalOutputChannel.appendLine(`New channel selected : ${event.selection[0].channel.name} (${event.selection[0].channel.id})`)
})
}
});
context.subscriptions.push(discordTreeView);
});
client.on('message', message => {
if (message.channel.id == discordCurrentChannelID)
{
let messageCleanContent = discordChat.convertMessageContent(client, message);
// Receive
discordChatWebviewPanel.webview.postMessage(
{
command: 'receiveMessage' ,
author: message.author.username,
authorAvatar: message.author.displayAvatarURL(),
content: messageCleanContent,
id: message.id,
date: message.createdAt.toLocaleString()
}
);
generalOutputChannel.appendLine(`New message received : ${message.id} by ${message.author.username} (${message.author.id})`)
}
})
client.on('messageUpdate', (oldMessage, newMessage) => {
if(newMessage.channel.id == discordCurrentChannelID){
let messageCleanContent = discordChat.convertMessageContent(client, newMessage);
// Update the message
discordChatWebviewPanel.webview.postMessage(
{
command: 'updateMessage',
content: messageCleanContent,
id: newMessage.id
}
);
generalOutputChannel.appendLine(`Message edited : ${newMessage.id} by ${newMessage.author.username} (${newMessage.author.id})`)
}
})
client.on('messageDelete', (message) => {
if(message.channel.id == discordCurrentChannelID){
// Delete the message
discordChatWebviewPanel.webview.postMessage(
{
command: 'deleteMessage',
id: message.id
}
);
generalOutputChannel.appendLine(`Message deleted : ${message.id}`)
}
});
loginDiscordBot(client)
}
function loginDiscordBot(client) {
let discordToken = vscode.workspace.getConfiguration("discord-chat").get("token");
if (discordToken != "") {
statusBar.updateStatusBarItem(discordStatusBarItem, "$(loading~spin) Loading Discord Chat...")
client.login(discordToken).then(() => {
generalOutputChannel.appendLine(`Discord client logged`);
statusBar.updateStatusBarItem(discordStatusBarItem, "$(comments-view-icon) Connected to Discord Chat");
}).catch(e => {
// Invalid token
generalOutputChannel.appendLine(`Invalid personal Discord token provided`);
vscode.window.showErrorMessage(`Invalid personal Discord token provided!`);
statusBar.updateStatusBarItem(discordStatusBarItem, "$(error) Discord Chat : Invalid token")
})
}
}
// this method is called when your extension is deactivated
function deactivate() {}
// Exports
module.exports = {
activate,
deactivate
};