Published on 2020-10-12, by Javed Shaikh
Hello everyone!
This is my first ever blog post and here I am going to share about a twitter bot that I developed in early 2018. The bot we are talking about is @Nasarobot . This bot tweets one beautiful astronomy image everyday using Nasa api with just few lines of python code. So lets get started..
To create a twitter bot, first thing we need to do is signup for a developer account at https://developer.twitter.com/en Once signup is done, lets go to the 'Apps' menu and create a new app. Do submit details as asked like the name of the app, its description etc. After creating an app you will be provided API Key, API Secret Key, Access Token and Access Token Secret as shown below.
Since this bot tweets astronomy picture provided by Nasa open API, we also need to signup for a free key at https://api.nasa.gov/ Once you signed up at above link, you will be provided an API Key that we need to fetch an image from Nasa APOD (Astronomy Picture of the Day).
At this point we have all the keys and secrets we need to make an HTTP request to twitter and Nasa api. Lets create a new folder and a new file named 'keys.py' inside it and copy all the keys and secret from above links into this file.
So here is how keys.py file should look like
1#Twitter keys and secrets
2API_KEY= 'Agh73979Ukjgkjhkyrowrnnva'
3API_SECRET= 'Ajkhskjafhljkfhiepriue9r739bhh39r8y3983jkjdlfkjgju'
4ACCESS_TOKEN= '988888667627524654-ZdfdljfuriueriowwopwbGFUgiHKuou'
5ACCESS_SECRET= 'Ghiosfuaiouiurieytityoeityoein798nBJK989HKkl7'
6
7#Nasa API Key
8NASA_API_KEY = 'VuiwryiThjgj9789HKkH0808jhjgkjglh97986gd'
(Please don't copy these keys, these are dummy keys and wont work 😃
To tweet programmatically using python we need install a third party library called tweepy using pip install tweepy and also we need request module to make HTTP request using python. So lets install it using pip install requests
Now lets create a new file called nasabot.py and put below lines
1import tweepy, requests, os
2from keys import *
At this point we have imported all the modules required, lets create our entry point i.e. the main method
1if __name__ == "__main__":
2
3 # NASA Image API access
4 HOST = 'https://api.nasa.gov/planetary/apod?api_key='+ NASA_API_KEY
5 nasa_obj = requests.get(HOST)
With above code we made a HTTP request to Nasa rest api and we saved json object as nasa_obj. If you want to check how json response looks like , go to this link with DEMO key https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY From this response object we are going to need 'copyright', 'title' and 'url' of image. So lets get those and build a message that we will tweet with below codes.
1 if 'copyright' in nasa_obj.json():
2 message = 'Astronomy Picture of the Day: ' + nasa_obj.json()['title'] + ' copyright : '+nasa_obj.json()['copyright'] + ' #APOD'
3 else:
4 message = 'Astronomy Picture of the Day: ' + nasa_obj.json()['title'] + ' #APOD'
5
6 if 'url' in nasa_obj.json():
7 url = nasa_obj.json()['url']
8 else:
9 url = nasa_obj.json()['hdurl']
10 if nasa_obj.json()['media_type'] == 'image':
11 tweet_image(url,message)
At this point we have message to be posted on Twitter and image url from which we will download the image from Nasa. The last 'if' statement checks the media type from json response and calls tweet_image() if media type is 'image. Since Twitter requires every request to its api to use OAuth for authentication, this is why we are using Tweepy module. Lets put these below codes in a new function in nasabot.py
1def twitter_api():
2 #Lets authenticate our app with OAuth
3 auth = tweepy.OAuthHandler(API_KEY, API_SECRET)
4 auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
5 #Get the API instance
6 api = tweepy.API(auth) # create an API object
7 return api
This above function will call Twitter api with keys and secrets and will return an instance of OAuthHandler which we will use to post a tweet in next step.
Finally lets create tweet_image() function that we discussed above to download an image from Nasa api and tweet that image.
1# Tweet an image with status and hashtag
2def tweet_image(url,message):
3 api = twitter_api()
4 filename = 'temp.jpg'
5 request = requests.get(url, stream=True)
6 if request.status_code == 200:
7 with open(filename, 'wb') as image:
8 for chunk in request:
9 image.write(chunk)
10 api.update_with_media(filename, status=message)
11 os.remove(filename)
12 else:
13 print("Unable to download image")
In above function, first we are calling twitter_api() function to get the OAuthHandler instance, then we are downloading image using Nasa's open api and finally we are calling update_with_media() function to tweet the image. Once we tweet the image we are deleting the image from our local directory using os.remove() function. That's it! our Nasabot is ready 😃
Our final nasabot.py should look like this
1import tweepy,request,os
2from keys import *
3
4
5def twitter_api():
6 # Lets authenticate our app with OAuth
7 auth = tweepy.OAuthHandler(API_KEY, API_SECRET)
8 auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
9 # Get the API instance
10 api = tweepy.API(auth) # create an API object
11 return api
12
13
14# Tweet an image with status and hashtag
15def tweet_image(url, message):
16 api = twitter_api()
17 filename = 'temp.jpg'
18 request = requests.get(url, stream=True)
19 if request.status_code == 200:
20 with open(filename, 'wb') as image:
21 for chunk in request:
22 image.write(chunk)
23 api.update_with_media(filename, status=message)
24 os.remove(filename)
25 else:
26 print("Unable to download image")
27
28
29if __name__ == "__main__":
30
31 # NASA Image API access
32 HOST = 'https://api.nasa.gov/planetary/apod?api_key=' + NASA_API_KEY
33 nasa_obj = requests.get(HOST)
34
35 if 'copyright' in nasa_obj.json():
36 message = 'Astronomy Picture of the Day: ' + \
37 nasa_obj.json()['title'] + ' copyright : ' + \
38 nasa_obj.json()['copyright'] + ' #APOD'
39 else:
40 message = 'Astronomy Picture of the Day: ' + \
41 nasa_obj.json()['title'] + ' #APOD'
42
43 if 'url' in nasa_obj.json():
44 url = nasa_obj.json()['url']
45 else:
46 url = nasa_obj.json()['hdurl']
47 if nasa_obj.json()['media_type'] == 'image':
48 tweet_image(url, message)
49
Congratulations! with just few lines of code, we developed a Twitter bot that can tweet an image from Nasa's APOD server. I am using cron job to run this code every day that downloads and tweets one astronomy picture of the day. Don't forget to check this bot with handle name @Nasarobot.
We are going to build a CLI app using Python to change desktop wallpaper every given number of minutes. Every wallpaper downloaded from internet will be unique and our app will change the wallpaper based on the time we set.
2020-10-27
There are many ways to monitor and set alerts for your web server using third party apps but they don't come with free, be it Pingdom or Amazon's CloudWatch. In this post I am going to show how we can write and setup our own alert tool with just few lines of code
2020-10-29
In this post we are going to see how we can use Python to find the size of any file and folder. We will check how many files we have inside a folder and how many of them are empty files and how to delete those empty files.
2020-10-26
Monitoring CPU and memory usage are one of the top todo checklist for a backend engineer. Sometimes you wont even notice when your server is down due to high CPU usage unless you login and manually check the system.
2020-11-04