Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/examples/python/chatterbox.py
Views: 789
# ==========================================================================1# This example demonstrates how easy it is to create a bot2# that sends chat messages whenever something interesting happens3# on the server you are connected to.4#5# Below you can find a wide range of different events you can watch6# but remember to check out the API documentation to find even more!7#8# Some events may be commented out because they are very frequent and9# may flood the chat, feel free to check them out for other purposes though.10#11# This bot also replies to some specific chat messages so you can ask him12# a few information while you are in game.13# ===========================================================================14import sys, re15from javascript import require, On, Once, console1617mineflayer = require("mineflayer", "latest")18Vec3 = require("vec3").Vec31920print(sys.argv)21if len(sys.argv) < 3 or len(sys.argv) > 6:22print("Usage : node chatterbot.js <host> <port> [<name>]")23exit(1)2425host = sys.argv[1]26port = sys.argv[2]27username = sys.argv[3] if len(sys.argv) > 3 else "boat"2829bot = mineflayer.createBot({30"host": host,31"port": port,32"username": username33})3435Item = require("prismarine-item")(bot.registry)363738@On(bot, "chat")39def handle(this, username, message, *args):40if username == bot.username:41return4243if message.startswith("can see"):44# Extract x, y and z45# e.g. "can see 327 60 -120" or "can see 327, -23, -120"46try:47x, y, z = map(lambda v: int(v), message.split("see")[1].replace(",", " ").split())48except Exception:49bot.chat("Bad syntax")50elif message.startswith("pos"):51say_position(username)52elif message.startswith("wearing"):53say_equipment(username)54elif message.startswith("block"):55say_block_under()56elif message.startswith("spawn"):57say_spawn()58elif message.startswith("quit"):59quit_game(username)60else:61bot.chat("That's nice")626364def can_see(pos):65block = bot.blockAt(pos)66canSee = bot.canSeeBlock(block)6768if canSee:69bot.chat(f"I can see the block of {block.displayName} at {pos}")70else:71bot.chat(f"I can't see the block of {block.displayName} at {pos}")727374def say_position(username):75p = bot.entity.position76bot.chat(f"I am at {p.toString()}")77if username in bot.players:78p = bot.players[username].entity.position79bot.chat(f"You are at {p.toString()}")808182def say_equipment(username):83eq = bot.players[username].entity.equipment84eqText = []85if eq[0]:86eqText.append(f"holding a {eq[0].displayName}")87if eq[1]:88eqText.append(f"wearing a {eq[1].displayName} on your feet")89if eq[2]:90eqText.append(f"wearing a {eq[2].displayName} on your legs")91if eq[3]:92eqText.append(f"wearing a {eq[3].displayName} on your torso")93if eq[4]:94eqText.append(f"wearing a {eq[4].displayName} on your head")95if len(eqText):96bot.chat(f"You are {', '.join(eqText)}.")97else:98bot.chat("You are naked!")99100101def say_spawn():102bot.chat(f"Spawn is at {bot.spawnPoint.toString()}")103104105def say_block_under():106block = bot.blockAt(bot.players[username].entity.position.offset(0, -1, 0))107bot.chat(f"Block under you is {block.displayName} in the {block.biome.name} biome")108print(block)109110111def quit_game(username):112bot.quit(f"{username} told me to")113114115def say_nick():116bot.chat(f"My name is {bot.player.displayName}")117118119@On(bot, "whisper")120def whisper(this, username, message, rawMessage, *a):121console.log(f"I received a message from {username}: {message}")122bot.whisper(username, "I can tell secrets too.")123124125@On(bot, "nonSpokenChat")126def nonSpokenChat(this, message):127console.log(f"Non spoken chat: {message}")128129130@On(bot, "login")131def login(this):132bot.chat("Hi everyone!")133134135@On(bot, "spawn")136def spawn(this):137bot.chat("I spawned, watch out!")138139140@On(bot, "spawnReset")141def spawnReset(this, message):142bot.chat("Oh noez! My bed is broken.")143144145@On(bot, "forcedMove")146def forcedMove(this):147p = bot.entity.position148bot.chat(f"I have been forced to move to {p.toString()}")149150151@On(bot, "health")152def health(this):153bot.chat(f"I have {bot.health} health and {bot.food} food")154155156@On(bot, "death")157def death(this):158bot.chat("I died x.x")159160161@On(bot, "kicked")162def kicked(this, reason, *a):163print("I was kicked", reason, a)164console.log(f"I got kicked for {reason}")165166167@On(bot, "time")168def time(this):169bot.chat(f"Current time: " + str(bot.time.timeOfDay))170171172@On(bot, "rain")173def rain(this):174if bot.isRaining:175bot.chat("It started raining")176else:177bot.chat("It stopped raining")178179180@On(bot, "noteHeard")181def noteHeard(this, block, instrument, pitch):182bot.chat(f"Music for my ears! I just heard a {instrument.name}")183184185@On(bot, "chestLidMove")186def chestLidMove(this, block, isOpen, *a):187action = "open" if isOpen else "close"188bot.chat(f"Hey, did someone just {action} a chest?")189190191@On(bot, "pistonMove")192def pistonMove(this, block, isPulling, direction):193action = "pulling" if isPulling else "pushing"194bot.chat(f"A piston is {action} near me, i can hear it.")195196197@On(bot, "playerJoined")198def playerJoined(this, player):199print("joined", player)200if player["username"] != bot.username:201bot.chat(f"Hello, {player['username']}! Welcome to the server.")202203204@On(bot, "playerLeft")205def playerLeft(this, player):206if player["username"] == bot.username:207return208bot.chat(f"Bye ${player.username}")209210211@On(bot, "playerCollect")212def playerCollect(this, collector, collected):213if collector.type == "player" and collected.type == "object":214raw_item = collected.metadata[10]215item = Item.fromNotch(raw_item)216header = ("I'm so jealous. " + collector.username) if (217collector.username != bot.username) else "I "218bot.chat(f"{header} collected {item.count} {item.displayName}")219220221@On(bot, "entitySpawn")222def entitySpawn(this, entity):223if entity.type == "mob":224p = entity.position225console.log(f"Look out! A {entity.displayName} spawned at {p.toString()}")226elif entity.type == "player":227bot.chat(f"Look who decided to show up: {entity.username}")228elif entity.type == "object":229p = entity.position230console.log(f"There's a {entity.displayName} at {p.toString()}")231elif entity.type == "global":232bot.chat("Ooh lightning!")233elif entity.type == "orb":234bot.chat("Gimme dat exp orb!")235236237@On(bot, "entityHurt")238def entityHurt(this, entity):239if entity.type == "mob":240bot.chat(f"Haha! The ${entity.displayName} got hurt!")241elif entity.type == "player":242if entity.username in bot.players:243ping = bot.players[entity.username].ping244bot.chat(f"Aww, poor {entity.username} got hurt. Maybe you shouldn't have a ping of {ping}")245246247@On(bot, "entitySwingArm")248def entitySwingArm(this, entity):249bot.chat(f"{entity.username}, I see that your arm is working fine.")250251252@On(bot, "entityCrouch")253def entityCrouch(this, entity):254bot.chat(f"${entity.username}: you so sneaky.")255256257@On(bot, "entityUncrouch")258def entityUncrouch(this, entity):259bot.chat(f"{entity.username}: welcome back from the land of hunchbacks.")260261262@On(bot, "entitySleep")263def entitySleep(this, entity):264bot.chat(f"Good night, {entity.username}")265266267@On(bot, "entityWake")268def entityWake(this, entity):269bot.chat(f"Top of the morning, {entity.username}")270271272@On(bot, "entityEat")273def entityEat(this, entity):274bot.chat(f"{entity.username}: OM NOM NOM NOMONOM. That's what you sound like.")275276277@On(bot, "entityAttach")278def entityAttach(this, entity, vehicle):279if entity.type == "player" and vehicle.type == "object":280print(f"Sweet, {entity.username} is riding that {vehicle.displayName}")281282283@On(bot, "entityDetach")284def entityDetach(this, entity, vehicle):285if entity.type == "player" and vehicle.type == "object":286print(f"Lame, {entity.username} stopped riding the {vehicle.displayName}")287288289@On(bot, "entityEquipmentChange")290def entityEquipmentChange(this, entity):291print("entityEquipmentChange", entity)292293294@On(bot, "entityEffect")295def entityEffect(this, entity, effect):296print("entityEffect", entity, effect)297298299@On(bot, "entityEffectEnd")300def entityEffectEnd(this, entity, effect):301print("entityEffectEnd", entity, effect)302303304