This repository was archived by the owner on Dec 13, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
475 lines (361 loc) · 17.1 KB
/
Copy pathbot.py
File metadata and controls
475 lines (361 loc) · 17.1 KB
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
import json
import asyncio
import logging
import logging.handlers
from components.config import Config
from components.websocket import WebSocket
from time import sleep
from javascript import require, AsyncTask
from uuid import uuid4
from aiohttp import ClientWebSocketResponse
class Bot():
def __init__(self, logger: logging.Logger, id: int, username: str, lobby: str, config: Config) -> None:
"""
Initialise the bot
:param logger: Logger
:param id: Bot ID
:param username: Bot username
:param config: Config
:param ws: Websocket
"""
self.logger = logger
self.id = id
self.username = username
self.lobby = lobby
self.config = config
self.websocket = None
self.bot = None
self.mineflayer = None
self.logged = False
self.totalPings = 0
self.totalNPCs = 0
self.totalLobbies = 0
self.totalInvalidPings = 0
self.lastLobby = 0
self.thread: WebSocket = None
self.currentLobby = 1
self.pings = []
def shortUUID(self) -> str:
return str(uuid4())[:8]
async def start(self) -> None:
"""
Start the bot
"""
self.thread = WebSocket(self.id, self.username, self.logger, self.setWebsocket)
self.thread.daemon = True
self.thread.start()
while not self.websocket:
sleep(1)
self.logger.info(f"""Launching bot...
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ ┃
┃ • Starting bot... ┃
┃ > ID: {self.id} {' ' * (42 - len(str(self.id)))}┃
┃ > Name: {self.username}{' ' * (44 - len(self.username))}┃
┃ ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
""")
try:
self.mineflayer = require("mineflayer")
self.bot = self.mineflayer.createBot(
{
"username": self.username.lower(),
"host": "hypixel.net",
"port": 25565,
"auth": "microsoft",
"version": "1.8.9",
"profilesFolder": self.config.profilesFolder,
"checkTimeoutInterval": 60 * 10000,
}
)
self.bot.addListener("messagestr", self.onMessage)
self.bot.addListener("login", self.onLogin)
self.bot.addListener("spawn", self.onSpwan)
self.bot.addListener("playerJoined", self.onPlayerJoined)
self.bot.addListener("windowOpen", self.windowOpen)
self.bot.addListener("error", self.error)
self.bot.addListener("kicked", self.kicked)
except Exception as e:
self.logger.error(f"Error occurred while starting bot: {e}")
self.restart()
def restart(self) -> None:
"""
Restart the bot
"""
self.logger.info(f"""Restarting bot in 10s...
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ ┃
┃ • Restarting bot in 10s... ┃
┃ > ID: {self.id} {' ' * (42 - len(str(self.id)))}┃
┃ > Name: {self.username}{' ' * (44 - len(self.username))}┃
┃ ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
""")
self.quit()
@AsyncTask(start=True)
def wait(task):
sleep(60)
asyncio.run(self.start())
def onMessage(self, raw, message: str, position, *args) -> None:
"""
Handle the message event
:param raw: Raw message
:param message: Message
:param position: Position of the message
:param args: Additional arguments
"""
if position == "chat":
if message == "That lobby is currently full!" or message == "You were kicked while joining that server!" or message == "This server is full! (Server closed)"\
or message == "You are already connected to this server" or message.startswith("You are already in") or message == "You are already connected to this server!":
self.logger.debug(f"Skipping lobby : {self.currentLobby} | {message}")
try:
self.bot.setQuickBarSlot(8)
self.bot.activateItem()
except:
self.logger.error("Error occurred setting quick bar slot and activating item")
self.restart()
return
elif message.startswith("From"):
rid = self.shortUUID()
rawMessage = message.split(":")[1].strip()
author = message.split(":")[0].split("From ")[1]
if " " in author:
author = author.split(" ")[1]
if author in self.config.admins:
if message.endswith("stats"):
self.logger.info(f"[MSG] Serving stats to {author}... Message: [Pings: {self.totalPings}, NPCs: {self.totalNPCs}, Lobbies: {self.totalLobbies}, Invalid Pings: {self.totalInvalidPings}] (Request ID: {rid})")
self.bot.chat(f"/msg {author} [Pings: {self.totalPings}, NPCs: {self.totalNPCs}, Lobbies: {self.totalLobbies}, Invalid Pings: {self.totalInvalidPings}] Request ID: {rid}")
elif message.endswith("stop"):
self.logger.info(f"[MSG] Stopping bot, requested by {author}!")
self.quit()
elif message.endswith("rejoin"):
self.logger.info(f"[MSG] Rejoining, requested by {author}!")
self.quit()
asyncio.run(self.start())
elif rawMessage.startswith("lobby"):
lobby = rawMessage.split(" ")[1]
self.logger.info(f"[MSG] Moving to lobby {lobby}, requested by {author}!")
self.bot.chat(f"/lobby {lobby}")
self.lastLobby = 0
@AsyncTask(start=True)
def wait(task):
sleep(3)
self.logger.info(f"[MSG] Moved to lobby {lobby}! (Request ID: {rid})")
self.bot.chat(f"/msg {author} Moved to lobby {lobby}! Request ID: {rid}")
elif rawMessage.startswith("friend"):
friend = rawMessage.split(" ")[1]
self.logger.info(f"[MSG] Adding {friend} as a friend, requested by {author}!")
self.bot.chat(f"/f add {friend}")
@AsyncTask(start=True)
def wait(task):
sleep(1)
self.logger.info(f"[MSG] Sent {friend} as a friend request! (Request ID: {rid})")
self.bot.chat(f"/msg {author} Sent {friend} as a friend request! Request ID: {rid}")
elif rawMessage.startswith("boop"):
player = rawMessage.split(" ")[1]
self.logger.info(f"[MSG] Booping {player}, requested by {author}!")
self.bot.chat(f"/boop {player}")
@AsyncTask(start=True)
def wait(task):
sleep(1)
self.logger.info(f"[MSG] Booped {player}! (Request ID: {rid})")
self.bot.chat(f"/msg {author} Booped {player}! Request ID: {rid}")
elif rawMessage.startswith("msg"):
player = rawMessage.split(" ")[1]
msg = " ".join(rawMessage.split(" ")[2:])
self.logger.info(f"[MSG] Messaging {player}, requested by {author}!")
self.bot.chat(f"/msg {player} {msg}")
@AsyncTask(start=True)
def wait(task):
sleep(1)
self.logger.info(f"[MSG] Messaged {player}! (Request ID: {rid})")
self.bot.chat(f"/msg {author} Messaged {player}! Request ID: {rid}")
elif message == "You are sending commands too fast! Please slow down.":
self.logger.debug("Sending commands too fast, sleeping...")
sleep(3)
try:
self.bot.setQuickBarSlot(8)
self.bot.activateItem()
except:
self.logger.error("Error occurred setting quick bar slot and activating item")
self.restart()
return
elif message.startswith("{"):
try:
data = json.loads(message)
if data.get("server") == "limbo":
self.logger.warning(f"Joined limbo, rejoining...")
sleep(3)
self.bot.chat(f"/lobby {self.lobby}")
self.lastLobby = 0
else:
self.logger.info(f"Scanned lobby: {data.get('lobbyname')} ({data.get('server')}) [{data.get('gametype')}] {{{self.currentLobby-1}/{self.lastLobby}}} | '{self.username}'")
self.totalLobbies += 1
except (json.JSONDecodeError, KeyError):
pass
def onLogin(self, *args) -> None:
"""
Handle the login event
:param args: Additional arguments
"""
if not self.logged:
self.logged = True
print(f"Logged in as: '{self.bot.username}'")
self.logger.info(f"Logged in as: '{self.bot.username}'")
self.logger.info(f"Joining lobby {self.lobby}...")
self.bot.chat(f"/lobby {self.lobby}")
self.lastLobby = 0
@AsyncTask(start=True)
def wait(task):
sleep(3)
self.logger.info(f"Joining lobby² {self.lobby}...")
self.bot.chat(f"/lobby {self.lobby}")
def onSpwan(self, *args) -> None:
"""
Handle the spawn event
:param args: Additional arguments
"""
self.bot.chat("/locraw")
self.logger.info("Scanning lobby...")
@AsyncTask(start=True)
def postPings(task):
pingsToPost = self.pings.copy()
self.logger.info(f"Found {len(pingsToPost)} pings!")
self.totalPings += len(pingsToPost)
if len(pingsToPost) > 1:
if self.thread.killed:
self.logger.warning("Websocket is killed, restarting bot...")
self.restart()
try:
asyncio.run(self.websocket.send_json(pingsToPost))
self.logger.info(f"Posted {len(pingsToPost)} pings!")
except Exception as e:
# FIXME: Add a better handling for this
self.logger.error(f"Error occurred while posting pings: {e}")
self.quit()
self.pings = []
@AsyncTask(start=True)
def wait(task):
self.logger.info("Sleeping...")
sleep(self.config.delay)
if self.bot:
try:
self.bot.setQuickBarSlot(8)
self.bot.activateItem()
except:
self.logger.error("Error occurred setting quick bar slot and activating item")
self.restart()
else:
self.logger.error("Bot is not defined!")
self.restart()
def onPlayerJoined(self, this, player) -> None:
"""
Handle the player joined event
:param this: This
:param player: Player object
"""
ping = player["ping"]
uuid = player["uuid"]
username = player["username"]
with open("players.json", "a+") as file:
data = json.dumps(player, indent=4)
file.write(data)
if ping != 0: # NPC's don't have ping
if ping > 0 and ping < 1000: # ping is always positive
self.pings.append({"uuid": uuid, "ping": ping, "username": username})
else:
self.totalInvalidPings += 1
else:
self.totalNPCs += 1
def windowOpen(self, this, window) -> None:
"""
Handle the window open event
:param this: This
:param window: Window object
"""
try:
if "Lobby Selector" in window.title:
if self.lastLobby == 0:
for slot in window.slots:
if slot and (slot.name == "quartz_block" or slot.name == "stained_hardened_clay"):
self.lastLobby += 1
self.bot.currentWindow.requiresConfirmation = False
skip = True
while skip:
self.currentLobby = (
self.currentLobby if self.currentLobby != self.lastLobby + 1 else self.config.lobby_start
)
for line in window.slots[self.currentLobby - 1].nbt.value.display.value.Lore.value.value:
found = False
if line.startswith("§7Players: "):
found = True
players = int(line.split("§7Players: ")[1].split("/")[0])
if players >= self.config.minimum:
skip = False
self.logger.info(f"[ > ] Joining lobby {self.currentLobby} | {players} players")
break
else:
self.logger.info(f"[ > ] Skipping lobby {self.currentLobby} as it has {players} player{'s' if players != 1 else ''}")
self.currentLobby = (
self.currentLobby if self.currentLobby != self.lastLobby + 1 else self.config.lobby_start
)
if skip:
break
if not found:
skip = False
@AsyncTask(start=True)
def wait(click):
self.logger.info(f"Clicking window {self.currentLobby}...")
sleep(0.1)
self.bot.clickWindow(self.currentLobby - 1, 0, 0)
self.currentLobby += 1
except (IndexError, KeyError, AttributeError) as e:
self.logger.error(f"Error occurred while processing window: {e}")
def error(self, this, error) -> None:
"""
Handle the error event
:param this: This
:param error: Error object
"""
self.logger.error(f"Error occurred: {error}")
self.restart()
def kicked(self, this, reason, loggedIn) -> None:
"""
Handle the kicked event
:param reason: Reason for being kicked
:param loggedIn: Logged in status
"""
self.logger.error(f"Kicked: {reason}")
if "banned" in reason.lower():
self.quit()
else:
self.restart()
def quit(self) -> None:
"""
Quit the bot
"""
self.logger.info(f"Quitting bot: {self.username}")
self.thread.terminate()
if self.bot:
self.logger.info(f"""
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ ┃
┃ • Quitting bot... ┃
┃ > ID: {self.id} {' ' * (42 - len(str(self.id)))}┃
┃ > Name: {self.username}{' ' * (44 - len(self.username))}┃
┃ ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
""")
self.bot.quit()
self.bot = None
def setWebsocket(self, websocket: ClientWebSocketResponse|None) -> None:
"""
Set the websocket
:param websocket: Websocket
"""
if not websocket:
self.logger.warning(f"Websocket is not defined, restarting bot after 4 minutes...")
sleep(180)
self.restart()
else:
self.websocket = websocket