[Method] Bot to respond to HARO emails for backlinks using OpenAI

FunkyJunky

Registered Member
Joined
Oct 26, 2022
Messages
56
Reaction score
30
Sup,

Below is some code you can copy and paste into your code editor(I use Visual Code). I am by no means a python expert, but the code does work.

The below code will scrape your inbox for any emails from HARO(Help A Reporter Out) from today that include your specified keywords. If your keywords are in the email, the bot will prompt OpenAI to write a return email to the reporter, including the requirements listed and save the email to your drafts folder so you can review prior to it being sent.

Some people respond to these emails in the hopes of getting backlinks. It can be time consuming going through all the questions in the 3 emails received daily. This will make it quicker to sift through the questions that relate to your niche, and also gives you a rough draft to respond to the reporter's query.

I would suggest changing the prompt as the one below is very generic and something I simply played around with for the sake of the bot.

You will need an OpenAI API. Create a separate file named "config.json" for your UN, PW, API Key, etc. If you don't know how to do that, ask chatGPT.

Let me know if you have any questions. For you python experts, go easy on me.




# %%
import imaplib
import json
import email
import openai
import time
import email.charset
import datetime
import pytz
import pandas as pd
# %%
# Read the email username and password from the config.json file
with open("config.json", "r") as config_file:
config_data = json.load(config_file)
email_username = config_data["email_username"]
email_password = config_data["email_password"]
openai.api_key = config_data["API_KEY"]
# %%
mail = imaplib.IMAP4_SSL("imap.gmail.com")
# Login to the email account
mail.login(email_username, email_password)
# Select the inbox
# %%
# Define the date range for last week
now = datetime.datetime.now(pytz.timezone("UTC"))
last_week = now - datetime.timedelta(days=7)
mail.select("inbox")
# Search for emails from the specified sender in the date range
status, emails = mail.search(None, f'FROM "[email protected]" SINCE "30-Jan-2023"')

# %%
keywords = ['Pregnancy','Pediatrician']
results = []
# Scrape all instances of the desired content
email_ids = emails[0].split()
for email_id in email_ids:
status, email_data = mail.fetch(email_id, "(RFC822)")
email_body = email_data[0][1].decode("utf-8")
msg = email.message_from_string(email_body)
email_body = email_body.replace("\r", "").replace("\n", "")
start = 0
while True:

start = email_body.find("Summary:", start)
if start == -1:
break
start += len("Summary:")
end = email_body.find("Name:", start)
summary = email_body[start:end].strip()
start = email_body.find("Email:", end) + len("Email:")
end = email_body.find("Media Outlet:", start)
address = email_body[start:end].strip()
start = email_body.find("Query:", end) + len("Query:")
end = email_body.find("Requirements:", start)
query = email_body[start:end].strip()
start = email_body.find("Requirements:", end) + len("Requirements:")
end = email_body.find("-----------------------------------", start)
requirements = email_body[start:end].strip()

# Check if any of the keywords are included in summary, email, query, and requirements
for keyword in keywords:
if keyword in summary or keyword in address or keyword in query or keyword in requirements:
# Add the summary, email, query and requirements to the questions dictionary
results.append((msg['Date'], summary, address, query, requirements))
break
df = pd.DataFrame(results, columns=["Date", "Summary", "Address", "Query", "Requirements"])
prompt = "I want you to write a professional email response to this question or questions: '{}'. In each response, you must include: '{}' You will act as the professional the email seeks. Introduce yourself by name at the start of the email. Any required links will be included in your email signature. After introducing yourself, immediately answer the questions asked. Do not beat around the bush. You are to list the question and immediately give your expert opinion."
return_emails = []
for index, row in df.iterrows():
query = row['Query']
requirements = row['Requirements']
response = openai.Completion.create(engine="text-davinci-003", prompt=prompt.format(query, requirements), temperature=0.7,max_tokens=1000,top_p=0.5)
response_text = response['choices'][0]['text']
return_emails.append(response_text)





# %%
for i, address in enumerate(df['Address']):
msg = email.message.Message()
msg["To"] = address
msg["Subject"] = "HARO Question"
msg.set_payload(return_emails)
return_emails = msg.as_string()
drafts = mail.append("[Gmail]/Drafts", "", imaplib.Time2Internaldate(time.time()), return_emails.encode())
 
Back
Top