Skip to content

Instantly share code, notes, and snippets.

@jongan69
Created July 17, 2024 04:09
Show Gist options
  • Save jongan69/726884aab258f0b4d514a4114b06a5a0 to your computer and use it in GitHub Desktop.
Save jongan69/726884aab258f0b4d514a4114b06a5a0 to your computer and use it in GitHub Desktop.
lockin.py
import os
import schedule
import time
import tweepy
import textwrap
from dotenv import load_dotenv
from random import randint
from openai import OpenAI
# Load environment variables from .env
load_dotenv()
# Load OpenAI API key from .env
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
client = OpenAI(api_key=OPENAI_API_KEY)
# Twitter API credentials from .env
TWITTER_CONSUMER_KEY = os.getenv("TWITTER_CONSUMER_KEY")
TWITTER_CONSUMER_SECRET = os.getenv("TWITTER_CONSUMER_SECRET")
TWITTER_ACCESS_TOKEN = os.getenv("TWITTER_ACCESS_TOKEN")
TWITTER_ACCESS_TOKEN_SECRET = os.getenv("TWITTER_ACCESS_TOKEN_SECRET")
# OpenAI API key from .env
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# Set up Twitter API authentication with tweepy.Client
twitter_api = tweepy.Client(
consumer_key=TWITTER_CONSUMER_KEY,
consumer_secret=TWITTER_CONSUMER_SECRET,
access_token=TWITTER_ACCESS_TOKEN,
access_token_secret=TWITTER_ACCESS_TOKEN_SECRET
)
# Function to create and post a tweet
def create_tweet(tweet_message):
if len(tweet_message) > 280:
print(tweet_message)
tweet_parts = textwrap.wrap(tweet_message, 280, break_long_words=False)
for part in tweet_parts:
time.sleep(randint(10, 100))
try:
twitter_api.create_tweet(text=part)
except Exception as e:
print("An exception occurred with twitter: ", e)
pass
else:
time.sleep(randint(10, 100))
print(tweet_message)
try:
twitter_api.create_tweet(text=tweet_message)
except Exception as e:
print("An exception occurred with twitter: ", e)
pass
# Function to generate a creative but deranged tweet using ChatGPT
def generate_deranged_tweet():
try:
response = client.chat.completions.create(model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a creative and slightly deranged bot that generates tweets."},
{"role": "user", "content": "Create a creative but deranged tweet including the hashtag $lockin."}
])
tweet_message = response.choices[0].message.content.strip() + " $lockin"
create_tweet(tweet_message)
except Exception as e:
print("An error occurred while generating a deranged tweet: ", e)
# Schedule and run the bot
# Schedule the deranged tweet every 1 hour
schedule.every(1).hours.do(generate_deranged_tweet)
# Schedule the deranged tweet every 1 minute
schedule.every(1).minutes.do(generate_deranged_tweet)
# Run immediately for testing
generate_deranged_tweet()
while True:
schedule.run_pending()
time.sleep(1) # Sleep for 1 second to avoid hitting rate limits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment