Files
status-python-sdk/monitor.py
T

258 lines
9.0 KiB
Python
Raw Normal View History

2026-03-19 22:47:35 +02:00
import datetime, os, pickle, yaml, time
import pandas as pd
2026-04-23 08:58:15 +03:00
from typing import Any
2026-03-19 22:47:35 +02:00
from pathlib import Path
from dotenv import load_dotenv
# Manual file imports
from bot import Account, Logger
from postgres import Postgres
2026-04-23 08:58:15 +03:00
def to_midnight(timestamp: datetime.datetime) -> datetime.datetime:
"""
Convert the given timestamp to midnight
Parameters:
- `timestamp` - current timestap
Output:
- `timestamp` at midnight
"""
return timestamp.replace(minute=0, second=0, hour=0, microsecond=0)
2026-03-19 22:47:35 +02:00
def load_config(file_path: str) -> dict:
"""
Load the config file and the `.env` variables
Parameter:
- `file_path` - the file path of the config yaml file. The `.env` variable must be in the same folder
Output:
- The config variables and secret from `.env`
"""
with open(file_path, "r") as f:
config: dict = yaml.safe_load(f)
env_file_path = os.path.join(os.path.dirname(file_path), ".env")
load_dotenv(env_file_path)
config["env_vars"] = {
key: value
for key, value in os.environ.items()
if key.startswith(("POSTGRES_", "STATUS_"))
}
return config
2026-04-23 08:58:15 +03:00
def extract_community_channels(account: Account, community: dict, latest_dates: dict[str, pd.Timestamp]) -> pd.DataFrame:
2026-03-23 07:36:49 +02:00
"""
Extract the community channel messages.
Parameters:
- `account` - logged in Status Bot account
- `community` - the current community from `account`
- `start_timestamp` - start timestamp for message fetching
- `end_timestamp` - end timestamp for message fetching
Output:
- DataFrame with all of the community messages for the given start and end timestamps
"""
final = []
for channel in community["channels"]:
2026-04-23 08:58:15 +03:00
now = datetime.datetime.now()
start_timestamp = latest_dates.get(channel["chat_id"])
if start_timestamp:
start_timestamp += datetime.timedelta(seconds=1)
else:
# Node will only return known / fetched messages for this channel.
# Without enabling community archives feature the node can only fetch last 30 days (from store nodes).
start_timestamp = to_midnight(now - datetime.timedelta(days=30))
account.logger.info(f"Starting message extraction for # {channel['name']} [{start_timestamp} - {now}]")
messages = account.get_messages(channel["chat_id"], start_timestamp, now)
2026-03-23 07:36:49 +02:00
messages = pd.DataFrame(messages)
if len(messages) == 0:
2026-04-23 08:58:15 +03:00
account.logger.info(f"No messages found")
2026-03-23 07:36:49 +02:00
continue
2026-04-23 08:58:15 +03:00
account.logger.info(f"Extracted {len(messages)} message(s)")
2026-03-23 07:36:49 +02:00
messages = messages.assign(
community_id = community["id"],
2026-04-23 08:58:15 +03:00
extracted_timestamp = now
2026-03-23 07:36:49 +02:00
)
final.append(messages)
return pd.concat(final, ignore_index=True) if final else pd.DataFrame()
2026-04-23 08:58:15 +03:00
def save_file(file_path: str, data: Any):
"""
Save data to a pickle file. Creates directories if they don't exist.
Parameters:
- `file_path` - Full pikle path
- `data` - Python object to be saved
"""
folder = os.path.dirname(file_path)
if len(folder) > 0:
os.makedirs(folder, exist_ok=True)
if isinstance(data, pd.DataFrame):
data.to_csv(file_path, index=False)
return
with open(file_path, "wb") as f:
pickle.dump(data, f)
2026-04-28 22:49:28 +03:00
def create_bot(config: dict) -> Account:
2026-03-19 22:47:35 +02:00
"""
2026-04-28 22:49:28 +03:00
Initialized a logged in bot account that will monitor the communities.
2026-03-19 22:47:35 +02:00
Parameters:
- `config` - the `load_config` configuration
2026-04-28 22:49:28 +03:00
Output:
- Logged in Bot account
2026-03-19 22:47:35 +02:00
"""
account = Account(**config.get("bot_params", {}))
available_accounts = [acc["display_name"] for acc in account.available_accounts]
prefix = "STATUS_"
params = {
key.replace(prefix, "").lower(): value
2026-04-23 08:58:15 +03:00
for key, value in config["env_vars"].items()
2026-03-19 22:47:35 +02:00
if key.startswith(prefix)
}
if params["display_name"] in available_accounts:
params.pop("mnemonic")
account.login(**params)
2026-04-23 08:58:15 +03:00
account.logger.info(f"Account Information:\nCompressed Key: {account.info['compressed_key']}\nPublic Key: {account.info['public_key']}\nURL: {account.info['url']}")
2026-04-28 22:49:28 +03:00
return account
def download(account: Account, folder: str, config: dict):
"""
Download Status App messages / info from communities and store them in pickle files.
Parameters:
- `folder` - the folder where the files will be created. Sub folders are automatically created
- `config` - the `load_config` configuration
"""
2026-04-23 08:58:15 +03:00
file_path = os.path.join(os.path.dirname(__file__), config["files"]["current_state"])
latest_dates: dict[str, pd.Timestamp] = pd.read_pickle(file_path) if os.path.exists(file_path) else {}
2026-03-19 22:47:35 +02:00
2026-04-23 08:58:15 +03:00
get_file_name = lambda: str(to_midnight(datetime.datetime.now()).timestamp()).replace(".", "")
communities = account.communities
if not communities:
account.logger.warning("No communities found...")
2026-03-19 22:47:35 +02:00
2026-04-23 08:58:15 +03:00
for community in communities:
2026-03-19 22:47:35 +02:00
2026-04-23 08:58:15 +03:00
if not community["is_member"]:
continue
community_folder_name = community["name"].replace(" ", "-")
messages_folder = os.path.join(folder, "messages", community_folder_name)
community_info_folder = os.path.join(folder, "community", community_folder_name)
account.logger.info(f"Extracting data for {community['name']}")
2026-03-19 22:47:35 +02:00
community["extracted_timestamp"] = datetime.datetime.now()
2026-04-23 08:58:15 +03:00
file_path = os.path.join(community_info_folder, get_file_name() + ".pkl")
2026-03-24 18:46:36 +02:00
if not os.path.exists(file_path):
2026-04-23 08:58:15 +03:00
save_file(file_path, community)
2026-03-24 18:46:36 +02:00
account.logger.info(f"Created {file_path}")
2026-03-19 22:47:35 +02:00
2026-04-23 08:58:15 +03:00
file_path = os.path.join(messages_folder, get_file_name() + ".csv")
2026-03-24 18:46:36 +02:00
if not os.path.exists(file_path):
2026-04-23 08:58:15 +03:00
messages = extract_community_channels(account, community, latest_dates)
2026-03-24 18:46:36 +02:00
if len(messages) > 0:
2026-04-23 08:58:15 +03:00
save_file(file_path, messages)
2026-03-24 18:46:36 +02:00
account.logger.info(f"Created {file_path}")
2026-03-19 22:47:35 +02:00
2026-04-28 22:49:28 +03:00
def store(folder: str, config: dict, logger: Logger):
2026-03-19 22:47:35 +02:00
"""
Upload Status App `download` file to Postgres.
NOTE: The Postgres schema must already exist
Parameters:
- `folder` - the folder where the files will be created. Sub folders are automatically created
- `config` - the `load_config` configuration
"""
path = Path(folder)
table_name_mapping: dict[str, str] = config["postgres"]["tables"]
table_schema = config["postgres"]["schema"]
upload: dict[str, list] = {}
2026-04-28 22:49:28 +03:00
file_path = os.path.join(os.path.dirname(__file__), config["files"]["current_state"])
latest_dates: dict[str, pd.Timestamp] = pd.read_pickle(file_path) if os.path.exists(file_path) else {}
2026-03-19 22:47:35 +02:00
completed = []
2026-04-23 08:58:15 +03:00
files = list(path.rglob("*.pkl")) + list(path.rglob("*.csv"))
2026-04-28 22:49:28 +03:00
logger.info(f"There are {len(files)} file(s) to upload")
2026-04-23 08:58:15 +03:00
for file_path in files:
table_name = table_name_mapping.get(file_path.parent.parent.name)
2026-03-19 22:47:35 +02:00
if not table_name:
continue
2026-04-23 08:58:15 +03:00
file_name = str(file_path.name)
data = pd.read_pickle(file_path) if file_name.endswith(".pkl") else pd.read_csv(file_path)
2026-03-19 22:47:35 +02:00
if isinstance(data, dict):
data = pd.DataFrame([data])
2026-04-23 08:58:15 +03:00
for column in data.columns:
if "timestamp" not in column:
continue
data[column] = pd.to_datetime(data[column])
2026-03-19 22:47:35 +02:00
if table_name not in upload:
upload[table_name] = []
2026-04-23 08:58:15 +03:00
if "timestamp" in data.columns:
latest_dates.update(data.groupby("chat_id")["timestamp"].max().to_dict())
2026-03-19 22:47:35 +02:00
upload[table_name].append(data)
completed.append(str(file_path))
2026-04-28 22:49:28 +03:00
save_file(config["files"]["current_state"], latest_dates)
logger.info(f"Updated {config['files']['current_state']}")
2026-04-23 08:58:15 +03:00
2026-03-19 22:47:35 +02:00
prefix = "POSTGRES_"
params = {
key.replace(prefix, "").lower(): value
for key, value in config["env_vars"].items()
if key.startswith(prefix)
}
connector = Postgres(**params)
for table_name, data in upload.items():
if len(data) == 0:
continue
df = pd.concat(data, ignore_index=True)
json_columns = [
column
for column in df.columns
2026-04-28 22:49:28 +03:00
if len(df[column].dropna()) > 0 and isinstance(df[column].dropna().reset_index(drop=True).iloc[0], (dict, list))
2026-03-19 22:47:35 +02:00
]
connector.insert(df, table_name, table_schema, json_columns)
2026-04-28 22:49:28 +03:00
logger.info(f"Uploaded {len(df)} record(s) to {table_schema}.{table_name}")
2026-03-19 22:47:35 +02:00
for file_path in completed:
os.remove(file_path)
2026-04-28 22:49:28 +03:00
logger.info(f"Deleted {file_path}")
2026-03-19 22:47:35 +02:00
if __name__ == "__main__":
folder = os.path.dirname(__file__)
config = load_config(os.path.join(folder, "config.yaml"))
upload_folder = os.path.join(os.path.dirname(__file__), "uploads")
2026-03-24 18:46:36 +02:00
logger = Logger()
2026-04-28 22:49:28 +03:00
account = create_bot(config)
2026-03-19 22:47:35 +02:00
2026-03-24 18:46:36 +02:00
while True:
2026-04-28 22:49:28 +03:00
download(account, upload_folder, config)
store(upload_folder, config, logger)
2026-03-24 18:46:36 +02:00
logger.info(f"Sleeping for {config['sleep']} minute(s)")
2026-04-28 22:49:28 +03:00
time.sleep(config["sleep"] * 60)