Automatically read chat text from Minecraft

user1867827 picture user1867827 · Dec 1, 2012 · Viewed 7.1k times · Source

In Minecraft I was hoping to find a way to read the chat automatically like pictured below

minecraft chat screenshot

In order to record transactions made in the virtual shop into a PostgreSQL database. Preferably using Python. I do not own the Minecraft server.

My plan is to either find a way to directly read the packets sent from the Minecraft server (preferred for reliability, but of unknown difficulty) or as a backup plan maybe figure out how to screen scrape the text. I've found some resources that would let me change the font to monospaced which would provide a more reliable way to read in the font and I believe create perfectly consistent places on the screen for each character. I could face a direction that is close to black but not quite, but would prefer not to have to. As pictured above you see there are many different colors of font to contend with too.

Even after reducing it as described above, I'm still not sure how to turn it into text using python.

Any tips on my approach? Any hints at how I could read the packets coming from the server? Any tips on scraping the text from my screen?

Answer

user8354265 picture user8354265 · Mar 3, 2018

There’s in fact an even better way to read the chat from Minecraft, and it doesn’t require either screen scraping or packet decoding.

Minecraft automatically writes chat messages (and numerous other things) to log files, both in singleplayer and in multiplayer. On Windows, they are located in %appdata%/.minecraft/logs. Previous logs are compressed using gzip, but the latest session’s log is written to the text file latest.log in realtime. Chat messages contain the text [Client thread/INFO]: [CHAT]. You can either open it as you would with a normal file using:

import os
with open(os.getenv("APPDATA")+"/.minecraft/logs/latest.log", "r") as logfile:
    for line in logfile:
        if "[Client thread/INFO]: [CHAT]" in line:
            print line,

Or if you want to read chat in realtime, you can use the code below, slightly modified from the code from this answer:

import time, os

def follow(thefile):
    thefile.seek(0,2)
    while True:
        line = thefile.readline()
        if not line:
            time.sleep(0.1)
            continue
        yield line

if __name__ == "__main__":
    logfile = open(os.getenv("APPDATA")+"/.minecraft/logs/latest.log", "r")
    loglines = follow(logfile)
    for line in loglines:
        if "[Client thread/INFO]: [CHAT]" in line:
            print line,