-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
297 lines (260 loc) · 11.6 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import json
import os
from typing import List
from psapi import EnumProcessModulesEx, GetModuleFileNameEx
from ReadWriteMemory import ReadWriteMemory, ReadWriteMemoryError
from time import sleep
import threading
import tkinter as tk
from tkinter import Button, Label
from tkinter import ttk
from ctypes import *
from uwp import get_minecraft_version
import requests
# Based on https://github.com/randomdavis/process_interface.py/blob/main/process_interface.py
class Memory:
def __init__(self, process):
self.process = process
def write(self, address, data, buffer_size=4):
try:
count = c_ulong(0)
c_int(0)
if not windll.kernel32.WriteProcessMemory(self.process.handle, address, byref(data), buffer_size,
byref(count)):
print("Failed: Write Memory - Error Code: ", FormatError(windll.kernel32.GetLastError()))
windll.kernel32.SetLastError(10000)
else:
return False
except (BufferError, ValueError, TypeError) as error:
print("Failed: Read Memory #2 - Error Code: ", windll.kernel32.GetLastError())
return False
def read(self, address, buffer_size=4):
try:
buf = create_string_buffer(buffer_size)
bytes_read = c_ulong(0)
if windll.kernel32.ReadProcessMemory(self.process.handle, address, buf, buffer_size, byref(bytes_read)):
return buf
else:
print("Failed: Read Memory - Error Code: ", windll.kernel32.GetLastError())
return False
except (BufferError, ValueError, TypeError) as error:
print("Failed: Read Memory #2 - Error Code: ", windll.kernel32.GetLastError())
return False
def get_pointer(self, base_address: int, offsets: List[hex] = ()):
temp_address = c_uint64.from_buffer(self.read(c_uint64(base_address), 8)).value
pointer = 0x0
if not offsets:
return base_address
else:
for offset in offsets:
pointer = c_uint64(int(temp_address) + offset)
temp_address = c_uint64.from_buffer(self.read(pointer, 8)).value
return pointer
class KeybindsChanger:
def __init__(self, use_gui=True):
self.prepare_dirs()
self.module_name = None
self.module_base = None
self.pointers_offset = None
self.searching_for_process = False
self.pointer_map = {}
self.process = None
self.use_gui = use_gui
self.selected_profile = None
self.profiles_list = {'values': []}
self.status_label = {'text': ''}
self.memory = None
self.start_process_search()
self.buttons = []
self.profiles = {}
if use_gui:
self.init_gui()
def init_gui(self):
window = tk.Tk()
window.title('Minecraft Keybinds Switcher')
window.geometry('330x520')
window.resizable(width=False, height=False)
self.status_label = Label(window, text='Searching for Minecraft', width=16)
self.status_label.grid(row=1, column=1, columnspan=2, ipadx=105, ipady=20, sticky='n')
Label(window, text='Profile:').grid(row=2, column=1, pady=5, sticky='e')
self.selected_profile = tk.StringVar()
self.profiles_list = ttk.Combobox(window, width=27, textvariable=self.selected_profile)
self.load_profiles()
self.profiles_list.grid(row=2, column=2, pady=5)
Button(window, text='SAVE CURRENT', width=38, command=self.save_current_as_profile).grid(row=4, column=1,
columnspan=2, pady=5)
Button(window, text='APPLY', width=38, command=self.apply_profile).grid(row=5, column=1,
columnspan=2)
delete_btn_id = 0
for slot_id in range(9):
slot = Label(window, text=f'SLOT {slot_id + 1}: X', font=1)
slot.grid(row=6 + slot_id, column=1, columnspan=2, pady=5)
self.buttons.append(slot)
delete_btn_id = slot_id + 7
Button(window, text='DELETE SELECTED', width=38, command=self.delete_current_profile).grid(row=delete_btn_id,
column=1,
columnspan=2,
pady=14)
window.mainloop()
def start_process_search(self):
if self.searching_for_process:
return
self.searching_for_process = True
threading.Thread(target=self.load_pointer_map, daemon=True).start()
def prepare_dirs(self):
if not os.path.exists('./profiles'):
os.mkdir('./profiles')
def load_profiles(self):
self.profiles = {}
for file in os.listdir('./profiles'):
filename = os.fsdecode(file)
if filename.endswith(".json"):
with open(f'./profiles/{filename}') as profile_file:
data = json.load(profile_file)
self.profiles.update({filename: data})
self.profiles_list['values'] = [x['Name'] for x in self.profiles.values()]
continue
else:
continue
def save_current_as_profile(self):
name = self.selected_profile.get()
if not name:
return
profile = {'Name': name}
filename = name.lower()
for slot_id in range(9):
slot = int(c_int32.from_buffer(self.memory.read(self.pointer_map[slot_id], 4)).value)
profile.update({f'Slot{slot_id + 1}': slot})
with open(f'./profiles/{filename}.json', 'w', encoding='utf-8') as f:
json.dump(profile, f, ensure_ascii=False, indent=4)
self.load_profiles()
def get_current_profile(self):
try:
return [(x, y) for x, y in zip(self.profiles.values(),
self.profiles.items()) if x['Name'] == self.selected_profile.get()][0]
except (IndexError, KeyError):
return False
def delete_current_profile(self):
try:
profile = self.get_current_profile()
if not profile:
print('NO PROFILE SELECTED')
return
file_to_delete = self.get_current_profile()[1][0]
path = f'./profiles/{file_to_delete}'
os.remove(path)
self.selected_profile.set('')
self.load_profiles()
except (IndexError, KeyError, FileNotFoundError):
print('DELETE ERROR')
def apply_profile(self):
try:
current_profile = self.get_current_profile()[0]
current_profile = list(current_profile.values())[1:]
for slot_id in range(9):
self.memory.write(self.pointer_map[slot_id], c_int32(current_profile[slot_id]), 4)
self.update_values()
except (IndexError, KeyError):
print('APPLY ERROR')
def update_values(self):
if not self.use_gui:
return
profile = self.get_current_profile()
current_profile = None
if profile:
current_profile = self.get_current_profile()[0]
current_profile = list(current_profile.values())[1:]
for slot_id in range(9):
slot = int(c_int32.from_buffer(self.memory.read(self.pointer_map[slot_id], 4)).value)
btn = f'MB{slot + 100}' if slot < 0 else chr(slot)
to_btn = ''
if current_profile:
to_slot = current_profile[slot_id]
if to_slot != slot:
to_btn = ' => ' + (f'MB{to_slot + 100}' if to_slot < 0 else chr(to_slot))
self.buttons[slot_id]['text'] = f'SLOT {slot_id + 1}: {btn}{to_btn}'
def realtime_values_update(self):
while True:
try:
self.update_values()
sleep(1)
except:
self.status_label['text'] = "Searching for Minecraft"
self.start_process_search()
break
def load_pointer_map(self):
url = 'https://raw.githubusercontent.com/FreezeEngine/bedrock-keybinds-map/main/memory_maps.json'
try:
response = requests.get(url)
if response.status_code == 200:
data = response.json()
# Используем ключ версии игры вместо названия файла
minecraft_version = get_minecraft_version()
if minecraft_version in data:
version_data = data[minecraft_version]
base_struct = version_data['BaseAddress'].split('+')
self.module_name = base_struct[0]
self.initiate_connection(version_data, base_struct)
else:
print('Version not supported!')
self.status_label['text'] = "Unsupported version!"
else:
print('Failed to fetch memory map:', response.status_code)
self.status_label['text'] = "Failed to fetch memory map!"
except Exception as e:
print('Error occurred while loading memory map:', str(e))
self.status_label['text'] = "Error loading memory map!"
def initiate_connection(self, data, base_struct):
# Find process
rwm = ReadWriteMemory()
while True:
try:
process = rwm.get_process_by_name(self.module_name)
process.open()
break
except ReadWriteMemoryError:
sleep(3)
pass
self.status_label['text'] = "Attached to Minecraft"
self.searching_for_process = False
self.process = process
self.memory = Memory(process)
# Load modules
for handle in EnumProcessModulesEx(self.process.handle):
module_base = int(handle.value) # base addr
module_name = os.path.basename(
GetModuleFileNameEx(self.process.handle, handle)) # name
# print({module_name: module_base})
if module_name == self.module_name:
self.module_base = module_base
break
if not self.module_base:
print('FAILED TO FIND MODULE')
return
# Calculate base
self.pointers_offset = int(base_struct[1], 16)
self.pointer_map = []
start_pointer_address = self.module_base + self.pointers_offset
# read pointers
data = list(data.values())[1:]
for slot_id in range(9):
offsets_obj = []
offsets = data[slot_id].split(',')
for offset in offsets:
offsets_obj.append(int(offset, 16))
errors = 0
error_limit = 4
while True:
try:
errors += 1
pointer = self.memory.get_pointer(start_pointer_address, offsets=offsets_obj)
break
except:
if errors == error_limit:
print('Failed to load pointers, restart required.')
return
sleep(5)
self.pointer_map.append(pointer)
threading.Thread(target=self.realtime_values_update, daemon=True).start()
if __name__ == '__main__':
mkc = KeybindsChanger()