CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PrismarineJS

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: PrismarineJS/mineflayer
Path: blob/master/examples/python/chatterbox.py
Views: 789
1
# ==========================================================================
2
# This example demonstrates how easy it is to create a bot
3
# that sends chat messages whenever something interesting happens
4
# on the server you are connected to.
5
#
6
# Below you can find a wide range of different events you can watch
7
# but remember to check out the API documentation to find even more!
8
#
9
# Some events may be commented out because they are very frequent and
10
# may flood the chat, feel free to check them out for other purposes though.
11
#
12
# This bot also replies to some specific chat messages so you can ask him
13
# a few information while you are in game.
14
# ===========================================================================
15
import sys, re
16
from javascript import require, On, Once, console
17
18
mineflayer = require("mineflayer", "latest")
19
Vec3 = require("vec3").Vec3
20
21
print(sys.argv)
22
if len(sys.argv) < 3 or len(sys.argv) > 6:
23
print("Usage : node chatterbot.js <host> <port> [<name>]")
24
exit(1)
25
26
host = sys.argv[1]
27
port = sys.argv[2]
28
username = sys.argv[3] if len(sys.argv) > 3 else "boat"
29
30
bot = mineflayer.createBot({
31
"host": host,
32
"port": port,
33
"username": username
34
})
35
36
Item = require("prismarine-item")(bot.registry)
37
38
39
@On(bot, "chat")
40
def handle(this, username, message, *args):
41
if username == bot.username:
42
return
43
44
if message.startswith("can see"):
45
# Extract x, y and z
46
# e.g. "can see 327 60 -120" or "can see 327, -23, -120"
47
try:
48
x, y, z = map(lambda v: int(v), message.split("see")[1].replace(",", " ").split())
49
except Exception:
50
bot.chat("Bad syntax")
51
elif message.startswith("pos"):
52
say_position(username)
53
elif message.startswith("wearing"):
54
say_equipment(username)
55
elif message.startswith("block"):
56
say_block_under()
57
elif message.startswith("spawn"):
58
say_spawn()
59
elif message.startswith("quit"):
60
quit_game(username)
61
else:
62
bot.chat("That's nice")
63
64
65
def can_see(pos):
66
block = bot.blockAt(pos)
67
canSee = bot.canSeeBlock(block)
68
69
if canSee:
70
bot.chat(f"I can see the block of {block.displayName} at {pos}")
71
else:
72
bot.chat(f"I can't see the block of {block.displayName} at {pos}")
73
74
75
def say_position(username):
76
p = bot.entity.position
77
bot.chat(f"I am at {p.toString()}")
78
if username in bot.players:
79
p = bot.players[username].entity.position
80
bot.chat(f"You are at {p.toString()}")
81
82
83
def say_equipment(username):
84
eq = bot.players[username].entity.equipment
85
eqText = []
86
if eq[0]:
87
eqText.append(f"holding a {eq[0].displayName}")
88
if eq[1]:
89
eqText.append(f"wearing a {eq[1].displayName} on your feet")
90
if eq[2]:
91
eqText.append(f"wearing a {eq[2].displayName} on your legs")
92
if eq[3]:
93
eqText.append(f"wearing a {eq[3].displayName} on your torso")
94
if eq[4]:
95
eqText.append(f"wearing a {eq[4].displayName} on your head")
96
if len(eqText):
97
bot.chat(f"You are {', '.join(eqText)}.")
98
else:
99
bot.chat("You are naked!")
100
101
102
def say_spawn():
103
bot.chat(f"Spawn is at {bot.spawnPoint.toString()}")
104
105
106
def say_block_under():
107
block = bot.blockAt(bot.players[username].entity.position.offset(0, -1, 0))
108
bot.chat(f"Block under you is {block.displayName} in the {block.biome.name} biome")
109
print(block)
110
111
112
def quit_game(username):
113
bot.quit(f"{username} told me to")
114
115
116
def say_nick():
117
bot.chat(f"My name is {bot.player.displayName}")
118
119
120
@On(bot, "whisper")
121
def whisper(this, username, message, rawMessage, *a):
122
console.log(f"I received a message from {username}: {message}")
123
bot.whisper(username, "I can tell secrets too.")
124
125
126
@On(bot, "nonSpokenChat")
127
def nonSpokenChat(this, message):
128
console.log(f"Non spoken chat: {message}")
129
130
131
@On(bot, "login")
132
def login(this):
133
bot.chat("Hi everyone!")
134
135
136
@On(bot, "spawn")
137
def spawn(this):
138
bot.chat("I spawned, watch out!")
139
140
141
@On(bot, "spawnReset")
142
def spawnReset(this, message):
143
bot.chat("Oh noez! My bed is broken.")
144
145
146
@On(bot, "forcedMove")
147
def forcedMove(this):
148
p = bot.entity.position
149
bot.chat(f"I have been forced to move to {p.toString()}")
150
151
152
@On(bot, "health")
153
def health(this):
154
bot.chat(f"I have {bot.health} health and {bot.food} food")
155
156
157
@On(bot, "death")
158
def death(this):
159
bot.chat("I died x.x")
160
161
162
@On(bot, "kicked")
163
def kicked(this, reason, *a):
164
print("I was kicked", reason, a)
165
console.log(f"I got kicked for {reason}")
166
167
168
@On(bot, "time")
169
def time(this):
170
bot.chat(f"Current time: " + str(bot.time.timeOfDay))
171
172
173
@On(bot, "rain")
174
def rain(this):
175
if bot.isRaining:
176
bot.chat("It started raining")
177
else:
178
bot.chat("It stopped raining")
179
180
181
@On(bot, "noteHeard")
182
def noteHeard(this, block, instrument, pitch):
183
bot.chat(f"Music for my ears! I just heard a {instrument.name}")
184
185
186
@On(bot, "chestLidMove")
187
def chestLidMove(this, block, isOpen, *a):
188
action = "open" if isOpen else "close"
189
bot.chat(f"Hey, did someone just {action} a chest?")
190
191
192
@On(bot, "pistonMove")
193
def pistonMove(this, block, isPulling, direction):
194
action = "pulling" if isPulling else "pushing"
195
bot.chat(f"A piston is {action} near me, i can hear it.")
196
197
198
@On(bot, "playerJoined")
199
def playerJoined(this, player):
200
print("joined", player)
201
if player["username"] != bot.username:
202
bot.chat(f"Hello, {player['username']}! Welcome to the server.")
203
204
205
@On(bot, "playerLeft")
206
def playerLeft(this, player):
207
if player["username"] == bot.username:
208
return
209
bot.chat(f"Bye ${player.username}")
210
211
212
@On(bot, "playerCollect")
213
def playerCollect(this, collector, collected):
214
if collector.type == "player" and collected.type == "object":
215
raw_item = collected.metadata[10]
216
item = Item.fromNotch(raw_item)
217
header = ("I'm so jealous. " + collector.username) if (
218
collector.username != bot.username) else "I "
219
bot.chat(f"{header} collected {item.count} {item.displayName}")
220
221
222
@On(bot, "entitySpawn")
223
def entitySpawn(this, entity):
224
if entity.type == "mob":
225
p = entity.position
226
console.log(f"Look out! A {entity.displayName} spawned at {p.toString()}")
227
elif entity.type == "player":
228
bot.chat(f"Look who decided to show up: {entity.username}")
229
elif entity.type == "object":
230
p = entity.position
231
console.log(f"There's a {entity.displayName} at {p.toString()}")
232
elif entity.type == "global":
233
bot.chat("Ooh lightning!")
234
elif entity.type == "orb":
235
bot.chat("Gimme dat exp orb!")
236
237
238
@On(bot, "entityHurt")
239
def entityHurt(this, entity):
240
if entity.type == "mob":
241
bot.chat(f"Haha! The ${entity.displayName} got hurt!")
242
elif entity.type == "player":
243
if entity.username in bot.players:
244
ping = bot.players[entity.username].ping
245
bot.chat(f"Aww, poor {entity.username} got hurt. Maybe you shouldn't have a ping of {ping}")
246
247
248
@On(bot, "entitySwingArm")
249
def entitySwingArm(this, entity):
250
bot.chat(f"{entity.username}, I see that your arm is working fine.")
251
252
253
@On(bot, "entityCrouch")
254
def entityCrouch(this, entity):
255
bot.chat(f"${entity.username}: you so sneaky.")
256
257
258
@On(bot, "entityUncrouch")
259
def entityUncrouch(this, entity):
260
bot.chat(f"{entity.username}: welcome back from the land of hunchbacks.")
261
262
263
@On(bot, "entitySleep")
264
def entitySleep(this, entity):
265
bot.chat(f"Good night, {entity.username}")
266
267
268
@On(bot, "entityWake")
269
def entityWake(this, entity):
270
bot.chat(f"Top of the morning, {entity.username}")
271
272
273
@On(bot, "entityEat")
274
def entityEat(this, entity):
275
bot.chat(f"{entity.username}: OM NOM NOM NOMONOM. That's what you sound like.")
276
277
278
@On(bot, "entityAttach")
279
def entityAttach(this, entity, vehicle):
280
if entity.type == "player" and vehicle.type == "object":
281
print(f"Sweet, {entity.username} is riding that {vehicle.displayName}")
282
283
284
@On(bot, "entityDetach")
285
def entityDetach(this, entity, vehicle):
286
if entity.type == "player" and vehicle.type == "object":
287
print(f"Lame, {entity.username} stopped riding the {vehicle.displayName}")
288
289
290
@On(bot, "entityEquipmentChange")
291
def entityEquipmentChange(this, entity):
292
print("entityEquipmentChange", entity)
293
294
295
@On(bot, "entityEffect")
296
def entityEffect(this, entity, effect):
297
print("entityEffect", entity, effect)
298
299
300
@On(bot, "entityEffectEnd")
301
def entityEffectEnd(this, entity, effect):
302
print("entityEffectEnd", entity, effect)
303
304