forked from coderwilson/FFX_TAS_Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwitch_bot.py
348 lines (317 loc) · 12.4 KB
/
twitch_bot.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
from twitchio.ext import commands
import subprocess
import random
import os
import json
import time
import yaml
import logging
from typing import Dict
logger = logging.getLogger(__name__)
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
# Define the path to the Python script to run
SCRIPT_PATH = "main.py"
CHOCO_PATH = "z_choco_races_test.py"
BLITZ_PATH = "x_blitz_only.py"
CSR_PATH = ""
GAME_PATH = ""
CONFIG_FILE_PATH = "bot-config.yaml"
def oblitz_history():
filepath = os.path.join("json_ai_files", "oblitz_results.json")
with open(filepath, "r") as fp:
rng_values = json.load(fp)
return rng_values
class BotConfig:
def __init__(self, config_path: str):
self.data = {}
# Open the config file and parse the yaml contents
try:
with open(config_path) as config_file:
try:
self.data = yaml.load(config_file, Loader=Loader)
except Exception as E:
logger.error(f"Error: Failed to parse config file {config_path}")
logger.exception(E)
except Exception:
logger.info(f"Didn't find config file {config_path}, using default values.")
# Define the bot
class Bot(commands.Bot):
def __init__(self, config: Dict):
token: str = config.get("token", "YOUR_TOKEN_HERE")
channels: str = config.get("channels", ["YOUR_CHANNEL_NAME"])
# Define the users who are allowed to send commands
self.allowed_users = config.get("allowed_users", ["YOUR_CHANNEL_NAME"])
super().__init__(token=token, prefix="!", initial_channels=channels)
self.process = None
self.csr = None
self.game = None
self.timer = None
def is_valid_user(self, ctx: commands.Context):
if ctx.author.is_mod or ctx.author.name in self.allowed_users:
return True
else:
return True
#await ctx.send(
ctx.send(
f"Sorry {ctx.author.name}, you don't have permissions to execute this."
)
return False
async def event_ready(self):
# Notify when we are logged in and ready to use commands
print(f"Logged in as {self.nick}")
print(f"User id is {self.user_id}")
print("Ready for commands")
# Define the start command
@commands.command(aliases=("begin", "launch"))
async def start(self, ctx: commands.Context):
arg_array = []
print(ctx.message.content)
args = ctx.message.content.split()
print(args)
seed_set = False
records = oblitz_history()
seed_num = str(random.choice(range(256)))
reroll = 0
print(records.keys())
while seed_num in records.keys() and reroll < 1000:
seed_num = str(random.choice(range(256)))
reroll += 1
for i in range(len(args)):
try:
if args[i].lower() == "seed":
arg_array.append("-seed")
seed_num = str(args[i + 1])
print(f"Specified Seed: {seed_num}")
seed_set = True
arg_array.append(seed_num)
if args[i].lower() == "state":
arg_array.append("-state")
arg_array.append(args[i + 1])
if args[i].lower() == "step":
arg_array.append("-step")
arg_array.append(args[i + 1])
if args[i].lower() == "blitz":
arg_array.append("-train_blitz")
arg_array.append("True")
if args[i].lower() == "godrng":
arg_array.append("-godrng")
arg_array.append("True")
except Exception:
await ctx.send(
f"There was an error with your command: {ctx.message.content}"
)
if not seed_set:
arg_array.append("-seed")
arg_array.append(seed_num)
if self.process is None:
print(["python", SCRIPT_PATH] + arg_array)
self.process = subprocess.Popen(["python", SCRIPT_PATH] + arg_array)
await ctx.send("FFX TAS started.")
print("aVIna FFX TAS started.")
else:
await ctx.send("FFX TAS is already running.")
print("aVIna FFX TAS is already running.")
return self.process
# Define the start command
@commands.command()
async def blitz(self, ctx: commands.Context):
if self.process is None:
print(["python", BLITZ_PATH])
self.process = subprocess.Popen(["python", BLITZ_PATH])
await ctx.send("FFX TAS started.")
print("aVIna FFX TAS started.")
else:
await ctx.send("FFX TAS is already running.")
print("aVIna FFX TAS is already running.")
return self.process
# Alternate start command, Chocobo races
@commands.command(aliases=("choco", "race", "races", "showcase"))
async def chocobo(self, ctx: commands.Context):
if self.process is None:
print(["python", CHOCO_PATH])
await self.start_csr(ctx)
await self.start_game(ctx)
time.sleep(3)
self.process = subprocess.Popen(["python", CHOCO_PATH])
await ctx.send("FFX Showcase started.")
print("Showcase started.")
else:
await ctx.send("FFX TAS is already running.")
print("TAS is already running.")
return self.process
# Define the exit command
@commands.command(aliases=("stop", "quit", "terminate"))
async def exit(self, ctx: commands.Context):
if self.is_valid_user(ctx):
if self.process is not None:
self.process.terminate()
self.process.wait()
self.process = None
await ctx.send("FFX TAS stopped.")
print("aVIna FFX TAS stopped.")
else:
await ctx.send("FFX TAS is not running.")
print("aVIna FFX TAS is not running.")
# Define the start-CSR command
@commands.command(aliases=("csr_start", "csr_launch"))
async def start_csr(self, ctx: commands.Context):
arg_array = []
if self.is_valid_user(ctx):
if self.csr is None:
print(CSR_PATH)
arg_array.append("--csr=true")
arg_array.append("--truerng=false")
self.csr = subprocess.Popen([CSR_PATH] + arg_array)
await ctx.send("CSR started.")
print("CSR started.")
else:
await ctx.send("CSR is already running.")
# Define the stop-CSR command
@commands.command(aliases=("csr_stop", "csr_halt"))
async def stop_csr(self, ctx: commands.Context):
if self.is_valid_user(ctx):
if self.csr is not None:
self.csr.terminate()
self.csr.wait()
self.csr = None
await ctx.send("CSR stopped.")
print("CSR stopped.")
else:
await ctx.send("CSR is not running.")
# Launch FFX
@commands.command(aliases=("game_start", "launch_game"))
async def start_game(self, ctx: commands.Context):
if self.is_valid_user(ctx):
if self.game is None:
cwd = os.getcwd()
print(cwd)
os.chdir(GAME_PATH)
print(os.getcwd())
launch_path = GAME_PATH + "\FFX.exe"
print(launch_path)
self.game = subprocess.Popen([launch_path])
os.chdir(cwd)
await ctx.send("FFX started.")
print("FFX started.")
else:
await ctx.send("FFX is already running.")
print("FFX is already running.")
# Kill FFX
@commands.command(aliases=("game_stop", "halt_game"))
async def stop_game(self, ctx: commands.Context):
if self.is_valid_user(ctx):
if self.game is not None:
self.game.terminate()
self.game.wait()
self.game = None
await ctx.send("FFX stopped.")
print("FFX stopped.")
else:
await ctx.send("FFX is not running.")
print("FFX is not running.")
# Launch timer
@commands.command(aliases=("timer_start", "launch_timer"))
async def start_timer(self, ctx: commands.Context):
print(ctx.message.content)
args = ctx.message.content.split()
csr_val = None
for i in range(len(args)):
try:
if args[i].lower() == "csr":
csr_val = str(args[i + 1])
print(f"CSR value: {csr_val}")
if csr_val not in ["False", "True"]:
csr_val = None
raise Exception("Value must be True or False")
except Exception:
await ctx.send(
"You must provide a CSR value of True or False: "
+ f"{ctx.message.content}"
)
if csr_val is None:
csr_val = "True"
if self.is_valid_user(ctx):
if self.timer is None:
if csr_val == "False":
TIMER_PATH = TIMER_PATH_NORM
else:
TIMER_PATH = TIMER_PATH_CSR
cwd = os.getcwd()
print(cwd)
os.chdir(TIMER_PATH)
print(os.getcwd())
launch_path = TIMER_PATH + "\LiveSplit.exe"
print(launch_path)
self.timer = subprocess.Popen([launch_path])
os.chdir(cwd)
await ctx.send("Timer started.")
print("Timer started.")
else:
await ctx.send("Timer is already running.")
print("Timer is already running.")
# Kill timer
@commands.command(aliases=("timer_stop", "halt_timer"))
async def stop_timer(self, ctx: commands.Context):
'''
if ctx.author.name not in self.allowed_users:
await ctx.send(
f"Sorry {ctx.author.name}, you don't have permissions to execute this."
)
'''
if self.is_valid_user(ctx):
if self.timer is not None:
self.timer.terminate()
self.timer.wait()
self.timer = None
await ctx.send("Timer stopped.")
print("Timer stopped.")
else:
await ctx.send("Timer is not running.")
print("Timer is not running.")
# Define the help command
@commands.command()
async def help(self, ctx: commands.Context):
await ctx.send(
"Primary commands: !start_all to run all the programs and start the TAS. "
+ " !halt_all to end the run and shut everything down."
)
await ctx.send(
"Commands to start and stop each piece: !game_start, !game_stop, "
+ "!csr_start, !csr_stop, !timer_start, !timer_stop || " +
"Other commands: !start, !showcase, or !blitz to start the TAS from the New Game screen, "
+ "or !stop to hald the TAS if already running."
)
# Start All
@commands.command(aliases=("begin_all", "all"))
async def start_all(self, ctx: commands.Context):
if self.is_valid_user(ctx):
await self.start_csr(ctx)
await self.start_timer(ctx)
await self.start_game(ctx)
await self.start(ctx)
# Kill All
@commands.command(aliases=("kill_all","halt_all","stop_all"))
async def kill(self, ctx: commands.Context):
if self.is_valid_user(ctx):
await self.exit(ctx)
await self.stop_csr(ctx)
await self.stop_timer(ctx)
await self.stop_game(ctx)
# Main entry point of script
if __name__ == "__main__":
conf = BotConfig(CONFIG_FILE_PATH)
print("================================")
print("================================")
print(conf.data["csr_path"])
CSR_PATH = conf.data["csr_path"]
print(conf.data["game_path"])
GAME_PATH = conf.data["game_path"]
TIMER_PATH_NORM = conf.data["timer_any_normal"]
TIMER_PATH_CSR = conf.data["timer_any_csr"]
print("================================")
print("================================")
bot = Bot(conf.data)
bot.run()