https://s3-us-west-2.amazonaws.com/secure.notion-static.com/e1133ba9-69ec-4960-96cd-a3a811df57a8/01-herobrine-has-joined.png

Troll friends on your server by posting random messages to the in-game chat from an external text file.

Learning objectives:

This is a simple program that takes advantage of Python’s ability to read a text file outside of your main program. Here’s a list of all the things we want our new program to do:

# Minecraft Whispers
# Pipes a randomly selected line from a text file to Minecraft chat at randomly selected times.
# Jim Christian
# CodinginMinecraft.com

#import the relevant modules for Minecraft, handling time and random numbers
import mcpi.minecraft as minecraft
import time
import random

# (Optional) define a custom function to shorten our calls to mc.postToChat
def chat(msg):
    mc.postToChat(msg)

# True is *always* True. So therefore the following code will run until it is terminated.
while True:
    #create a connection to the Minecraft game
     mc = minecraft.Minecraft.create()

     # Pick a random number between 0 and 9. This is how often the following code will execute.
     time.sleep(random.randint(0,9))

     # Define the whisper variable as a random line from the whispers.txt file
     whisper = random.choice(open('whispers.txt', 'r').readlines())

     # Output that random line to in-game chat.
     chat(whisper[:-1])