Morning Text Bot

Python has quickly become my new favorite programming language, due to its versatility and easy implementation of numerous available APIs. Over the last year I’ve made dozens of projects for my Introduction to Engineering course as well as some personal projects I will be sharing here.
For this project, I wanted to wake up every morning to a text message containing the news, top headlines, some advice, and a joke. A great way to start my morning, and a great way to begin learning about APIs in python.
To start, I’m simply using VS Code, and my project is also hosted on GitHub here.
So to start, we need to be able to send a text message from the Python script to a phone number of our choosing. If you, like me, were unaware, if you email a phone number it instead sends an SMS text to that number. However, you must add an ending to the phone number that changes based on the service provider. For AT&T, you have to add @txt.att.net after the phone number, or for Verizon, you must add @vtext.com.
So for this script we’re using a library that allows us to send text messages in Python. Thus, we will need to import it into the project.
import smtplib
Smtplib is a library that allows us to easily send emails using python. Next we must declare a few variables.
#email must be gmail and have less secure sign on turned on
gmail_user = input("Enter your email: ")
gmail_password = input("Enter your password: ")
number = input("Enter the number you intend to text: ")
For these variables I choose to leave them as user inputs making the program more easily usable for anyone, however you can simply change these values to fill them in with exact information. Notice my comments, using Gmail makes this process much simpler, but I recommend making a new Gmail account for this as you must have the less secure sign on turned on so the smtp server may sign in.
Next, I wanted to make sure that I would be able to text anyone without having to know who their provider was. So here I wrote this portion of the script:
to = []
endings = [
"@txt.att.net",
"@messaging.sprintpcs.com", "@pm.sprint.com",
"@tmomail.net",
"@vtext.com",
"@myboostmobile.com",
"@sms.mycricket.com",
"@mymetropcs.com",
"@mmst.tracfone.com",
"@email.uscc.net",
"@vmobl.com"
]
for ending in endings:
numberWithEnding = ""
numberWithEnding = number + ending
to.append(numberWithEnding)
print(to)
We start by creating a List where the potential recipients will be held. Then I created another list with all the possible endings for the most common cell service providers. Then I wrote a for loops that goes through all the endings and creates a new value with the ending appended to the end of the phone number and it adds that value to the list of possible recipients. Then I simply printed the list of recipients so I knew it functioned properly.
Now we have a list of recipients, and since only one phone number exists for every sim card, we can then email or text every recipient in the list and it will only go through for the number with its matching providers ending.
Next I needed to write the code to actually send an email. A bit of this is more complicated, but this is the portion of the script that connects to a server, signs in and then writes and sends the email:
email_text = f"""
#Here is where you write the body to your message
"""
try:
smtp_server = smtplib.SMTP('smtp.gmail.com', 587)
smtp_server.starttls()
smtp_server.ehlo()
smtp_server.login(gmail_user, gmail_password)
smtp_server.sendmail(gmail_user, to, email_text)
smtp_server.close()
print ("Email sent successfully")
except Exception as ex:
print (f"Something went wrong: {ex}")
So first we have a simple f””” string that allows us to write the body of the text to store for later. I made it an f string in order to allow us to use variables and such later on.
Then we start a try except, in order to send the email and check easily for errors. So in this try, we first create a server object and with the Gmail address and port. Then we start ttls and run ehlo. Next we login using the user and password variables we created earlier, and then send mail with the from and to arguments along with the text we created for the body. Then we close the server as our email has sent!
APIs
APIs are very simple. They are libraries that people have previously written that allow our script to interact with other programs. For this project I used Open Weather as well as NewsAPI, these two allowed me to gather the latest headlines on the news as well as the local weather.
For these all I had to do was add:
def get_latest_news():
counter = 0
news_headlines = ""
res = requests.get(
f"https://newsapi.org/v2/top-headlines?country=in&apiKey={NEWS_API_KEY}&category=general").json()
articles = res["articles"]
for article in articles:
if(counter != 5):
news_headlines = news_headlines + ", " + article["title"]
counter = counter + 1
counter = 0
#news_headlines.replace("'", "")
#news_headlines.replace("-", " ")
news_headlines.encode("ascii", "ignore")
return news_headlines
def get_weather_report(city):
res = requests.get(
f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={OPENWEATHER_APP_ID}&units=metric").json()
weather = res["weather"][0]["main"]
temperature = res["main"]["temp"]
feels_like = res["main"]["feels_like"]
return weather, f"{temperature} degrees", f"{feels_like} degrees"
weather, temperature, feels_like = get_weather_report("cooper city")
headlines = get_latest_news()
These are two functions that pull from the APIs using the url and the API key which you get from signing up for free on their websites. Then I simply modified my email_text variable to add:
email_text = f"""
Good Morning Miles, The current temperature is {temperature},
but it feels like {feels_like},
and the weather looks like {weather}.
{headlines}
"""
I also added two other functions using the requests library which pulls certain information from websites.
def get_random_advice():
res = requests.get("https://api.adviceslip.com/advice").json()
return res['slip']['advice']
def get_random_joke():
headers = {
'Accept': 'application/json'
}
res = requests.get("https://icanhazdadjoke.com/", headers=headers).json()
return res["joke"]
joke = get_random_joke()
advice = get_random_advice()
These two functions allowed me to pull a dad joke and some random advice from icanhazdadjoke.com and api.adviceslip.com.
Then I fixed my email_text to include the joke and advice:
email_text = f"""
Good Morning Miles, The current temperature is {temperature},
but it feels like {feels_like},
and the weather looks like {weather}.
{headlines}
{advice}
{joke}
"""
Now this is fun and if you’re looking to mess with friends or be an ass, which of course I highly encourage, try using something like the Shakespearian Insult Generator.
Running the Script on a Schedule
For me, I wanted to run this script every morning around the time that my alarms go off so I would wake up to the text. First what you need to do is create a windows batch file that runs your python script.
The basic format for this is:
@echo off
"Path where your Python exe is stored\python.exe" "Path where your Python script is stored\script name.py"
pause
Fill in the file paths and create a .bat file from the txt document you used to write this.
Then you’ll need to open windows task scheduler and add a new task, find the .bat file and determine when and how often you need the script to run.