Skip to content

Instantly share code, notes, and snippets.

@odashi
Last active July 26, 2023 20:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odashi/6dceb28cf143df373d0a54257903c7a0 to your computer and use it in GitHub Desktop.
Save odashi/6dceb28cf143df373d0a54257903c7a0 to your computer and use it in GitHub Desktop.
Cloud Functions script to delete old tweets.
import datetime
import logging
import os
from google.cloud import logging as cloud_logging
import tweepy
THRESHOLD_DAYS = 3
BATCH_SIZE = 25
def is_local_run() -> bool:
return os.environ.get("FUNCTION_TARGET") is None
def setup() -> None:
if not is_local_run():
cloud_logging.Client().setup_logging()
logging.basicConfig(level=logging.INFO)
def make_twitter_client() -> tweepy.Client:
return tweepy.Client(
consumer_key=os.environ["TWITTER_CONSUMER_KEY"],
consumer_secret=os.environ["TWITTER_CONSUMER_SECRET"],
access_token=os.environ["TWITTER_ACCESS_TOKEN"],
access_token_secret=os.environ["TWITTER_ACCESS_TOKEN_SECRET"],
)
def main(event, content) -> None:
logger = logging.getLogger(__name__)
client = make_twitter_client()
my_id = client.get_me().data.id
threshold = datetime.datetime.now() - datetime.timedelta(days=THRESHOLD_DAYS)
tweets = client.get_users_tweets(
my_id,
max_results=BATCH_SIZE,
end_time=threshold,
tweet_fields=["created_at"],
user_auth=True,
).data
if tweets:
for tweet in tweets:
logger.info(f"Delete: id={tweet.id}, created_at={tweet.created_at}")
client.delete_tweet(tweet.id)
else:
logger.info("No tweet to delete.")
setup()
if is_local_run():
main(None, None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment