3

Hello kind folks of StackOverflow.

I am trying to make a sort of 'bot' which can connect to a Minecraft Classic server, post messages and possibly build.

Anyway, I'm having some trouble understanding how to send packets in python, and how to correctly encode them.

Here are the packets I need to send, I want to send the 'Player Identification' one: http://www.minecraftwiki.net/wiki/Classic_server_protocol#Client_.E2.86.92_Server_packets I know I need to be using sockets, and I need to be using struct.pack, but how exactly can I send it?

An example piece code that sends a login packet would be marvellous.

Thanks.

Jack
  • 740
  • 5
  • 21

1 Answers1

4

I'll get the ball rolling:

import socket
import struct

username = "username_value"
verification_key = "verification_key"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # boilerplate
s.connect(("example.com", 1234))  # adjust accordingly

# now for the packet
# note that the String type is specified as having a length of 64, we'll pad that

packet = ""

packet += struct.pack("B", 1)  # packet type
packet += struct.pack("B", 7)  # protocol version
packet += "%-64s" % username  # magic!
packet += "%-64s" % verification_key
packet += struct.pack("B", 0)  # that unused byte, assuming a NULL byte here

# send what we've crafted
s.send(packet)

The "%-20s" may be weird for you if you've never used format strings. Essentially..

print "%s" % 5

.. would print out 5 ..

print "%10s" % 5

.. would pad the output to be exactly 10 characters in width. But it pads them on the right side, we want that padding on the left -- hence the - ..

print "%-10s" % s, "<this will be 9 spaces away from the '5'>"

.. play around with it.

If anything is unclear, let me know. I like what you're doing, reminds me of an old project of mine. Except that I didn't have a neat protocol specification like you did, lucky bastard. ;)

ntl0ve
  • 1,896
  • 3
  • 19
  • 25
  • 2
    Thanks so much for this! This is exactly what I wanted, couldn't have been more helpful. – Jack Mar 01 '12 at 18:40
  • Hello, can you please help me? When i try to connect to MC Classic Server, it gives me error response `Incompatible client, or a network error.`. What should i do? – JadedTuna Aug 20 '13 at 10:10