publish-meetups/publish_meetups/feeds/twitter_feed.py

64 lines
1.7 KiB
Python
Raw Normal View History

2024-02-12 21:17:48 +00:00
from pathlib import Path
from twikit import Client
from twikit.errors import Forbidden, Unauthorized
from . import Feed
2024-02-13 20:25:47 +00:00
from ..utils import config, PROGRAM_NAME, prompt
2024-02-12 21:17:48 +00:00
class TwitterFeed(Feed):
2024-02-13 20:25:47 +00:00
__config_name__ = "twitter"
2024-02-12 21:17:48 +00:00
@classmethod
2024-02-13 20:25:47 +00:00
def prompt_auth(cls) -> dict:
2024-02-12 21:17:48 +00:00
"""
client.login(
auth_info_1=USERNAME ,
auth_info_2=EMAIL,
password=PASSWORD
)
"""
return {
"auth_info_1": prompt.for_string("Username"),
"auth_info_2": prompt.for_string("Email"),
"password": prompt.for_password("Password"),
}
# https://github.com/d60/twikit
def __init__(self, auth_info_1: str, auth_info_2: str, password: str, cookies: dict = None, **kwargs):
2024-02-13 20:25:47 +00:00
super().__init__()
2024-02-12 21:17:48 +00:00
self.client = Client('en-US')
logged_in = False
if cookies is not None:
self.client.http.client.cookies = cookies
try:
self.client.user_id()
logged_in = True
except (Forbidden, Unauthorized):
self.logger.warning("Cookies are expired.")
self.client.http.client.cookies.clear()
if not logged_in:
self.logger.info("Logging in with username and email.")
self.client.login(
auth_info_1=auth_info_1,
auth_info_2=auth_info_2,
password=password,
)
logged_in = True
2024-02-15 00:08:45 +00:00
config.set_field(f"feed.{self.__config_name__}.cookies", dict(self.client.http.client.cookies), update_dict=True)
2024-02-12 21:17:48 +00:00
def post(self, message: str):
self.client.create_tweet(
text=message,
)
2024-02-13 20:25:47 +00:00
super().post(message)