-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsrc.py
2080 lines (1740 loc) · 90.7 KB
/
src.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
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# =============================================================================
# Imports
# =============================================================================
import json
import signal
import sys
from argparse import ArgumentParser, ArgumentTypeError
from datetime import datetime
from pathlib import Path
from time import sleep, time
import pandas as pd
import sqlalchemy as db
from websockets.sync.client import connect
from datetime import datetime
import pytz
import os
import random
import difflib
from difflib import SequenceMatcher
import re
from shapely.geometry import Polygon, Point
import math
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import threading
from collections import defaultdict
# =============================================================================
# Database Connection
# =============================================================================
with open(Path(__file__).parent / "credentials.json") as f:
creds = json.load(f)
ENG = db.create_engine(db.URL.create("mysql+mysqlconnector", **creds["database"]))
# ================================================================================================================
# Import Rachel Zhou's Important Places Coordinate system (edited to handshake with Jack's code and Triggers code.
# ================================================================================================================
data = pd.read_csv("WHIMC Coordinate Tracking updated.csv")
# Fill forward 'World' and 'Object' columns to handle blank cells
data["World"].fillna(method="ffill", inplace=True)
data["Object"].fillna(method="ffill", inplace=True)
# Initialize the dictionary to hold world data and global expected actions
world_coordinates_dictionary = {}
# Iterate through the dataframe
for _, row in data.iterrows():
world = row["World"]
object_name = row["Object_name"]
object_type = row["Object"]
expected_action = (
row["Expected_Action"] if not pd.isna(row["Expected_Action"]) else ""
)
# Ensure that the world and object type keys exist in the dictionary
if world not in world_coordinates_dictionary:
world_coordinates_dictionary[world] = {}
if object_type not in world_coordinates_dictionary[world]:
world_coordinates_dictionary[world][object_type] = {}
# Handle global expected actions
if object_name == "NA" and object_type == "Global":
world_coordinates_dictionary[world]["Global"] = expected_action.split(", ")
# Handle other objects (Places, NPCs, Signals)
else:
x = row["x"] if not pd.isna(row["x"]) else None
z = row["z"] if not pd.isna(row["z"]) else None
object_range = row["range"] if not pd.isna(row["range"]) else None
# Add details to the respective object in the dictionary
world_coordinates_dictionary[world][object_type][object_name] = {
"x": x,
"z": z,
"range": object_range,
"Expected Action": expected_action.split(", ") if expected_action else [],
}
if world_coordinates_dictionary.get("TwoMoonsLow", {}).get("Global", []):
print(f"\033[92m\nStart! \nWHIMC Coordinate Tracking updated.csv imported successfully\n\033[0m")
else:
# print(world_coordinates_dictionary.get("TwoMoonsLow", {}).get("Global", []))
print(f"\033[91mSomething went wrong with importing WHIMC Coordinate Tracking updated.csv\n\033[0m")
# =============================================================================
# Global Variables
# =============================================================================
# Set after parsing args
SOCKET = None
# =============================================================================
# SQL Queries
# =============================================================================
GET_TABLES = """
SHOW TABLES;
"""
'''
GET_PEEK = """
DESCRIBE whimc_chat;
"""
'''
GET_PEEK = """
SELECT * from rg_region_players;
"""
'''
GET_CO_COMMAND = """
SELECT * from co_command where time > (unix_timestamp(current_timestamp) - 10);
"""
'''
GET_CO_COMMAND = """
SELECT * from co_command where time > (unix_timestamp(current_timestamp) - 10);
"""
GET_CO_COMMAND_WITH_WORLDS = """
select from_unixtime(c.time) as time
, u.user as username
, message
, w.world, x, y, z
from (
select * from co_command where time > (unix_timestamp(current_timestamp) - 20)
) as c
left join co_user as u on c.user = u.rowid
left join co_world as w on c.wid = w.rowid
"""
GET_CO_CHAT_WITH_WORLDS = """
select from_unixtime(c.time) as time
, c.user as user_id
, message
, w.world as world
, c.x, c.y, c.z
from (
select * from co_chat where time > (unix_timestamp(current_timestamp) - 15)
) as c
left join co_world as w on c.wid = w.rowid
"""
GET_CO_CHAT = """
SELECT * from co_chat where time > (unix_timestamp(current_timestamp) - 60);
"""
GET_CO_USER = """
SELECT * from co_user;
"""
GET_CO_BLOCK_WITH_USERS = """
SELECT b.*, u.user as username
FROM co_block b
LEFT JOIN co_user u ON b.user = u.rowid
WHERE wid = 111 and b.time > (unix_timestamp(current_timestamp) - 120)
"""
# Extended GET_ONLINE_PLAYERS TO have current world data
GET_ONLINE_PLAYERS = """
select latest_positions.username as online_user
, pos.world as world
, pos.x as x
, pos.z as z
, latest_pos_time as position_time
from (
select username, max(time) as latest_pos_time
from whimc_player_positions
where time > (unix_timestamp(current_timestamp) - 30)
group by username
) as latest_positions
left join whimc_player_positions as pos
on latest_positions.username = pos.username and latest_positions.latest_pos_time = pos.time
"""
GET_COMMANDS = """
select from_unixtime(c.time) as time
, u.user as username
, message
, world, x, y, z
from (
select * from co_command where from_unixtime(time) >= '{newer_than}'
) as c
left join co_user as u on c.user = u.rowid
left join co_world as w on c.wid = w.rowid
"""
GET_OBSERVATIONS = """
select from_unixtime(floor(time / 1000)) as time
, username
, observation_color_stripped as observation
, world, x, y, z
from whimc_observations
-- timestamp has millisecond precision
where from_unixtime(time / 1000) >= '{newer_than}'
"""
GET_SCIENCE_TOOLS = """
select from_unixtime(time / 1000) as time
, username
, tool
, measurement
, world, x, y, z
from whimc_sciencetools
-- timestamp has millisecond precision
where from_unixtime(time / 1000) >= '{newer_than}'
"""
GET_WORLD_PERIMETERS = """
select region_id
, world_id
, min_x
, min_y
, min_z
, max_x
, max_y
, max_z
from rg_region_cuboid where region_id = 'perimeter'
-- we could also include selecting regions for kid bases, we'd want to standardize naming conventions,
-- though you could just assume that any region that's not perimeter on a mars build world is a kid base
"""
'''
GET_BLOCKS = """
select user
, world_id, x, y, z
, type
, action
from co_block where wid = 111 and
-- this should be a variable defined at startup, not hardcoded; wid 111 = sdp7
where from_unixtime(time) >= '{newer_than}'
-- timestamp is 10 digit unix precision
"""
'''
GET_BLOCKS = """
select user
, world_id, x, y, z
, type
, action
from co_block
where wid = {wid} and
from_unixtime(time) >= '{newer_than}'
"""
# Fetch the blocks with the provided wid (special function with special scope)
def fetch_blocks(self):
query = GET_BLOCKS.format(wid=self.wid, newer_than=self.newer_than.strftime("%Y-%m-%d %H:%M:%S"))
self.co_block_with_users = get_data(query)
GET_MATERIALS = """
select id
, material
from co_material_map
"""
GET_WID_FOR_WORLD = """
select w.rowid as wid
from co_world w
where w.world = 'sdp7'
"""
# =============================================================================
# Utility Functions (get from WHIMC, send to Dispatcher)
# =============================================================================
def send_trigger(trigger_name: str, username: str, priority: int):
payload = {
"event": "new_message",
"data": {
"from": "software",
"software": "WHIMC",
"timestamp": int(datetime.now().timestamp() * 1000),
"eventID": "",
"student": username,
"trigger": trigger_name,
"priority": priority,
},
}
payload["data"]["masterlogs"] = {
**payload["data"],
"reviewer": "",
"end": "",
"feedbackTXT": "",
"feedbackREC": "",
}
json_data = json.dumps(payload)
try:
global SOCKET
SOCKET = connect(
"wss://free.blr2.piesocket.com/v3/qrfchannel?api_key=4TRTtRRXmvNwXCWUFIjgKLDdZJ0zwoKpzn5ydd7Y¬ify_self=1"
)
stopwatch = time()
SOCKET.send(json_data)
print(f"Data sent to socket after {time() - stopwatch:.3f} seconds")
stopwatch = time()
response = SOCKET.recv()
print(f"Received response after {time() - stopwatch:.3f} seconds")
print(response)
stopwatch = time()
SOCKET.close()
print(f"Closed socket after {time() - stopwatch:.3f} seconds\n")
except Exception as e:
print(f"An error occurred: {e}")
def get_data(query, newer_than: datetime | None = None) -> pd.DataFrame:
return pd.read_sql(query.format(newer_than=newer_than), ENG)
# =============================================================================
# The Fetcher Class
# =============================================================================
class Fetcher:
CMDS = {
"commands": GET_COMMANDS,
"observations": GET_OBSERVATIONS,
"science_tools": GET_SCIENCE_TOOLS,
"players": GET_ONLINE_PLAYERS,
"peek": GET_PEEK,
"co_chat": GET_CO_CHAT,
"co_chat_with_worlds": GET_CO_CHAT_WITH_WORLDS,
"co_user": GET_CO_USER,
"co_command": GET_CO_COMMAND,
"co_command_with_worlds": GET_CO_COMMAND_WITH_WORLDS,
"co_block_with_users": GET_CO_BLOCK_WITH_USERS,
"get_wid_for_world": GET_WID_FOR_WORLD,
}
def load_data(self):
for key, query in Fetcher.CMDS.items():
df = get_data(query, self.newer_than)
setattr(self, key, df)
def __init__(self, initial_newer_than, saveload_file=None, wid=None):
self.newer_than = initial_newer_than
self.saveload_file = saveload_file
# self.players = get_data(GET_ONLINE_PLAYERS)
self.wid = wid
self.block_triggers_df = pd.read_csv('BlockBasedTriggers.csv')
# Mostly for type hinting
self.commands = pd.DataFrame()
self.observations = pd.DataFrame()
self.science_tools = pd.DataFrame()
self.players = pd.DataFrame()
self.peek = pd.DataFrame()
self.co_chat = pd.DataFrame()
self.co_user = pd.DataFrame()
self.co_command = pd.DataFrame()
self.co_command_with_worlds = pd.DataFrame()
self.co_chat_with_worlds = pd.DataFrame()
self.co_block_with_users = pd.DataFrame()
self.get_wid_for_world = pd.DataFrame()
self.load_data()
# this is for random trigger that fires when inactivity is detected
# does not matter which timezone, we just need a timer interval to detect inactivty since the time the python script was ran
self.last_trigger_time = datetime.now().timestamp()
# dataframes / dictionaries for triggers
self.triggers_list = []
# self.tools_usage = {} <- recoded to look for a save/load file first if any
if saveload_file and os.path.exists(saveload_file):
with open(saveload_file, "r") as f:
self.tools_usage = json.load(f)
else:
self.tools_usage = {}
self.observations_record = {}
self.pair_durations = defaultdict(int)
def save_tools_usage(self):
if self.saveload_file:
with open(self.saveload_file, "w") as f:
json.dump(self.tools_usage, f)
print(
f"\033[92mProgress saved to '{self.saveload_file}'. \nIt is now safe to stop the python script.\n \033[0m"
)
def fetch_data(self):
for key, query in Fetcher.CMDS.items():
df = get_data(query, self.newer_than)
# Set 'self.<key>' to the new dataframe
'''
if key == "co_block_with_users":
print ("PEEK")
print (df)
print ("WID")
print (self.wid)
'''
if key == "get_wid_for_world":
print ("PEEK")
print (df)
setattr(self, key, df)
self.save_tools_usage() # save after fetching the data
def fetch_data_playersonly(self):
for key, query in Fetcher.CMDS.items():
if key == "players":
df = get_data(query, self.newer_than)
# Set 'self.<key>' to the new dataframe
setattr(self, key, df)
self.save_tools_usage() # save after fetching the data
def fetch_data_observationsonly(self):
for key, query in Fetcher.CMDS.items():
if key == "observations":
df = get_data(query, self.newer_than)
# Set 'self.<key>' to the new dataframe
setattr(self, key, df)
self.save_tools_usage() # save after fetching the data
def on_wakeup(self):
# Use global variables
# global meganumber
# Need to convert the time to central time always because the actions
# of the players in the server are logged in central time.
central_tz = pytz.timezone("America/Chicago")
now = datetime.now(central_tz)
# now = datetime.now()
print(f"\033[96mWakeup at ----------- {now}. \nFetching data since - {self.newer_than.astimezone(central_tz)} \n^- \033[0mtime window for needed location values")
self.fetch_data()
'''
print(f"\nONLINE PLAYERS:\n{self.players}\n")
print(f"COMMANDS:\n{self.commands}\n")
print(f"OBSERVATIONS:\n{self.observations}\n")
print(f"SCIENCE TOOLS:\n{self.science_tools}\n")
print(f"OBSERVATIONS RECORD:\n{self.observations_record}\n")
'''
if not self.players.empty:
print(f"\033[95m\nONLINE PLAYERS:\033[0m\n{self.players}\n")
if not self.commands.empty:
print(f"\033[95m\nCOMMANDS:\033[0m\n{self.commands}\n")
if not self.observations.empty:
print(f"\033[95m\nOBSERVATIONS:\033[0m\n{self.observations}\n")
if not self.science_tools.empty:
print(f"\033[95m\nSCIENCE TOOLS:\033[0m\n{self.science_tools}\n")
if self.observations_record: # Assuming observations_record is a dictionary: nts: Check this occassionally
print(f"\033[95m\nOBSERVATIONS RECORD:\033[0m\n{self.observations_record}\n")
if not self.co_chat.empty:
print(f"\033[95m\nLATEST CHATS:\033[0m\n{self.co_chat}\n")
# print(f"CO_SESSION:\n{self.co_session}\n")
# Initialize tools_usage for all online players so we can get the worlds visited, and curr world data even
# if the student didn't make any observations / commands yet
for _, row in self.players.iterrows():
user = row["online_user"]
current_world = row["world"]
position_time = row["position_time"]
if user not in self.tools_usage:
self.tools_usage[user] = {
"worlds_visited": [
current_world
], # Initialize with the actual current world
"current_world": current_world,
"tool_use_count": 0,
# 'observation_count': 0
"total_observation_count": 0, # For overall observation count
"world_observation_counts": {
current_world: 0
}, # For per-world observation count
"last_observation_time": position_time,
# "last_observation_time": position_time,
"mynoa_start_time": None,
"mynoa_trigger_fired": False,
"recent_positions": [], # racing / non-stopping
"recent_observations": [],
"tool_usage_timestamps": [],
"last_tool_use_time": position_time,
# "last_tool_use_time": position_time,
"far_from_crowd_duration": 0,
"npc_interaction_start": None,
"poi_stay_start": None,
"world_tool_counts": {current_world: 0},
"chat_counts": {current_world: 0},
"tool_counts": {}
}
else:
# Update the current world
self.tools_usage[user]["current_world"] = current_world
# Add to worlds_visited if not already there
if current_world not in self.tools_usage[user]["worlds_visited"]:
self.tools_usage[user]["worlds_visited"].append(current_world)
# Racing / non-stopping
if 'recent_positions' not in self.tools_usage[user]:
self.tools_usage[user]['recent_positions'] = []
# Initialize world_tool_counts if not present
if 'world_tool_counts' not in self.tools_usage[user]:
self.tools_usage[user]['world_tool_counts'] = {}
if current_world not in self.tools_usage[user]['world_tool_counts']:
self.tools_usage[user]['world_tool_counts'][current_world] = 0
if 'chat_counts' not in self.tools_usage[user]:
self.tools_usage[user]['chat_counts'] = {}
if current_world not in self.tools_usage[user]['chat_counts']:
self.tools_usage[user]['chat_counts'][current_world] = 0
if 'tool_counts' not in self.tools_usage[user]:
self.tools_usage[user]['tool_counts'] = {}
if current_world not in self.tools_usage[user]['tool_counts']:
self.tools_usage[user]['tool_counts'][current_world] = {}
'''
# Reset last observation and tool use times
print(f"Resetting times for user {user}")
self.tools_usage[user]["last_observation_time"] = now.timestamp()
self.tools_usage[user]["last_tool_use_time"] = now.timestamp()
print(f"Last observation time: {self.tools_usage[user]['last_observation_time']}")
print(f"Last tool use time: {self.tools_usage[user]['last_tool_use_time']}")
'''
# check for triggers and populate triggers_list
self.update_tool_usage()
self.update_observation_usage()
self.check_mynoa_observations()
self.check_activities_near_important_places()
# summer2024newtriggers
self.check_no_observations_last_20_minutes()
self.check_racing_non_stopping()
self.check_3_observations_in_2_minutes()
self.check_3_tools_in_1_minute()
self.check_last_tool_use_over_20_minutes()
self.check_3_chat_entries_in_1_minute()
self.check_long_pair_close()
self.check_long_far_from_crowd()
self.check_prolonged_interaction_npc()
self.check_prolonged_stay_poi()
self.check_teleporting_to_multiple_players()
self.check_specific_commands()
self.check_five_or_more_observations_in_world()
self.check_five_or_more_tools_in_world()
self.check_five_chat_messages_in_world()
# self.check_over_200_actions_in_2_minutes()
self.check_over_200_placed_actions_in_2_minutes()
self.check_over_200_destroyed_actions_in_2_minutes()
self.check_block_triggers()
# print(f"TOOLS & OBSERVATION USAGE (SAVED): \n{self.tools_usage}\n")
# Send all triggers
for trigger_name, username, priority in self.triggers():
print(
f"\033[93mTriggered '{trigger_name}' for '{username}' (priority {priority}) \033[0m"
)
send_trigger(trigger_name, username, priority)
# Next iteration should /only/ show new data
self.newer_than = now
# Also reset the triggers list
self.triggers_list = []
def triggers(self) -> list[tuple[str, str, int]]:
"""
Return any triggers as a list of tuple[trigger name, username, priority]
"""
triggers = []
# TODO add checks here
# trigger = ("test", "Poi", 1)
# triggers.append(trigger)
return self.triggers_list
# =============================================================================
# Helper functions for trigger dictionaries / dataframes
# =============================================================================
def print_world_coordinates_dictionary(self):
for world, object_types in world_coordinates_dictionary.items():
print(f"World: {world}")
for object_type, objects in object_types.items():
print(f" Object Type: {object_type}")
for object_name, details in objects.items():
print(f" Object Name: {object_name}")
for key, value in details.items():
print(f" {key}: {value}")
# =============================================================================
# For Checking Important Places
# =============================================================================
def check_activities_near_important_places(self):
#now includes aliases
slash_commands_in_expected_actions = [
"airflow",
"wind",
"altitude",
"height",
"atmosphere",
"composition",
"cosmicrays",
"gravity",
"humidity",
"water",
"vapor",
"magnetic_field",
"oxygen",
"pressure",
"air_pressure",
"atmosphere_pressure",
"radiation",
"radius",
"rotational_period",
"daylength",
"scale",
"tectonic",
"seismic",
"temperature",
"temp",
"tides",
"ocean_level",
"tilt",
"axial_tilt",
"year",
"orbital_period",
"observe",
]
# handle observations
for _, row in self.observations.iterrows():
user = row["username"]
world = row["world"]
x = row["x"]
z = row["z"]
observation_text = row[
"observation"
] # 'observation' column holds the text of the observation
for object_type, objects in world_coordinates_dictionary.get(
world, {}
).items():
if object_type == "Global":
continue # Skip global actions for now; handle them later if needed
for object_name, details in objects.items():
similarity = SequenceMatcher(
None, observation_text, object_name
).ratio()
# Check if the observation is near a specific place or object
if "range" in details and self.is_point_inside_space(
x, z, details["range"]
):
print(
f"{user} made an observation near {object_name} in {world}. Similarity score: {similarity}"
)
self.triggers_list.append(
(
f"{user} made an observation near {object_name} in {world}. Similarity score: {similarity}",
user,
5,
)
)
elif "x" in details and "z" in details:
place_x, place_z = details["x"], details["z"]
# Check if x, z, place_x, and place_z are not None before calculation
if (
place_x is not None
and place_z is not None
and x is not None
and z is not None
):
if abs(x - place_x) + abs(z - place_z) <= 10:
print(
f"{user} made an observation near {object_name} in {world}. Similarity score: {similarity}"
)
self.triggers_list.append(
(
f"{user} made an observation near {object_name} in {world}. Similarity score: {similarity}",
user,
5,
)
)
# handle tool usage
for _, cmd_row in self.commands.iterrows():
user = cmd_row["username"]
world = cmd_row["world"]
x = cmd_row["x"]
z = cmd_row["z"]
message = cmd_row["message"].strip()
# print ("WORLD COORDS DICT", world_coordinates_dictionary.get(world, {}).get('Global', []))
# Determine the tool used in the command, if any
used_tool = None
for tool in slash_commands_in_expected_actions:
if message.startswith(f"/{tool}"):
used_tool = tool
break
# print ("\033[93mUSED TOOL\033[0m", used_tool)
if used_tool:
tool_triggered = False
# Check against important places in the world
for object_type, objects in world_coordinates_dictionary.get(
world, {}
).items():
if object_type == "Global":
# print("\033[93mOBJECT TYPE GLOBAL\033[0m")
continue # We will handle Global tools later
for object_name, details in objects.items():
expected_actions = details.get("Expected Action", [])
# print(f"\033[93mEXPECTED ACTIONS {expected_actions}\033[0m")
if (
"range" in details
and self.is_point_inside_space(x, z, details["range"])
and f"/{used_tool}" in expected_actions
):
print(
f"{user} used tool {used_tool} near {object_name} in {world}."
)
self.triggers_list.append(
(
f"{user} used tool {used_tool} near {object_name} in {world}",
user,
6,
)
)
tool_triggered = True
elif (
"x" in details
and "z" in details
and f"/{used_tool}" in expected_actions
):
place_x, place_z = details["x"], details["z"]
if abs(x - place_x) + abs(z - place_z) <= 10:
print(
f"{user} used tool {used_tool} near {object_name} in {world}."
)
self.triggers_list.append(
(
f"{user} used tool {used_tool} near {object_name} in {world}",
user,
6,
)
)
tool_triggered = True
if not tool_triggered:
global_actions = world_coordinates_dictionary.get(world, {}).get(
"Global", {}
)
# print("\033[93mGLOBAL ACTIONS\033[0m", global_actions)
for _, details in global_actions.items():
expected_actions = details.get("Expected Action", [])
# print("\033[93mEXPECTED ACTIONS\033[0m", expected_actions)
if f"/{used_tool}" in expected_actions:
print(
f"{user} used tool {used_tool} in world {world} (Global action)."
)
self.triggers_list.append(
(
f"{user} used tool {used_tool} in world {world} (Global action)",
user,
8,
)
)
break # Exit after finding and processing the first set of global actions
# Rachel Zhou's code edited to work with .self
def define_polygon_boundary(self, range_str):
if not range_str:
return [] # Or return a default polygon if applicable
coordinates = [
tuple(map(int, coord))
for coord in re.findall(r"\((-?\d+),(-?\d+)\)", range_str)
]
if len(coordinates) == 2:
x1, z1 = coordinates[0]
x2, z2 = coordinates[1]
coordinates = [(x1, z1), (x1, z2), (x2, z2), (x2, z1)]
return coordinates
def is_point_inside_space(self, x, z, range_str):
if not range_str:
return False
boundary = self.define_polygon_boundary(range_str)
if not boundary: # Check if the boundary is empty or invalid
return False
polygon = Polygon(boundary)
point = Point(x, z)
return polygon.contains(point)
# =============================================================================
# /For Checking Important Places
# =============================================================================
def check_mynoa_observations(self):
for _, player_row in self.players.iterrows():
user = player_row["online_user"]
current_world = player_row["world"]
position_time = player_row["position_time"]
if user not in self.tools_usage:
self.tools_usage[user] = {
"last_observation_time": position_time,
"mynoa_start_time": None,
"mynoa_trigger_fired": False,
}
# if current_world.startswith("mynoa"):
if current_world.startswith("Mynoa"):
if self.tools_usage[user]["mynoa_start_time"] is None:
self.tools_usage[user]["mynoa_start_time"] = position_time
self.tools_usage[user]["mynoa_trigger_fired"] = False
else:
time_in_mynoa = (
position_time - self.tools_usage[user]["mynoa_start_time"]
)
if (
time_in_mynoa >= 25 * 60
and not self.tools_usage[user]["mynoa_trigger_fired"]
):
# if time_in_mynoa >= 10 and not self.tools_usage[user]['mynoa_trigger_fired']:
observations_in_mynoa = (
self.tools_usage[user]
.get("world_observation_counts", {})
.get(current_world, 0)
)
if observations_in_mynoa == 0:
print(
f"{user} has been in {current_world} for more than 25 minutes without making an observation."
)
self.triggers_list.append(
(
f"{user} in {current_world} for 25+ minutes without observations",
user,
1,
)
)
self.tools_usage[user]["mynoa_trigger_fired"] = True
else:
self.tools_usage[user]["mynoa_start_time"] = None
self.tools_usage[user]["mynoa_trigger_fired"] = False
def update_observation_usage(self):
central_tz = pytz.timezone("America/Chicago")
for _, row in self.observations.iterrows():
user = row["username"]
world = row["world"]
position_time = row["time"]
# Convert position_time to a string if it's a Timestamp
if isinstance(position_time, pd.Timestamp):
position_time = position_time.strftime("%Y-%m-%d %H:%M:%S")
# Convert position_time to a timestamp in central timezone
position_time = datetime.strptime(position_time, "%Y-%m-%d %H:%M:%S").replace(tzinfo=central_tz).timestamp()
x = row["x"]
z = row["z"]
observation_text = row["observation"]
# Add the observation to the record, organized by world
if world not in self.observations_record:
self.observations_record[world] = []
self.observations_record[world].append((x, z, user, observation_text))
# Check for nearby observations
for obs_x, obs_z, obs_user, obs_text in self.observations_record[world]:
distance = abs(x - obs_x) + abs(z - obs_z) # Manhattan distance
if 0 < distance < 10:
similarity = difflib.SequenceMatcher(None, observation_text, obs_text).ratio()
print(f"obs distance is: {distance}, similarity is: {similarity}")
trigger_message = f"{user} made an observation near another observation in {world}. Difflib similarity is {similarity}"
print(trigger_message)
self.triggers_list.append((trigger_message, user, 5))
break # Exit after finding one nearby observation to avoid multiple triggers for the same event
if user not in self.tools_usage:
self.tools_usage[user] = {
"worlds_visited": [world],
"current_world": world,
"total_observation_count": 0, # For overall observation count
"world_observation_counts": {world: 0}, # For per-world observation count
"last_observation_time": position_time, # Initialize last observation time
"recent_observations": [position_time], # Initialize recent observations list
}
else:
self.tools_usage[user]["total_observation_count"] += 1
self.tools_usage[user]["current_world"] = world
self.tools_usage[user]["last_observation_time"] = position_time # Update last observation time
if world not in self.tools_usage[user]["worlds_visited"]:
self.tools_usage[user]["worlds_visited"].append(world)
if world not in self.tools_usage[user]["world_observation_counts"]:
self.tools_usage[user]["world_observation_counts"][world] = 0
self.tools_usage[user]["world_observation_counts"][world] += 1
# Add the current observation time to the list of recent observations
self.tools_usage[user].setdefault("recent_observations", []).append(position_time)
# Keep only the observations from the last 2 minutes
current_time = datetime.now(central_tz).timestamp()
self.tools_usage[user]["recent_observations"] = [
t for t in self.tools_usage[user]["recent_observations"] if current_time - t <= 2 * 60
]
# Check if the world is "mars" or "sdp7"
if world.lower() in ["mars", "sdp7"]:
trigger_message = f"{user} made an observation in {world}."
self.triggers_list.append((trigger_message, user, 2))
print(trigger_message)
for user, data in self.tools_usage.items():
worlds_visited = data["worlds_visited"]
current_world = data["current_world"]
world_observation_count = data.get("world_observation_counts", {}).get(current_world, 0)
# Check for lack of observations
if len(worlds_visited) >= 3:
trigger_key = f"no_observations_since_third_{current_world}"
if not data.get(trigger_key, False):
if len(worlds_visited) == 3 and world_observation_count == 0:
trigger_message = f"{user} has not made any observations by the third world."
print(trigger_message)
self.triggers_list.append((trigger_message, user, 2))
data[trigger_key] = True
elif len(worlds_visited) > 3 and world_observation_count == 0:
trigger_message = f"{user} has visited {len(worlds_visited)} worlds without making any observations."
print(trigger_message)
self.triggers_list.append((trigger_message, user, 2))
data[trigger_key] = True
# High observation counts check
high_obs_trigger_key = f"high_observations_{current_world}"
if len(worlds_visited) <= 3 and world_observation_count > 10: # 10
if not data.get(high_obs_trigger_key, False):
print(f"{user} has made more than 10 observations in {current_world}.")
self.triggers_list.append((f"{user} has high observation count in {current_world}", user, 7))
data[high_obs_trigger_key] = True
elif len(worlds_visited) > 3 and world_observation_count > 5: # 5