forked from justinmerrell/Twitter-AutoPost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tweet_builder.py
93 lines (67 loc) · 2.41 KB
/
tweet_builder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import os
import openai
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.environ.get("OPENAI_API_KEY")
def generate_concept():
'''
Generate a concept using the GPT-3 Concept Prompt
'''
with open("prompts/concept.txt", "r", encoding="UTF-8") as concept_prompt_file:
prompt = concept_prompt_file.read()
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}],
)
return response.choices[0].message.content.strip(), prompt
def format_concept(concept):
'''
Format the concept into a tweet using the GPT-3 Structure Prompt
'''
with open("prompts/structure.txt", "r", encoding="UTF-8") as structure_prompt_file:
prompt = structure_prompt_file.read()
# Inject the concept into the prompt
prompt = prompt.replace("{{CONCEPT}}", concept)
# Inject the tweet length into the prompt
disclaimer = get_disclaimer()
tweet_length = str(280 - len(disclaimer) - 1)
prompt = prompt.replace("{{TWEET_LENGTH}}", tweet_length)
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}],
)
return response.choices[0].message.content.strip(), prompt
def get_disclaimer():
'''
Get the disclaimer text
'''
with open("prompts/disclaimer.txt", "r", encoding="UTF-8") as disclaimer_prompt_file:
disclaimer = disclaimer_prompt_file.read()
# Inject GitHub link into the disclaimer
disclaimer = disclaimer.replace("{{GITHUB_USERNAME}}", os.environ.get("GITHUB_USERNAME"))
disclaimer = "\n\n" + disclaimer
return disclaimer
def add_disclaimer(tweet_text):
'''
Add the disclaimer to the end of the tweet
'''
disclaimer = get_disclaimer()
return tweet_text + disclaimer
def get_tweet():
'''
Generate a tweet
'''
max_attempts = 10
attempts = 0
while attempts < max_attempts:
concept, _ = generate_concept()
tweet, _ = format_concept(concept)
tweet = add_disclaimer(tweet)
if len(tweet) <= 279:
return tweet
else:
attempts += 1
# If the function reaches this point, all attempts failed to generate a tweet shorter than 280 characters.
raise ValueError("Unable to create a tweet within the character limit after 10 attempts.")
if __name__ == "__main__":
print(get_tweet())