Skip to content

Commit

Permalink
implemented websockets
Browse files Browse the repository at this point in the history
  • Loading branch information
OwOHamper committed Jul 7, 2022
1 parent d4d69fc commit 6012e7b
Show file tree
Hide file tree
Showing 6 changed files with 99 additions and 30 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -148,4 +148,5 @@ logs/

env/
tempCodeRunnerFile.py
vRY.lnk
vRY.lnk
node_modules
41 changes: 36 additions & 5 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import time
from prettytable import PrettyTable
from alive_progress import alive_bar
import asyncio

from src.constants import *
from src.requests import Requests
Expand Down Expand Up @@ -81,7 +82,10 @@ def program_exit(status: int): # so we don't need to import the entire sys modu

stats = Stats()

Wss = Ws(Requests.lockfile)
Wss = Ws(Requests.lockfile, Requests)
# loop = asyncio.new_event_loop()
# asyncio.set_event_loop(loop)
# loop.run_forever()

log(f"VALORANT rank yoinker v{version}")

Expand All @@ -94,14 +98,40 @@ def program_exit(status: int): # so we don't need to import the entire sys modu
lastGameState = ""

print(color("\nVisit https://vry.netlify.app/matchLoadouts to view full player inventories\n", fore=(255, 253, 205)))


# loop = asyncio.new_event_loop()
# asyncio.set_event_loop(loop)
# loop.run_until_complete(Wss.conntect_to_websocket(game_state))
# loop.close()
firstTime = True
while True:
table.clear()
try:
presence = presences.get_presence()
game_state = presences.get_game_state(presence)


# loop = asyncio.get_event_loop()
# loop.run_until_complete(Wss.conntect_to_websocket())
# if firstTime:
# loop = asyncio.new_event_loop()
# asyncio.set_event_loop(loop)
# game_state = loop.run_until_complete(Wss.conntect_to_websocket(game_state))
if firstTime:
presence = presences.get_presence()
game_state = presences.get_game_state(presence)
else:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
game_state = loop.run_until_complete(Wss.recconect_to_websocket(game_state))
loop.close()
firstTime = False
# loop = asyncio.new_event_loop()
# asyncio.set_event_loop(loop)
# loop.run_until_complete()
except TypeError:
raise Exception("Game has not started yet!")
if cfg.cooldown == 0 or game_state != lastGameState:
# if cfg.cooldown == 0 or game_state != lastGameState:
if True:
log(f"getting new {game_state} scoreboard")
lastGameState = game_state
game_state_dict = {
Expand Down Expand Up @@ -460,7 +490,8 @@ def program_exit(status: int): # so we don't need to import the entire sys modu
if cfg.cooldown == 0:
input("Press enter to fetch again...")
else:
time.sleep(cfg.cooldown)
# time.sleep(cfg.cooldown)
pass
except:
log(traceback.format_exc())
print(color(
Expand Down
1 change: 1 addition & 0 deletions src/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def get_all_agents(self):
rAgents = requests.get("https://valorant-api.com/v1/agents?isPlayableCharacter=true").json()
agent_dict = {}
agent_dict.update({None: None})
agent_dict.update({"": ""})
for agent in rAgents["data"]:
agent_dict.update({agent['uuid'].lower(): agent['displayName']})
self.log(f"retrieved agent dict: {agent_dict}")
Expand Down
1 change: 0 additions & 1 deletion src/presences.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import json
import time


class Presences:
def __init__(self, Requests, log):
self.Requests = Requests
Expand Down
1 change: 0 additions & 1 deletion src/server.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import asyncio
import json
from websocket_server import WebsocketServer
from threading import Thread
Expand Down
82 changes: 60 additions & 22 deletions src/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,44 +6,82 @@
import json

class Ws:
def __init__(self, lockfile):
def __init__(self, lockfile, Requests):

self.lockfile = lockfile

self.Requests = Requests
# websocket.enableTrace(True)
self.ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
self.ssl_context.check_hostname = False
self.ssl_context.verify_mode = ssl.CERT_NONE

async def conntect_to_websocket(self):
async def conntect_to_websocket(self, initial_game_state):


local_headers = {}
local_headers['Authorization'] = 'Basic ' + base64.b64encode(('riot:' + self.lockfile['password']).encode()).decode()
url = f"wss://127.0.0.1:{self.lockfile['port']}"
async with websockets.connect(url, ssl=self.ssl_context, extra_headers=local_headers) as websocket:
self.websocket_client = websockets.connect(url, ssl=self.ssl_context, extra_headers=local_headers)
async with self.websocket_client as websocket:
await websocket.send('[5, "OnJsonApiEvent_chat_v4_presences"]')
while True:
response = await websocket.recv()
if len(response) > 10:
presence = json.loads(response[38:-1])
print(presence["data"]["presences"])

return None
# while True:
# response = await websocket.recv()
# h = self.handle(response, initial_game_state)
# if h is not None:
# return h


async def recconect_to_websocket(self, initial_game_state):
#wont actually recconect :)
local_headers = {}
local_headers['Authorization'] = 'Basic ' + base64.b64encode(('riot:' + self.lockfile['password']).encode()).decode()
url = f"wss://127.0.0.1:{self.lockfile['port']}"
self.websocket_client = websockets.connect(url, ssl=self.ssl_context, extra_headers=local_headers)
async with self.websocket_client as websocket:
await websocket.send('[5, "OnJsonApiEvent_chat_v4_presences"]')
while True:
response = await websocket.recv()
h = self.handle(response, initial_game_state)
if h is not None:
await websocket.close()
return h

def handle(self, m, initial_game_state):
if len(m) > 10:
presence = json.loads(m[38:-1])
n_presence = presence["data"]["presences"][0]
# print(n_presence)
# print(type(n_presence))
if n_presence['puuid'] == self.Requests.puuid:
# if n_presence['puuid'] == "963ad672-61e1-537e-8449-06ece1a5ceb7":
# #preventing vry from crashing when lol is open
# print(presence)
# print(presence.get("championId"))
if n_presence.get("championId") is not None or n_presence.get("product") == "league_of_legends":
state = None
else:
state = json.loads(base64.b64decode(n_presence['private']))["sessionLoopState"]

if state is not None:
if state != initial_game_state:
return state

if __name__ == "__main__":
try:
with open(os.path.join(os.getenv('LOCALAPPDATA'), R'Riot Games\Riot Client\Config\lockfile')) as lockfile:
data = lockfile.read().split(':')
keys = ['name', 'PID', 'port', 'password', 'protocol']
lockfile = dict(zip(keys, data))
except:
raise Exception("Lockfile not found")
# if __name__ == "__main__":
# try:
# with open(os.path.join(os.getenv('LOCALAPPDATA'), R'Riot Games\Riot Client\Config\lockfile')) as lockfile:
# data = lockfile.read().split(':')
# keys = ['name', 'PID', 'port', 'password', 'protocol']
# lockfile = dict(zip(keys, data))
# except:
# raise Exception("Lockfile not found")


ws = Ws(lockfile)
# loop = asyncio.get_event_loop()
# loop.run_until_complete(ws.conntect_to_websocket())
asyncio.run(ws.conntect_to_websocket())
# ws = Ws(lockfile, "MENUS")
# loop = asyncio.new_event_loop()
# asyncio.set_event_loop(loop)
# loop.run_until_complete(ws.conntect_to_websocket("MENUS"))
# loop = asyncio.new_event_loop()
# asyncio.set_event_loop(loop)
# loop.run_forever()

0 comments on commit 6012e7b

Please sign in to comment.