Files
NijiHolo_EN_ID_Bot/src/util.py
T

138 lines
3.7 KiB
Python
Raw Normal View History

2022-09-24 17:56:58 -07:00
## Shared utility functions.
import os
import sys
2022-09-27 22:04:26 -07:00
import traceback
2024-01-25 16:29:01 -08:00
from pathlib import Path
from datetime import datetime
2023-08-18 01:34:25 -07:00
from dotenv import dotenv_values
2022-09-27 02:49:03 -07:00
import pytz
from tweetcapture import TweetCapture
2023-08-18 18:20:53 -07:00
import tweepy
2022-11-22 21:46:42 -08:00
from recrop import fix_aspect_ratio
2022-09-25 18:31:50 -07:00
import talent_lists
2022-09-24 17:56:58 -07:00
2024-01-25 16:29:01 -08:00
def project_root(dir_path: tuple[str] = tuple(), file: str = None):
"""Returns path relative to the project root."""
dir_path = os.path.join(os.path.dirname(__file__), os.pardir, *dir_path)
Path(dir_path).mkdir(parents=True, exist_ok=True)
if file is not None:
return os.path.join(dir_path, file)
return os.path.join(dir_path)
def working_path(dir_path: tuple[str] = tuple(), file: str = None):
"""Returns file path relative to the working ephemeral directory."""
2024-01-25 16:59:41 -08:00
dir_path = project_root(("run", *dir_path))
2024-01-25 16:29:01 -08:00
Path(dir_path).mkdir(parents=True, exist_ok=True)
if file is not None:
return os.path.join(dir_path, file)
return os.path.join(dir_path)
2022-09-24 17:56:58 -07:00
def clamp(n, smallest, largest):
return max(smallest, min(n, largest))
2024-01-25 16:29:01 -08:00
def datetime_to_tdate(date_time: datetime):
2022-09-26 14:44:46 -07:00
return date_time.strftime("%Y-%m-%d")
2024-01-25 16:29:01 -08:00
2022-09-26 14:44:46 -07:00
def tdate_to_datetime(tdate: str):
return datetime.strptime("%Y-%m-%d")
2022-09-26 14:44:46 -07:00
2024-01-25 16:29:01 -08:00
2022-09-27 02:49:03 -07:00
def timestamp_to_tdate(timestamp=None):
2024-01-25 16:29:01 -08:00
if timestamp == None:
timestamp = datetime.now().timestamp()
return datetime_to_tdate(datetime.fromtimestamp(timestamp, tz=pytz.utc))
2022-09-27 02:49:03 -07:00
2024-01-25 16:29:01 -08:00
def get_current_timestamp():
return datetime.now().timestamp()
2024-01-25 16:29:01 -08:00
def get_current_date():
2024-01-25 16:29:01 -08:00
return datetime.today().strftime("%Y-%m-%d")
2023-08-16 18:48:13 -07:00
def get_key_from_value(d: dict, val):
2022-09-27 02:49:03 -07:00
keys = [k for k, v in d.items() if v == val]
if keys:
return keys[0]
return None
2024-01-25 16:29:01 -08:00
2023-08-18 18:20:53 -07:00
# FIXME: web_auth_token under rate-limitation will fail to screenshot
async def create_ttweet_image(ttweet):
tc = TweetCapture()
2024-01-25 16:29:01 -08:00
auth_token = dotenv_values(working_path(file=".env")).get("web_auth_token")
2023-08-20 16:13:38 -07:00
if auth_token:
2024-01-25 16:29:01 -08:00
tc.cookies = [{"name": "auth_token", "value": auth_token}]
if "linux" in sys.platform:
# Linux chromedriver path
2024-01-25 16:29:01 -08:00
tc.driver_path = "/usr/bin/chromedriver"
filename = working_path(file="img.png")
img = None
2024-01-25 16:29:01 -08:00
try:
os.remove(filename)
except:
pass
try:
img = await tc.screenshot(
2023-08-20 16:13:38 -07:00
url=ttweet.url(),
path=filename,
2023-08-18 03:16:10 -07:00
mode=4,
2022-12-12 23:23:41 -08:00
night_mode=1,
2024-01-25 16:29:01 -08:00
show_parent_tweets=True,
)
2022-11-22 21:46:42 -08:00
img = fix_aspect_ratio(img)
except:
2024-01-25 16:29:01 -08:00
print("unable to create tweet image")
2022-09-28 03:04:11 -07:00
traceback.print_exc()
return None
2024-01-25 16:29:01 -08:00
print(f"successfully saved {img}")
2023-08-20 16:13:38 -07:00
return img
2024-01-25 16:29:01 -08:00
2022-09-28 13:33:31 -07:00
def get_tweet_url(id, username):
2024-01-25 16:29:01 -08:00
return f"https://www.twitter.com/{username}/status/{id}"
2022-09-27 22:04:26 -07:00
## Attempt to pull username from local; pull from online if doesn't exist.
def get_username(id):
ret = talent_lists.talents.get(id, None)
if ret == None:
return get_username_online(id)
2022-09-28 13:33:31 -07:00
return ret
2022-09-27 02:49:03 -07:00
2024-01-25 16:29:01 -08:00
2023-01-14 01:18:15 -08:00
def get_username_with_company(id):
company = talent_lists.talents_company.get(id, None)
return f'{get_username(id)} {f"({company})" if company is not None else ""}'
2024-01-25 16:29:01 -08:00
2023-08-16 18:48:13 -07:00
def get_username_local(id: int):
2024-01-25 16:29:01 -08:00
return talent_lists.talents.get(id, f"{id}")
2023-08-16 18:48:13 -07:00
# Retrieve username via API v2 (tweepy)
def get_username_online(id, default=None):
2023-08-18 18:20:53 -07:00
import twapi
2024-01-25 16:29:01 -08:00
2022-09-27 02:49:03 -07:00
try:
2023-08-16 18:48:13 -07:00
resp = twapi.TwAPI.instance.client.get_user(id=id)
return resp.data.username
except tweepy.TooManyRequests:
2024-01-25 16:29:01 -08:00
return str(default) if default is not None else f"id:{id}"
2022-09-27 02:49:03 -07:00
except:
2024-01-25 16:29:01 -08:00
print(f"Unhandled error retrieving username for {id}!")
2023-08-16 18:48:13 -07:00
traceback.print_exc()
2024-01-25 16:29:01 -08:00
return str(default) if default is not None else f"id:{id}"