This repository has been archived on 2024-10-10. You can view files and clone it, but cannot push or open issues or pull requests.
TelegramBot/classes/location.py

65 lines
1.8 KiB
Python
Raw Permalink Normal View History

2023-08-27 23:43:16 +03:00
from dataclasses import dataclass
2023-09-25 00:47:09 +03:00
from typing import Union
2023-08-27 23:43:16 +03:00
from bson import ObjectId
2023-09-25 00:47:09 +03:00
from pytz import timezone as pytz_timezone
from pytz.tzinfo import BaseTzInfo, DstTzInfo
2023-08-27 23:43:16 +03:00
from classes.point import Point
2023-11-05 15:20:01 +02:00
from modules.database_api import col_locations
2023-08-27 23:43:16 +03:00
@dataclass
class Location:
__slots__ = (
"_id",
"id",
"name",
"location",
"country",
"timezone",
)
_id: ObjectId
id: int
name: str
location: Point
country: int
2023-09-25 00:47:09 +03:00
timezone: Union[BaseTzInfo, DstTzInfo]
2023-08-27 23:43:16 +03:00
@classmethod
async def get(cls, id: int):
db_entry = await col_locations.find_one({"id": id})
if db_entry is None:
raise ValueError(f"No location with ID {id} found.")
db_entry["location"] = Point(*db_entry["location"]) # type: ignore
2023-09-25 00:47:09 +03:00
db_entry["timezone"] = pytz_timezone(db_entry["timezone"]) # type: ignore
2023-08-27 23:43:16 +03:00
return cls(**db_entry)
@classmethod
async def find(cls, name: str):
db_entry = await col_locations.find_one({"name": {"$regex": name}})
if db_entry is None:
raise ValueError(f"No location with name {name} found.")
db_entry["location"] = Point(*db_entry["location"]) # type: ignore
2023-09-25 00:47:09 +03:00
db_entry["timezone"] = pytz_timezone(db_entry["timezone"]) # type: ignore
2023-08-27 23:43:16 +03:00
return cls(**db_entry)
@classmethod
async def nearby(cls, lat: float, lon: float):
db_entry = await col_locations.find_one({"location": {"$near": [lon, lat]}})
if db_entry is None:
raise ValueError(f"No location near {lat}, {lon} found.")
db_entry["location"] = Point(*db_entry["location"]) # type: ignore
2023-09-25 00:47:09 +03:00
db_entry["timezone"] = pytz_timezone(db_entry["timezone"]) # type: ignore
2023-08-27 23:43:16 +03:00
return cls(**db_entry)