-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
143 lines (97 loc) · 3.33 KB
/
Copy pathbot.py
File metadata and controls
143 lines (97 loc) · 3.33 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# %% imports
import os
import openai
from dotenv import load_dotenv
import reddit_posts as rp
# %%
# store API credntials
load_dotenv()
openai.api_key = os.environ.get('OPENAI_API_KEY')
openai.Model.list()
def find_relevant_posts(submissions_df, num_posts=1):
top_post = submissions_df.sort_values(by='created_utc', ascending=False).head(num_posts)
return top_post
def prompt_gpt(prompt: str):
"""
Take a string and send it to GPT as a prompt
"""
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}])
return completion.choices[0].message
def has_ai_language(response: str) -> bool:
"""
This function will check if the response contains
the "As an AI language model..." disclaimer.
"""
check_string = "As an AI language model".lower()
if check_string in response.lower():
return True
else:
return False
# check ai language function
def test_has_ai_language():
assert True == has_ai_language("As an AI language model, I don't have personal opinions.")
assert False == has_ai_language("I don't have personal opinions.")
def check_post_history(post_id: str, history_file: str) -> bool:
"""
This function will update the post history with
the post id of the post that was responded to.
If the post id is already in the file, it will
return True. Otherwise it will write the post id
to the file and return False.
"""
# check for post id in file
# https://stackoverflow.com/questions/15233340
with open(history_file, 'r') as f:
post_ids = f.read().splitlines()
print(post_ids)
# check if post id is in file
if post_id in post_ids:
print("Post has already been responded to.")
return True
# add post id to file
with open(history_file, 'a') as f:
f.write(post_id + '\n')
return False
# test the check_post_history function
def test_check_post_history():
assert True == check_post_history('test1', 'data/post_history.txt')
# %% main
if __name__ == '__main__':
print('Running GPT Bot')
reddit = rp.reddit_connection()
# get posts
submissions = reddit.subreddit('AskReddit').new(limit=10)
# this function is a simpler version of what we had earlier
submissions_df = rp.create_submission_df(submissions)
top_posts = find_relevant_posts(submissions_df, 10)
# check if there are any posts to respond to
for index, submission in top_posts.iterrows():
print(submission['id'])
# check if post has been responded to
if check_post_history(submission['id'], 'data/post_history.txt'):
# skip this post
continue
# sleep for 20 seconds to prevent rate limiting
import time
time.sleep(20)
prompt = submission['title']
print("Post title:", prompt)
# prompt GPT
response = prompt_gpt(prompt)
print("GPT response:", response.content)
# check if response is AI language
if has_ai_language(response.content):
print("Response is AI language")
continue # skip this post
# post response to reddit
reply = reddit.submission(submission['id']).reply(response.content)
print('posted: ', reply)
# get posts history from our bot
my_comments_list = reddit.user.me().comments.top('all')
comments_df = rp.create_comments_df(my_comments_list)
import datetime
filename = 'bot_history_' + datetime.datetime.now().strftime("%Y-%m-%d_%I-%M-%S-%p")
comments_df.to_csv('data/' + filename + '.csv')
# %%