-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.js
1758 lines (1523 loc) · 52.6 KB
/
main.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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
console.log("Please wait...");
const mineflayer = require("mineflayer");
// const {
// pathfinder,
// Movements,
// goals: { GoalNear, GoalBlock },
// } = require("mineflayer-pathfinder");
const { mineflayer: mineflayerViewer, viewer } = require("prismarine-viewer");
const express = require("express");
const { Server } = require("socket.io");
const bodyParser = require("body-parser");
const toolPlugin = require("mineflayer-tool").plugin;
const dns = require("node:dns");
const os = require("node:os");
const https = require("https");
const http = require("http");
const path = require("path");
const { Image } = require("canvas");
const fs = require("fs").promises;
const Vec3 = require("vec3").Vec3;
const cors = require("cors");
const { elytrafly } = require("mineflayer-elytrafly");
const e = require("express");
const prompt = require("prompt-sync")();
const { createCanvas, loadImage } = require("canvas");
const WebSocket = require("ws");
const { fetch } = require("node-fetch");
const { EventEmitter } = require("events");
const OpenAI = require("openai");
const sharp = require("sharp");
const pathfinder = require("mineflayer-pathfinder").pathfinder;
const Movements = require("mineflayer-pathfinder").Movements;
const { GoalNear, GoalBlock } = require("mineflayer-pathfinder").goals;
const {
default: loader,
EntityState,
} = require("@nxg-org/mineflayer-physics-util");
var createRsaKeys = require("rsa-json");
var pem = require("pem");
const { exit } = require("node:process");
// const pathfinder = createPlugin();
// Express API setup
async function main() {
console.clear();
const dotenv = require("dotenv").config();
const fs2 = require("fs");
const app = express();
const morgan = require("morgan");
const port = process.env.PORT || 4500;
// Middleware
app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(cors()); // Add this line to enable CORS for all routes
// Routes
// openssl genrsa -out localhost-key.pem 2048
// openssl req -new -x509 -sha256 -key localhost-key.pem -out localhost.pem -days 365
// Generate self-signed certificate
function generateCertificate() {
return new Promise((resolve, reject) => {
pem.createCertificate({ days: 1, selfSigned: true }, (err, keys) => {
if (err) {
reject(err);
} else {
console.log("Certificate generated successfully");
resolve(keys);
}
});
});
}
const rsa_keys = await generateCertificate();
const server = https.createServer(
{ key: rsa_keys.clientKey, cert: rsa_keys.certificate },
app
);
const io = new Server(server, {
cors: {
origin: "*",
methods: ["*"],
},
});
// set up rate limiter: maximum of five requests per minute
var RateLimit = require("express-rate-limit");
var limiter = RateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100000, // max 100 requests per windowMs
});
// apply rate limiter to all requests
app.use(limiter);
const DEFAULT_PORT = 3001;
const versions = require("minecraft-data").supportedVersions.pc;
// Bot state
let botState = {
created: false,
spawned: false,
username: "",
data: {},
versions: versions,
};
let storageArea = { x: "-34", y: "122", z: "-50" };
let isDelivering = false;
let chestIndex = {};
let bot;
let botviewer;
const CHEST_CHECK_INTERVAL = 60000 * 10; // Check chests every 5 minutes
const SEARCH_RADIUS = 20; // Search radius for chests
const mapData = {};
const entityPositions = {};
const textureCache = {};
const TEXTURE_BASE_URL = "http://localhost:3000/block/";
const chatMessages = [];
const MAX_CHAT_MESSAGES = 100;
const chatEmitter = new EventEmitter();
chatEmitter.setMaxListeners(50);
const FALLBACK_TEXTURE = "obsidian.png";
// Add this function after bot creation
function setupChatListener() {
if (!bot) return;
bot.on("messagestr", (message, messagePosition, jsonMsg, sender) => {
const chatMessage = {
message,
messagePosition,
sender: sender ? sender.username : "Unknown",
timestamp: new Date().toISOString(),
};
chatMessages.unshift(chatMessage);
if (chatMessages.length > MAX_CHAT_MESSAGES) {
chatMessages.pop();
}
chatEmitter.emit("newMessage", chatMessage);
});
}
// Function to process and cache textures
async function processTexture(buffer, blockName) {
const image = await loadImage(buffer);
textureCache[blockName] = image;
return image;
}
// Function to load textures
function getTexture(blockName) {
if (textureCache[blockName]) {
return textureCache[blockName];
}
const texturePath = getTexturePathForBlock(blockName);
const url = TEXTURE_BASE_URL + texturePath;
// const image = loadImage(`frontend/public/block/${texturePath}`);
const img = new Image();
img.src = `frontend/public/block/${texturePath}`;
textureCache[blockName] = img;
return img;
}
function getObsidianTexture() {
return new Promise((resolve, reject) => {
if (textureCache[FALLBACK_TEXTURE]) {
resolve(textureCache[FALLBACK_TEXTURE]);
return;
}
const url = TEXTURE_BASE_URL + FALLBACK_TEXTURE;
http
.get(url, (response) => {
if (response.statusCode !== 200) {
reject(
new Error(
`Failed to fetch fallback texture: ${response.statusCode} ${url}`
)
);
return;
}
const chunks = [];
response.on("data", (chunk) => chunks.push(chunk));
response.on("end", () => {
const buffer = Buffer.concat(chunks);
processTexture(buffer, FALLBACK_TEXTURE)
.then(resolve)
.catch(reject);
});
})
.on("error", (err) => {
reject(err);
});
});
}
// async function processTexture(buffer, blockName) {
// const image = await loadImage(buffer);
// textureCache[blockName] = image;
// return image;
// }
function processTexture(buffer, textureName) {
sharp(buffer)
.resize(16, 16, { fit: "cover" })
.raw()
.toBuffer((err, resizedBuffer, info) => {
if (err) {
reject(err);
return;
}
const texture = {
data: new Uint8Array(resizedBuffer),
width: info.width,
height: info.height,
};
textureCache[textureName] = texture;
return loadImage(texture);
});
}
// Helper function to get texture path for a block
function getTexturePathForBlock(blockName) {
// Add more mappings as needed
const textureMap = {
grass_block: "grass_block_side.png",
stone: "stone.png",
dirt: "dirt.png",
water: "water_still.png",
// Add more block types here
};
return textureMap[blockName] || `${blockName}.png`;
}
// Function to update map data
async function updateMapData(x, z) {
const maxY = bot.game.height - 1; // Get the maximum height of the world
let y;
// Start from the top and move down until we find a non-air block
for (y = maxY; y >= 0; y--) {
const block = bot.blockAt(new Vec3(x, y, z));
if (
block &&
block.type !== 0 &&
block.name !== "grass" &&
block.name !== "tall_grass" &&
block.name != "chest" &&
block.name !== "ender_chest" &&
block.name !== "water" &&
block.name != "stairs"
) {
console.log("Found block:", block.name, x, y, z);
// 0 is the ID for air
break;
}
}
if (y >= 0) {
const block = bot.blockAt(new Vec3(x, y, z));
mapData[`${x},${z}`] = block.name;
} else {
// If no non-air block was found, we can consider it as void or some default
mapData[`${x},${z}`] = "void";
}
}
// Function to scan area around bot
async function scanArea(radius) {
const botPos = bot.entity.position;
for (
let x = Math.floor(botPos.x) - radius;
x <= Math.floor(botPos.x) + radius;
x++
) {
for (
let z = Math.floor(botPos.z) - radius;
z <= Math.floor(botPos.z) + radius;
z++
) {
await updateMapData(x, z);
}
}
}
async function loadChestIndex() {
try {
const data = await fs.readFile("chestIndex.json", "utf8");
chestIndex = JSON.parse(data);
} catch (error) {
console.log("No existing chest index found. Starting fresh.");
}
}
async function saveChestIndex() {
await fs.writeFile("chestIndex.json", JSON.stringify(chestIndex, null, 2));
}
async function startChestMonitoring() {
while (true) {
if (!isDelivering && storageArea) {
await updateChestContents();
}
await new Promise((resolve) => setTimeout(resolve, CHEST_CHECK_INTERVAL));
}
}
async function findWaterOrLavaAndRespawn() {
try {
console.log("Searching for water to respawn...");
const water = bot.findBlock({
matching: (block) => block.name === "water" || block.name === "lava",
maxDistance: 100,
});
if (!water) {
console.log(
"No water or lava found nearby. Searching for a larger area..."
);
return;
}
console.log(
`Water or lava found at ${water.position}. Moving to location.`
);
try {
await bot.pathfinder.goto(
new GoalBlock(water.position.x, water.position.y, water.position.z)
);
} catch (error) {
console.error("Notice respawn");
}
console.log("Jumping into water/lava to respawn...");
bot.setControlState("sneak", true);
// Wait for the bot to respawn
await new Promise((resolve) => bot.once("death", resolve));
bot.pathfinder.stop();
console.log("Respawned at spawn point.");
bot.setControlState("sneak", false);
} catch (error) {
console.error("Error during respawn process:", error);
}
}
async function updateChestContents() {
try {
await goToLocation(storageArea, false);
const chests = await findChestsInArea();
for (const chest of chests) {
console.log(chest);
await updateSingleChestContents(chest);
}
await saveChestIndex();
console.log("Chest contents updated");
} catch (error) {
console.error("Error updating chest contents:", error.message);
}
}
async function updateSingleChestContents(chestBlock) {
await goToLocation(chestBlock, false);
const chest = await bot.openContainer(bot.blockAt(chestBlock));
console.log("Updating chest contents:", chestBlock);
const items = chest.containerItems();
const chestPos = `${chestBlock.x},${chestBlock.y},${chestBlock.z}`;
chestIndex[chestPos] = items.reduce((acc, item) => {
if (item.name.endsWith("shulker_box")) {
const shulkerItems = getShulkerContents(item);
acc[`${item.name}`] = shulkerItems;
} else {
acc[item.name] = (acc[item.name] || 0) + item.count;
}
return acc;
}, {});
await chest.close();
}
function getShulkerContents(item) {
if (
item.nbt &&
item.nbt.value.BlockEntityTag &&
item.nbt.value.BlockEntityTag.value.Items
) {
const items = item.nbt.value.BlockEntityTag.value.Items.value.value;
return items.map((i) => `${i.id.value}: ${i.Count.value}`);
}
return [];
}
async function findChestsInArea() {
console.log("Searching for chests...");
return bot.findBlocks({
matching: bot.registry.blocksByName["chest"].id,
useExtraInfo: true,
maxDistance: SEARCH_RADIUS,
count: 1000, // Adjust this number based on expected number of chests
});
}
async function storeItemsInClosestEnderChest() {
try {
const enderChestBlock = bot.findBlock({
matching: bot.registry.blocksByName["ender_chest"].id,
maxDistance: 20,
});
if (!enderChestBlock) {
throw new Error("No ender chest found nearby.");
}
await goToLocation(enderChestBlock.position, false);
try {
await bot.unequip("torso");
} catch (error) {}
const enderChest = await bot.openContainer(enderChestBlock);
console.log("Storing items in ender chest...");
for (const item of bot.inventory.slots) {
if (item != null) {
console.log(item);
await enderChest.deposit(item.type, null, item.count);
await bot.waitForTicks(20);
}
}
await enderChest.close();
} catch (error) {
console.error("Error storing items in ender chest:", error.message);
throw error;
}
}
async function generateMapImage() {
const width = 64;
const height = 64;
const blockSize = 16; // Size of each block in pixels
const canvas = createCanvas(width, height);
const ctx = canvas.getContext("2d");
// Render map data
for (const [key, blockName] of Object.entries(mapData)) {
const [x, z] = key.split(",").map(Number);
const texture = await getTexture(blockName);
if (texture) {
console.log(texture);
ctx.drawImage(texture, x, z, blockSize, blockSize);
console.log("Rendered block:", blockName, x, z);
}
}
// Render entities
Object.values(entityPositions).forEach((entity) => {
ctx.fillStyle = entity.type === "player" ? "red" : "blue";
ctx.beginPath();
ctx.arc(entity.x * blockSize, entity.z * blockSize, 8, 0, 2 * Math.PI); // Scale and size adjustments for visibility
ctx.fill();
});
console.log("Map image generated");
return canvas.toBuffer();
}
// Function to get examples from flow_functions folder
async function getExamples() {
const folderPath = path.join(__dirname, "flow_functions");
const files = await fs.readdir(folderPath);
const examples = [];
for (const file of files) {
if (file.endsWith(".js")) {
const content = await fs.readFile(path.join(folderPath, file), "utf-8");
examples.push({ filename: file, content });
}
}
return examples;
}
async function updateFunctionsJson(newNode) {
const functionsPath = path.join(
__dirname,
"flow_functions",
"functions.json"
);
const functionsData = await fs.readFile(functionsPath, "utf-8");
const functionsJson = JSON.parse(functionsData);
const nodeId = newNode; // Get the new node's ID directly
console.log("New node:", nodeId);
let nodeName;
for (const key in newNode) {
if (newNode[key].name) {
nodeName = newNode[key].name;
}
}
console.log(nodeName);
const insides = newNode[nodeName];
var now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1; // Months are zero-based, so add 1
const day = now.getDate();
const badges = insides["badges"];
const updatedInsides = (insides["badges"] = [
`${badges} @ ${day}/${month}/${year}`,
]);
console.log(insides);
// Ensure the node doesn't have an extra key layer
if (functionsJson[nodeName]) {
console.error(`Node with ID ${nodeId} already exists.`);
} else {
functionsJson[nodeName] = insides;
}
await fs.writeFile(functionsPath, JSON.stringify(functionsJson, null, 2));
}
function getInnerObject(dynamicObj, key) {
if (dynamicObj[key]) {
return dynamicObj[key];
}
return null;
}
function getFilename(dynamicObj) {
for (const key in dynamicObj) {
if (dynamicObj[key].file) {
return dynamicObj[key].file;
}
}
return null;
}
app.post("/generate-node", async (req, res) => {
try {
const { description } = req.body;
const apiKey = req.app.locals.apiKey;
if (!apiKey) {
return res
.status(400)
.json({ error: "API key not set. Please set the API key first." });
}
const openai = new OpenAI({
apiKey: apiKey,
baseURL: "https://integrate.api.nvidia.com/v1",
});
if (!description) {
return res.status(400).json({ error: "Description is required" });
}
const examples = await getExamples();
const prompt = `
Create a new flow node based on the following description:
${description}
Here are some examples of existing nodes:
${examples.map((ex) => `${ex.filename}:\n${ex.content}\n`).join("\n")}
Generate a new node in the same format, including:
1. The main function implementation
2. A JSON object for the functions.json file entry
3. Add an badge "badges": ["Made With AI"]
4. for author use 'meta/llama-3.1-405b-instruct'
5. For input fields names use lowercase and underscores for spaces. Dont add words together with no spaces or underscores.
6. make the input fields as clear as possible and explain what the user needs to input and what format it should be in. like for a range make it block_range
when working with coordinates:
the data you get from the input will be in a string format that the bot cant use.
to convert it to a vec3 object you can use the following code:
const { Vec3 } = require("vec3");
let position;
if (data.includes(",")) {
position = data.split(",");
if (data.includes(" ")) {
position = data.split(" ");
}
const positionVec = new Vec3(position[0], position[1], position[3]);
for the input names please explain what the user needs to input and what format it should be in.
then access that input in the main function by doing data['input_name']
Ensure the node follows the project's conventions and best practices.
Here are some documentation you can use:
2. Create a New Node File
Navigate to the flow_functions folder in the project directory. Create a new file for your node with the following naming conventions:
Name Format: your_node_name.js
Rules:
Use lowercase letters
Use underscores (_) to separate words
Do not include numbers in the file name
For example, if you want to create a node for crafting planks, you might name the file craft_planks.js.
3. Update functions.json
In the flow_functions directory, open the functions.json file and add an entry for your new node:
{
"YOUR_NODE_NAME": {
"name": "YOUR_NODE_NAME",
"file": "YOUR_NODE_NAME.js",
"id": "YOUR_NODE_NAME",
"label": "DISPLAY NAME",
"hasInput": true,
"description": "YOUR NODE DESCRIPTION",
// example of input
"input": { "amount": "number", "message": "text", "explain what state does": "switch" },
"author": "YOUR NAME"
}
}
Replace the placeholders:
YOUR_NODE_NAME - The name of your node (in lowercase with underscores)
DISPLAY NAME - The name displayed in the UI
YOUR NODE DESCRIPTION - A description of what your node does
YOUR NAME - Your GitHub username
{ "Explain input and format": "number", "Explain input and format": "text" } - Your input fields.
Available input options:
text - An general text input box
number - An input box limited to numbers only
switch - An switch that can be set to true or false
4. Implement the Node
Open your newly created file and implement your node using the following structure:
const { getBot } = require("../main.js");
function main(data) {
// Get the bot object
const bot = getBot();
// Your function logic here
console.log("Executing test_node with data:", data);
}
module.exports = { main };
Key Points:
Require bot from ../main.js.
The main function should be defined and exported. This function is executed when the node runs.
Use try and catch statements for error handling. If an error occurs, log it and rethrow it to ensure it can be caught elsewhere.
Accessing input fields In order to the get values from the input field of a node you can use the data argument in the main function an example: in functions.json I've added an function with the following input: { "Amount": "number", "Message": "text" } now i can access them in the main function by doing: data['amount'] and data['message'] the parameter name is based on the key provided in the input.
`;
const completion = await openai.chat.completions.create({
model: "meta/llama-3.1-405b-instruct",
messages: [{ role: "user", content: prompt }],
temperature: 0.7,
max_tokens: 1500,
});
const generatedContent = completion.choices[0].message.content;
// Extract the JavaScript code and JSON object from the generated content
const jsCode = generatedContent
.match(/```javascript([\s\S]*?)```/)[1]
.trim();
const jsonObject = JSON.parse(
generatedContent.match(/```json([\s\S]*?)```/)[1].trim()
);
// Generate a filename for the new node
let nodeId = getFilename(jsonObject);
console.log(jsonObject);
console.log("Node ID:", nodeId);
if (!nodeId) {
// Fallback: generate an id from the name or label
nodeId = (jsonObject.name || jsonObject.label || "generated_node")
.toLowerCase()
.replace(/\s+/g, "_")
.replace(/[^a-z0-9_]/g, "");
jsonObject.id = nodeId;
}
console.log("Node ID:", nodeId);
// Update functions.json and get the node ID
await updateFunctionsJson(jsonObject);
const filename = `${nodeId}`;
const filePath = path.join(__dirname, "flow_functions", filename);
// Write the new node file
await fs.writeFile(filePath, jsCode);
res.json({
message: "Node generated successfully",
filename,
functionsJsonEntry: jsonObject,
});
} catch (error) {
console.error("Error generating node:", error);
res
.status(500)
.json({ error: "Failed to generate node", details: error.message });
}
});
// // New endpoint
// app.post("/generate-node", async (req, res) => {
// try {
// const { description } = req.body;
// const apiKey = req.app.locals.apiKey;
// if (!apiKey) {
// return res
// .status(400)
// .json({ error: "API key not set. Please set the API key first." });
// }
// const openai = new OpenAI({
// apiKey: apiKey,
// baseURL: "https://integrate.api.nvidia.com/v1",
// });
// if (!description) {
// return res.status(400).json({ error: "Description is required" });
// }
// const examples = await getExamples();
// const prompt = `
// Create a new flow node based on the following description:
// ${description}
// Here are some examples of existing nodes:
// ${examples.map((ex) => `${ex.filename}:\n${ex.content}\n`).join("\n")}
// Generate a new node in the same format, including:
// 1. The main function implementation
// 2. A JSON object for the functions.json file entry
// Ensure the node follows the project's conventions and best practices.
// Here are some documentation you can use:
// 2. Create a New Node File
// Navigate to the flow_functions folder in the project directory. Create a new file for your node with the following naming conventions:
// Name Format: your_node_name.js
// Rules:
// Use lowercase letters
// Use underscores (_) to separate words
// Do not include numbers in the file name
// For example, if you want to create a node for crafting planks, you might name the file craft_planks.js.
// 3. Update functions.json
// In the flow_functions directory, open the functions.json file and add an entry for your new node:
// {
// "YOUR_NODE_NAME": {
// "name": "YOUR_NODE_NAME",
// "file": "YOUR_NODE_NAME.js",
// "id": "YOUR_NODE_NAME",
// "label": "DISPLAY NAME",
// "hasInput": true,
// "description": "YOUR NODE DESCRIPTION",
// // example of input
// "input": { "amount": "number", "message": "text", "sneak": "switch" },
// "author": "YOUR NAME"
// }
// }
// Replace the placeholders:
// YOUR_NODE_NAME - The name of your node (in lowercase with underscores)
// DISPLAY NAME - The name displayed in the UI
// YOUR NODE DESCRIPTION - A description of what your node does
// YOUR NAME - Your GitHub username
// { "NAME": "number", "NAME": "text" } - Your input fields.
// Available input options:
// text - An general text input box
// number - An input box limited to numbers only
// switch - An switch that can be set to true or false
// 4. Implement the Node
// Open your newly created file and implement your node using the following structure:
// const { getBot } = require("../main.js");
// function main(data) {
// // Get the bot object
// const bot = getBot();
// // Your function logic here
// console.log("Executing test_node with data:", data);
// }
// module.exports = { main };
// Key Points:
// Require bot from ../main.js.
// The main function should be defined and exported. This function is executed when the node runs.
// Use try and catch statements for error handling. If an error occurs, log it and rethrow it to ensure it can be caught elsewhere.
// Accessing input fields In order to the get values from the input field of a node you can use the data argument in the main function an example: in functions.json I've added an function with the following input: { "Amount": "number", "Message": "text" } now i can access them in the main function by doing: data.amount and data.message the parameter name is based on the key provided in the input.
// `;
// const completion = await openai.chat.completions.create({
// model: "meta/llama-3.1-405b-instruct",
// messages: [{ role: "user", content: prompt }],
// temperature: 0.7,
// max_tokens: 1500,
// });
// const generatedContent = completion.choices[0].message.content;
// // Extract the JavaScript code and JSON object from the generated content
// const jsCode = generatedContent
// .match(/```javascript([\s\S]*?)```/)[1]
// .trim();
// const jsonObject = JSON.parse(
// generatedContent.match(/```json([\s\S]*?)```/)[1].trim()
// );
// // Generate a filename for the new node
// const filename = `${jsonObject.id}.js`;
// const filePath = path.join(__dirname, "flow_functions", filename);
// // Write the new node file
// await fs.writeFile(filePath, jsCode);
// // Update functions.json
// await updateFunctionsJson(jsonObject);
// res.json({
// message: "Node generated successfully",
// filename,
// functionsJsonEntry: jsonObject,
// });
// } catch (error) {
// console.error("Error generating node:", error);
// res
// .status(500)
// .json({ error: "Failed to generate node", details: error.message });
// }
// });
// API endpoints
// API endpoint to get bot state
app.get("/bot-state", (req, res) => {
botState.versions = versions;
res.json(botState);
});
app.get("/functions", async (req, res) => {
try {
const functionsPath = path.join(
__dirname,
"flow_functions",
"functions.json"
);
const functionsData = await fs.readFile(functionsPath, "utf-8");
const functionsJson = JSON.parse(functionsData);
const formattedFunctions = Object.entries(functionsJson).map(
([key, value]) => ({
id: key,
label: value.label,
hasInput: value.hasInput,
description: value.description,
inputLabel: value.inputLabel,
inputType: value.inputType,
author: value.author,
input: value.input,
badges: value.badges,
})
);
res.json(formattedFunctions);
} catch (error) {
console.error("Error reading functions.json:", error);
res.status(500).json({ error: "Internal server error" });
}
});
app.post("/set-api-key", (req, res) => {
const { apiKey } = req.body;
if (!apiKey) {
return res.status(400).json({ error: "API key is required" });
}
// In a real application, you'd want to store this securely, not in memory
req.app.locals.apiKey = apiKey;
res.json({ message: "API key set successfully" });
});
app.post("/generate-text", async (req, res) => {
const { prompt } = req.body;
const apiKey = req.app.locals.apiKey;
if (!apiKey) {
return res
.status(400)
.json({ error: "API key not set. Please set the API key first." });
}
if (!prompt) {
return res.status(400).json({ error: "Prompt is required" });
}
const openai = new OpenAI({
apiKey: apiKey,
baseURL: "https://integrate.api.nvidia.com/v1",
});
try {
const completion = await openai.chat.completions.create({
model: "meta/llama-3.1-405b-instruct",
messages: [{ role: "user", content: prompt }],
temperature: 0.2,
top_p: 0.7,
max_tokens: 1024,
});
res.json({ response: completion.choices[0]?.message?.content || "" });
} catch (error) {
console.error("Error generating text:", error);
res
.status(500)
.json({ error: "Failed to generate text", details: error.message });
}
});
app.post("/flow/:flowName", async (req, res) => {
const flowName = req.params.flowName;
const inputData = req.body;
try {
const flowPath = path.join(__dirname, "flow_functions", `${flowName}.js`);
const flowModule = require(flowPath);
if (typeof flowModule.main !== "function") {
throw new Error("Invalid flow function");
}
await flowModule.main(inputData);
delete require.cache[require.resolve(flowPath)];
res.status(200).json({ message: "Flow executed successfully" });
} catch (error) {
console.error(`Error executing flow ${flowName}: %s`, error);
res
.status(500)
.json({ error: "Flow execution failed", details: error.message });
}
});
// API endpoint to stop the bot.
app.post("/stop-bot", async (req, res) => {
if (bot) {
try {
await bot.quit();
} catch (error) {
console.error("Error stopping bot:", error.message);
}
botState = {
created: false,
spawned: false,
};
try {
await bot.viewer.close();
} catch (error) {
console.error("Error stopping bot:", error.message);
}
try {
bot = null;
} catch (error) {
console.error("Error stopping bot:", error.message);
}
res.json({ message: "Bot stopped successfully" });
} else {
res.status(400).json({ error: "Bot not found" });
}
});
function waitForEvent(emitter, event) {
return new Promise((resolve) => {
emitter.once(event, resolve);
});
}
app.get("/", async (req, res) => {
res.json({ message: "Successfully reached the api." });
});