Rewrite class construction, usage, test and readme.

Added correct name support.
This commit is contained in:
clerie 2018-10-28 12:02:55 +01:00
parent ec6099421b
commit 0963e78b4b
4 changed files with 108 additions and 62 deletions

View File

@ -1,20 +1,43 @@
# Minecraft Username to UUID
Convert old Minecraft usernames to their UUID.
Written for Python3.
# MCUUID
Getting Minecraft Player Information from Mojang API.
## Usage
1. Add the username_to_uuid.py file to your Python path.
2. Use the library like this:
```
from username_to_uuid import UsernameToUUID
1. Add the mcuuid.py file to your Python path.
2. Use the module like this:
converter = UsernameToUUID("MrLolEthan")
uuid = converter.get_uuid()
... # Do stuff
```
The contents of `uuid` will now be:
`854dd5e0fe044568a787053417ea6335`
from mcuuid import GetPlayerData
player = GetPlayerData(username)
if player.valid is True:
uuid = player.uuid
name = player.username
```
Read `test.py` for some explaination.
When `username = "gronkh"`:
`uuid` will be `"a2080281c2784181b961d99ed2f3347c"`
and `name` will be `"Gronkh"`
## Test file
Usage
```
$ python test.py gronkh
```
or
```
$ python test.py
Please enter a username:
gronkh
```
Response:
```
UUID: a2080281c2784181b961d99ed2f3347c
correct name: Gronkh
```
## License
This software is licensed under the MIT license. Feel free to use it however you like.

48
mcuuid.py Normal file
View File

@ -0,0 +1,48 @@
""" Username to UUID
Converts a Minecraft username to it's UUID equivalent.
Uses the official Mojang API to fetch player data.
"""
### Import necessary modules
import http.client
import json
### Main class
class GetPlayerData:
def __init__(self, username, timestamp=None):
self.valid = True
"""
Get the UUID of the player.
Parameters
----------
username: string
The known minecraft username
timestamp : long integer (optional)
The time at which the player used this name, expressed as a Unix timestamp.
"""
# Handle the timestamp
get_args = ""
if timestamp is not None:
get_args = "?at=" + str(timestamp)
# Request the UUID
http_conn = http.client.HTTPSConnection("api.mojang.com");
http_conn.request("GET", "/users/profiles/minecraft/" + username + get_args,
headers={'User-Agent':'https://github.com/clerie/mcuuid', 'Content-Type':'application/json'});
response = http_conn.getresponse().read().decode("utf-8")
# In case the answer is empty, the user dont exist
if not response:
self.valid = False
# If there is an answer, fill out the variables
else:
# Parse the JSON
json_data = json.loads(response)
# The UUID
self.uuid = json_data['id']
# The username written correctly
self.username = json_data['name']

32
test.py
View File

@ -1,14 +1,30 @@
from username_to_uuid import UsernameToUUID
### Import our module
from mcuuid import GetPlayerData
### Import some other necessary modules
import sys
### Which username should we use?
# Are there some arguments brought by the console use the first after the filename as username
if len(sys.argv) > 1:
username = sys.argv[1]
# Else, ask for a username by userinput
else:
print("Please enter a username: ")
username = raw_input()
print("Please enter a username: ")
username = sys.stdin.readline().rstrip()
### Obtaining the playerinformation using our module
player = GetPlayerData(username)
# Check if the request was valid and the user exists
if player.valid is True:
# Getting UUID
uuid = player.uuid
# Getting real Username
name = player.username
converter = UsernameToUUID(username)
uuid = converter.get_uuid()
if (uuid is not ""):
print("That player's UUID is: " + uuid)
# Print everything
print('UUID: ' + uuid)
print('correct name: ' + name)
# Error message
else:
print("That player was not found.")

View File

@ -1,41 +0,0 @@
""" Username to UUID
Converts a Minecraft username to it's UUID equivalent.
Uses the official Mojang API to fetch player data.
"""
import http.client
import json
class UsernameToUUID:
def __init__(self, username):
self.username = username
def get_uuid(self, timestamp=None):
"""
Get the UUID of the player.
Parameters
----------
timestamp : long integer
The time at which the player used this name, expressed as a Unix timestamp.
"""
get_args = "" if timestamp is None else "?at=" + str(timestamp)
http_conn = http.client.HTTPSConnection("api.mojang.com");
http_conn.request("GET", "/users/profiles/minecraft/" + self.username + get_args,
headers={'User-Agent':'Minecraft Username -> UUID', 'Content-Type':'application/json'});
response = http_conn.getresponse().read().decode("utf-8")
if (not response and timestamp is None): # No response & no timestamp
return self.get_uuid(0) # Let's retry with the Unix timestamp 0.
if (not response): # No response (player probably doesn't exist)
return ""
json_data = json.loads(response)
try:
uuid = json_data['id']
except KeyError as e:
print("KeyError raised:", e);
return uuid