0%

博德之门3自动荣耀

摘要

荣耀属于需要他的人(逃

  • F5 监听存档文件夹下的荣耀存档
  • Shift+ESC 退出脚本

Python脚本

  • 旧版使用15秒自动复制文件, 被群友嫌弃

  • 新版使用看门狗监听文件夹, 并自动根据Hash变化备份文件

  • 游戏存档文件位于

    • %localappdata%/Larian Studios/Baldur’s Gate 3/PlayerProfiles/Public/Savegames/Story
  • 默认备份文件于

    • %localappdata%/Larian Studios/Baldur’s Gate 3/PlayerProfiles/Public/Savegames/Story/BackupFiles/[备份时间]
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
#coding=utf-8
__doc__= u"""
使荣耀更加荣耀
"""

import sys, os
import time
import shutil
import itertools

import hashlib
from pynput import keyboard
from threading import Thread

import watchdog.events
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from watchdog.observers.api import BaseObserver

class HashHelper (object):

@classmethod
def calFileSha256(cls, filePath):
# type: (str) -> str
with open(filePath, "rb") as file:
file_hash = hashlib.sha256()
while chunk := file.read(1024 * 1024):
file_hash.update(chunk)
return file_hash.hexdigest()


class BG3AutoHonour (object):
playerProfileSavedPath = os.path.join (
os.environ["localappdata"],
"Larian Studios/Baldur's Gate 3/PlayerProfiles/Public/Savegames/Story"
).replace("\\","/")
playerBackupPath = os.path.join(playerProfileSavedPath, "BackupFiles").replace("\\","/")
waitSecond = 15

@classmethod
def autoBackup(cls):
print("Waiting for {}s".format(cls.waitSecond))
time.sleep(cls.waitSecond) # 强制等待, 确保存档已经创建

honourSavedFolderList = [] # type: list[str]
currentTime = time.strftime("%Y-%m-%d_%H-%M", time.localtime())
for curPath in os.listdir(cls.playerProfileSavedPath):
if ( not os.path.isdir(curPath)):
continue
if not curPath.endswith("__HonourMode"):
continue
honourSavedFolderList.append(curPath)

if not os.path.exists(cls.playerBackupPath):
os.mkdir(cls.playerBackupPath)

newBackupTargetFolder = os.path.join(cls.playerBackupPath,currentTime).replace("\\","/")
if not os.path.exists(newBackupTargetFolder):
os.mkdir(newBackupTargetFolder)

for folderPath in honourSavedFolderList:
targetFolder = os.path.join(newBackupTargetFolder, os.path.basename(folderPath)).replace("\\","/")
shutil.copytree(folderPath, targetFolder,
dirs_exist_ok=True, ignore_dangling_symlinks=True)
print("Backup to {}".format(targetFolder))

@classmethod
def listen(cls):

def shiftEsc():
print("Shift + Esc Pressed, Exit")
exit()

class KeyRecorder (object):
def __init__(self):
self.keyPressed = set() # type: set[keyboard.Key]

def onPress(self, key):
# type: (keyboard.Key) -> None
self.keyPressed.add(key)

def onRelease(self, key) :
# type: (keyboard.Key) -> None
keyCount=self.keyPressed.__len__()

if (keyCount == 1) and (keyboard.Key.f5 == key):
print("F5 Pressed")
cls.autoBackup()

if (keyCount == 2) and (keyboard.Key.esc in self.keyPressed) and (keyboard.Key.shift in self.keyPressed):
shiftEsc()

self.keyPressed.clear()

print (u"Current save path: {}".format(cls.playerProfileSavedPath))
print (u"Use hotkey F5 for honour!")

keyRecorder = KeyRecorder()
with keyboard.Listener(on_press=keyRecorder.onPress, on_release=keyRecorder.onRelease) as listener:
listener.join()


class BG3AutoHonourWatchdog(BG3AutoHonour):

@classmethod
def generateSaveFilePathHashDict(cls):
honourSavedFolderList = [] # type: list[str]
# NOTE: Use in save dir
for curPath in os.listdir(cls.playerProfileSavedPath):
if ( not os.path.isdir(curPath)):
continue
if not curPath.endswith("__HonourMode"):
continue
honourSavedFolderList.append(curPath)

# create hash dict
fileDict = dict() #type: dict[str,str]
for saveFolderPath in honourSavedFolderList:
folderName = os.path.join(cls.playerProfileSavedPath, saveFolderPath).replace("\\", "/")
savedFile = os.path.join(folderName, "HonourMode.lsv").replace("\\", "/")
hashValue = HashHelper.calFileSha256(savedFile)
print("File [{}], Hash [{}]".format(savedFile, hashValue))
fileDict[folderName] = hashValue

return fileDict


@classmethod
def autoBackup(cls, savedFilePath):
# type: (str)->None
currentTime = time.strftime("%Y-%m-%d_%H-%M", time.localtime())
print("Generate Time: {}".format(currentTime))
if not os.path.exists(cls.playerBackupPath):
os.mkdir(cls.playerBackupPath)

newBackupTargetFolder = os.path.join(cls.playerBackupPath, currentTime).replace("\\","/")
if not os.path.exists(newBackupTargetFolder):
os.mkdir(newBackupTargetFolder)

sourceFolderPath = savedFilePath
targetFolder = os.path.join(newBackupTargetFolder, os.path.basename(sourceFolderPath)).replace("\\","/")
shutil.copytree(sourceFolderPath, targetFolder, dirs_exist_ok=True, ignore_dangling_symlinks=True)
print("Backup to [{}]\r\n".format(targetFolder))
print("-" * 20)

@classmethod
def listen(cls):

def shiftEsc():
print("[Shift + Esc] Pressed, Exit")
exit()

class UserSavedFileWatchDog (object):
def __init__(self):
self._eventHandle = None
self._observer = None

def makeFolderWatching(self):
watchingPath = cls.playerProfileSavedPath
userSaveHashDict = cls.generateSaveFilePathHashDict()

class SaveChangedHandler(FileSystemEventHandler):

def __init__ (self, observer, *args, **kw):
# type: (BaseObserver, ..., ...)->None
self._observer = observer
super().__init__(*args, **kw)

def on_modified(self, event):
# type: (watchdog.events.FileModifiedEvent) -> None
sourcePath = event.src_path # type: str
changedFilePath = os.path.abspath(sourcePath).replace("\\", "/")
print("File path [{}] was modified".format(changedFilePath))

if changedFilePath in userSaveHashDict:
print("Found in hash dict, Checking hash value")
savedFile = os.path.join(changedFilePath, "HonourMode.lsv").replace("\\", "/")
try:
changedFileHash = HashHelper.calFileSha256(savedFile)
except FileNotFoundError :
time.sleep(5)
changedFileHash = HashHelper.calFileSha256(savedFile)
finally:
print("New File Hash: {}".format(changedFileHash))

if userSaveHashDict[changedFilePath] != changedFileHash:
print("File Hash was changed! Backup !")
BG3AutoHonourWatchdog.autoBackup(changedFilePath)
if self._observer:
self._observer.stop()

if self._observer == None:
self._observer = Observer()
observer = self._observer

if self._eventHandle == None:
self._eventHandle = SaveChangedHandler(observer)

observer.schedule(self._eventHandle, watchingPath, recursive=False)
print("Start watching : [{}]".format(watchingPath))
observer.start()

try:
while True:
time.sleep(1)
if not observer.is_alive():
break
except KeyboardInterrupt:
print("User Interrupt!")
observer.stop()

observer.join()
# NOTE: Reset to None
self._observer = self._eventHandle = None

class KeyRecorder (object):
def __init__(self):
self.keyPressed = set() # type: set[keyboard.Key]
self.watchDog = None
self.isWatching = False

def onPress(self, key):
# type: (keyboard.Key) -> None
self.keyPressed.add(key)

def onRelease(self, key) :
# type: (keyboard.Key) -> None
keyCount=self.keyPressed.__len__()

if (keyCount == 1) and (keyboard.Key.f5 == key):
print("F5 Pressed")
if self.watchDog == None:
self.watchDog = UserSavedFileWatchDog()

self.watchDog.makeFolderWatching()

if (keyCount == 2) and (keyboard.Key.esc in self.keyPressed) and (keyboard.Key.shift in self.keyPressed):
shiftEsc()

self.keyPressed.clear()

print (u"Current save path: [{}]".format(cls.playerProfileSavedPath))
print (u"Use hotkey [F5] for honour!\nUse hotkey [Shift+ESC] exit this script ...")

keyRecorder = KeyRecorder()
with keyboard.Listener(on_press=keyRecorder.onPress, on_release=keyRecorder.onRelease) as listener:
listener.join()


class ListenThread(Thread):

def __init__(self):
super().__init__()

def run(self):
BG3AutoHonourWatchdog.listen()


def runScript(*args, **kw):
listenThread = ListenThread()
listenThread.start()

if __name__ == "__main__":
runScript()

歡迎關注我的其它發布渠道