-
Notifications
You must be signed in to change notification settings - Fork 5
/
plugin.js
348 lines (272 loc) · 10.8 KB
/
plugin.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
const { Configuration, OpenAIApi } = require('openai');
const DEFAULT_PERSONALITY = "helpful";
const clients = {}; // not sure if "client" is the right word but whatever
async function getChatGPTResponse(bot, messages) {
if (!bot.gpt.online) return "SAY Offline '^'"; // Not perfect but it works.
let client = clients[bot.username];
const completion = await client.createChatCompletion({
model: bot.gpt.model,
messages: messages,
});
return completion.data.choices[0].message.content;
}
async function getGreetingMessage(bot, client) {
if (!bot.gpt.online) return "I'm a happy little robot."; // I could use bot.gpt.personality here...
const completion = await client.createChatCompletion({
model: bot.gpt.model,
messages: [
{"role": "system", "content": `You are a ${bot.gpt.personality} in Minecraft.`},
{"role": "user", "content": "Generate a greeting to say when you join the game. Don't use quotes."},
],
});
return completion.data.choices[0].message.content;
}
async function respondToMessage(bot, message) {
let response = await getChatGPTResponse(bot, [
{"role": "system", "content": `You are a ${bot.gpt.personality} in Minecraft. Don't break character for any reason.`},
...bot.gpt.log,
{"role": "user", "content": message},
]);
bot.gpt.log.push({"role": "user", "content": message});
bot.gpt.log.push({"role": "assistant", "content": response});
return response;
}
const DEFAULT_COMMAND_LIST = {
"GOTO": "Makes you walk to a specified entity. Pathfinding is done automatically.",
"SAY": "Sends a message in the game. Use this to talk. Messages do not require quotes.",
"LOOKAT": "Makes you look in the direction of a specified entity.",
"PUNCH": "Punches the nearest entity.",
//"ITEM": "Switches item in hand to specified item. (eg. wooden_sword)",
"WAIT": "Waits for a specified number of ticks.",
//"KILL": "Kill the specified entity.",
//"TOSS": "Toss items out of inventory. First argument is the type of item to toss, second argument is the quantity.",
"SNEAK": "Activate/deactivate sneaking. Takes one argument which can be either ON or OFF.",
};
const COMMAND_PROMPT = `
Each line of your response will be treated as a "command".
Use commands to complete the tasks you are given.
Arguments to these commands are seperated by spaces.
Each command is executed in order by the system, waiting for the current command to finish before running the next.
You can use the following commands:
<INSERT COMMANDS HERE>
These are the only commands you can use.
The following syntax can be used to refer to entities:
#name=cheese (gets the nearest entity or player with the name "cheese")
#type=pig (gets the nearest pig)
#name=frank&type=player (gets the nearest player with the name "frank")
You can also use the following values:
$player (the player that sent the message)
$myself (Your own player)
Examples of some commands:
SAY Hello $player!
LOOKAT #type=rabbit
GOTO $player
Message from player:
`;
async function getActionsFromCommand(bot, command) {
let listOfCommands = "";
for (key of Object.keys(bot.gpt.COMMAND_LIST)) {
listOfCommands = `${key} -> ${bot.gpt.COMMAND_LIST[key]}\n`;
}
let response = await getChatGPTResponse(bot, [
{"role": "system", "content": `You are a ${bot.gpt.personality} in Minecraft. Don't break character for any reason.`},
{"role": "user", "content": COMMAND_PROMPT.replace('<INSERT COMMANDS HERE>', listOfCommands) command},
]);
return response;
}
// This next part is a little messy.
function precomputeTokens(bot, username, tokens) {
let computedTokens = [];
for (token of tokens) {
if (token === "$player") {
let user = bot.players[username];
computedTokens.push(user.entity);
continue;
}
if (token === "$myself") {
computedTokens.push(bot.entity);
continue;
}
if (token.startsWith("#")) {
let properties = {};
token.slice(1).split("&").forEach(condition => {
const [key, value] = condition.split("=");
properties[key] = value;
});
let entity = bot.nearestEntity((entity)=>{
let name = entity.username || entity.displayName;
let type = entity.name;
if (properties["name"] && name !== properties.name) return false;
if (properties["type"] && type !== properties.type) return false;
return true;
});
computedTokens.push(entity);
continue;
}
computedTokens.push(token);
}
return computedTokens;
}
const DEFAULT_COMMAND_FUNCTIONS = {
"GOTO": async (bot, [entity])=>{
await bot.pathfinder.goto(entity.position);
},
"LOOKAT": async (bot, [entity])=>{
await bot.lookAt(entity.position.offset(0, entity.height, 0));
},
"SAY": async (bot, _, fullText)=>{
let text = fullText.slice(4);
text = text.replace("$player", username);
text = text.replace("$myself", bot.username);
await bot.chat(text);
},
"PUNCH": async (bot, [entity])=>{
await bot.attack(entity);
},
"ITEM": async (bot, [itemName])=>{
let item = bot.registry.itemsByName[itemName];
await bot.equip(item.id);
},
"KILL": async (bot, [entity])=>{
// TODO: implement actual cheese
for (let x = 0; x < 5; x ) {
bot.attack(entity);
await bot.waitForTicks(5);
}
},
"SNEAK": async (bot, [state])=>{
if (state === "ON") bot.setControlState('sneak', true);
else if (state === "OFF") bot.setControlState('sneak', false);
},
"TOSS": async (bot, [itemName, quantity])=>{
let itemType = bot.registry.itemsByName(itemName).id;
quantity = parseInt(quantity) || 1;
await bot.toss(itemType, null, quantity);
},
"WAIT": async (bot, [duration])=>{
duration = parseInt(duration);
await bot.waitForTicks(duration);
},
};
async function performActions(bot, username, actions) {
actions = actions.split('\n');
let user = bot.players[username];
for (action of actions) {
let tokens = action.split(' ');
tokens = precomputeTokens(bot, username, tokens);
//console.log(`${action} (${tokens[0]})`);
/*
if (tokens[0] === "SAY") {
let text = action.slice(4);
text = text.replace("$player", username);
text = text.replace("$myself", bot.username);
await bot.chat(text);
bot.emit("gpt-succeed", action);
continue;
}
*/
let commandFunction = bot.gpt.COMMAND_FUNCTIONS[tokens[0]];
if (!commandFunction) bot.emit("gpt-failed", action); // <- this is wrong but works fine temp
else bot.emit("gpt-succeed", action);
console.log(`T0: "${tokens[0]}"`, bot.gpt.COMMAND_FUNCTIONS);
await commandFunction(bot, tokens.slice(1), action);
/*
switch (tokens[0]) {
case "GOTO":
await bot.pathfinder.goto(entity.position);
break;
case "SAY":
let text = action.slice(4);
text = text.replace("$player", username)
text = text.replace("$myself", bot.username)
await bot.chat(text);
break
case "LOOKAT":
await bot.lookAt(entity.position.offset(0, entity.height, 0));
break;
case "PUNCH":
bot.attack(entity);
break;
case "ITEM":
let itemName = tokens[1];
let itemType = bot.registry.itemsByName(itemName);
await bot.equip(itemType);
break;
case "KILL":
// TODO: implement actual cheese
for (let x = 0; x < 5; x ) {
bot.attack(entity);
await bot.waitForTicks(5);
}
break;
case "SNEAK":
if (tokens[1] === "ON") bot.setControlState('sneak', true);
else if (tokens[1] === "OFF") bot.setControlState('sneak', false);
break;
case "TOSS":
let itemName = tokens[1];
let amount = parseInt(tokens[2]) || 1;
let itemType = bot.registry.itemsByName(itemName).id;
await bot.toss(itemType, null, amount);
break;
case "WAIT":
let duration = parseInt(tokens[1]);
await bot.waitForTicks(duration);
break;
default:
commandFailed = true;
bot.emit("gpt-failed", action);
}
*/
await bot.waitForTicks(bot.gpt.actionDelay);
}
}
function plugin(bot, {key, personality=DEFAULT_PERSONALITY, fillerDelay=2000, online=true}) {
bot.gpt = {
COMMAND_FUNCTIONS: DEFAULT_COMMAND_FUNCTIONS,
COMMAND_LIST: DEFAULT_COMMAND_LIST,
actionDelay: 1, // How long to wait between executing commands. (ticks)
allowFollowUpPrompts: false,
allowMetaPrompts: false,
fillerDelay: fillerDelay, // Miliseconds to wait before saying stuff like "umm..." while generating a response.
model: "gpt-3.5-turbo",
online: online,
personality: personality " robot", // The personality to adopt
log: [],
};
// putting this here last minute
if (!bot.registry) bot.registry = require('minecraft-data')(bot.version);
const configuration = new Configuration({
apiKey: key,
});
client = new OpenAIApi(configuration);
bot.gpt.greetingPromise = getGreetingMessage(bot, client);
bot.once('spawn', async ()=>{
clients[bot.username] = client;
let greeting = await bot.gpt.greetingPromise;
bot.chat(greeting);
bot.gpt.log.push({
"role": "assistant",
"content": greeting
});
});
bot.on('chat', async (username, message)=>{
if (username === bot.username) return;
if (message.startsWith('!')) return;
if (message.startsWith('#')) return;
let response = await respondToMessage(bot, message);
bot.chat(response);
});
bot.gpt.get = async (messages)=>{
return getChatGPTResponse(bot, messages);
};
bot.gpt.command = async (username, instruction)=>{
let actions = await getActionsFromCommand(bot, instruction);
console.log(actions);
performActions(bot, username, actions);
};
bot.gpt.action = (username, action)=>{
performActions(bot, username, action);
};
}
module.exports = plugin;