Added some tools

- syntax validator for usernames
- syntax vaidator for UUIDs

GetPlayerData now accepts UUIDs too
This commit is contained in:
clerie 2018-10-28 15:07:58 +01:00
parent 6788cb3944
commit ff4f5da25c
4 changed files with 145 additions and 38 deletions

View File

@ -5,22 +5,41 @@ Getting Minecraft Player Information from Mojang API.
1. `pip install mcuuid` 1. `pip install mcuuid`
2. Use the module like this: 2. Use the module like this:
### API
``` ```
from mcuuid.api import GetPlayerData from mcuuid.api import GetPlayerData
player = GetPlayerData(username) player = GetPlayerData(identifier)
if player.valid is True: if player.valid is True:
uuid = player.uuid uuid = player.uuid
name = player.username name = player.username
``` ```
Read `test.py` for some explaination. Identifier can be a username or a UUID.
When `username = "gronkh"`: When `identifier = "gronkh"`:
`uuid` will be `"a2080281c2784181b961d99ed2f3347c"` `uuid` will be `"a2080281c2784181b961d99ed2f3347c"`
and `name` will be `"Gronkh"` and `name` will be `"Gronkh"`
### Tools
Syntax check of username
```
from mcuuid.tools import is_valid_minecraft_username
if is_valid_minecraft_username('gronkh'):
print('Valid')
```
Syntaxcheck of UUID
```
from mcuuid.tools import is_valid_mojang_uuid
if is_valid_mojang_uuid('a2080281c2784181b961d99ed2f3347c'):
print('Valid')
```
## Test file ## Test file
Usage Usage
``` ```
@ -28,10 +47,20 @@ $ python test.py gronkh
``` ```
or or
``` ```
$ python test.py a2080281c2784181b961d99ed2f3347c
```
or
```
$ python test.py $ python test.py
Please enter a username: Please enter a username or UUID:
gronkh gronkh
``` ```
or
```
$ python test.py
Please enter a username or UUID:
a2080281c2784181b961d99ed2f3347c
```
Response: Response:
``` ```

View File

@ -7,11 +7,12 @@ Uses the official Mojang API to fetch player data.
### Import necessary modules ### Import necessary modules
import http.client import http.client
import json import json
from tools import is_valid_minecraft_username
from tools import is_valid_mojang_uuid
### Main class ### Main class
class GetPlayerData: class GetPlayerData:
def __init__(self, username, timestamp=None): def __init__(self, identifier, timestamp=None):
self.valid = True self.valid = True
""" """
Get the UUID of the player. Get the UUID of the player.
@ -29,20 +30,53 @@ class GetPlayerData:
if timestamp is not None: if timestamp is not None:
get_args = "?at=" + str(timestamp) get_args = "?at=" + str(timestamp)
# Request the UUID req = ""
http_conn = http.client.HTTPSConnection("api.mojang.com"); if is_valid_minecraft_username(identifier):
http_conn.request("GET", "/users/profiles/minecraft/" + username + get_args, req = "/users/profiles/minecraft/" + identifier + get_args
headers={'User-Agent':'https://github.com/clerie/mcuuid', 'Content-Type':'application/json'}); elif is_valid_mojang_uuid(identifier):
response = http_conn.getresponse().read().decode("utf-8") req = "/user/profiles/" + identifier + "/names" + get_args
# 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: else:
# Parse the JSON self.valid = False
json_data = json.loads(response)
# The UUID if self.valid:
self.uuid = json_data['id'] # Request the UUID
# The username written correctly http_conn = http.client.HTTPSConnection("api.mojang.com");
self.username = json_data['name'] http_conn.request("GET", req,
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)
if is_valid_minecraft_username(identifier):
# The UUID
self.uuid = json_data['id']
# The username written correctly
self.username = json_data['name']
elif is_valid_mojang_uuid(identifier):
# The UUID
self.uuid = identifier
if timestamp is None:
timestamp = 0
current_name = ""
current_time = 0
# Getting the current username
for name in json_data:
if 'changedToAt' in name:
changed_to_at = name['changedToAt']
else:
changed_to_at = 0
if changed_to_at <= timestamp and current_time <= changed_to_at:
current_time = changed_to_at
current_name = name['name']
# The username written correctly
self.username = name['name']

31
mcuuid/tools.py Normal file
View File

@ -0,0 +1,31 @@
def is_valid_minecraft_username(username):
"""https://help.mojang.com/customer/portal/articles/928638-minecraft-usernames"""
allowed_chars = 'abcdefghijklmnopqrstuvwxyz1234567890_'
allowed_len = [3, 16]
username = username.lower()
if len(username) < allowed_len[0] or len(username) > allowed_len[1]:
return False
for char in username:
if char not in allowed_chars:
return False
return True
def is_valid_mojang_uuid(uuid):
"""https://minecraft-de.gamepedia.com/UUID"""
allowed_chars = '0123456789abcdef'
allowed_len = 32
uuid = uuid.lower()
if len(uuid) != 32:
return False
for char in uuid:
if char not in allowed_chars:
return False
return True

45
test.py
View File

@ -1,5 +1,7 @@
### Import our module ### Import our module
from mcuuid.api import GetPlayerData from mcuuid.api import GetPlayerData
from mcuuid.tools import is_valid_minecraft_username
from mcuuid.tools import is_valid_mojang_uuid
### Import some other necessary modules ### Import some other necessary modules
import sys import sys
@ -7,24 +9,35 @@ import sys
### Which username should we use? ### Which username should we use?
# Are there some arguments brought by the console use the first after the filename as username # Are there some arguments brought by the console use the first after the filename as username
if len(sys.argv) > 1: if len(sys.argv) > 1:
username = sys.argv[1] identifier = sys.argv[1]
# Else, ask for a username by userinput # Else, ask for a username by userinput
else: else:
print("Please enter a username: ") print("Please enter a username or UUID: ")
username = raw_input() identifier = raw_input()
### Obtaining the playerinformation using our module if is_valid_minecraft_username(identifier) or is_valid_mojang_uuid(identifier):
player = GetPlayerData(username) if is_valid_minecraft_username(identifier):
# Check if the request was valid and the user exists print('Valid username')
if player.valid is True: if is_valid_mojang_uuid(identifier):
# Getting UUID print('Valid UUID')
uuid = player.uuid
# Getting real Username ### Obtaining the playerinformation using our module
name = player.username player = GetPlayerData(identifier)
# 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
# Print everything
print('UUID: ' + uuid)
print('correct name: ' + name)
# Error message
else:
print("That player was not found.")
# Print everything
print('UUID: ' + uuid)
print('correct name: ' + name)
# Error message
else: else:
print("That player was not found.") print('identifier is not valid')