Scheduling a tweet using Python and Django
1. The problem statement
2. Persistence
3. Scheduling
4. How to install and set it up for yourself
5. Possible improvements
6. Usages
Tweet regularly
First, I want to clarify that I am not a big fan of all the sh*t that goes on over Twitter where a user who started programming 7 days ago acts as an expert and is having a ton of followers and on the other hand, people with a lot of experience has none.
It doesn’t matter if I like it or not, I have to increase the number of followers to sound more genuine and the key ingredient for that is 2. Persistence
3. Scheduling
4. How to install and set it up for yourself
5. Possible improvements
6. Usages
tweeting regularly
.
But it’s hard to find time for tweeting, especially when it doesn’t come naturally to you. It’s pretty hard to come up with the content itself and it is even hard to tweet about it.
To solve this, I tried to come up with a web app in which I can schedule tweets for say the next seven days or so.
I recently read the post written by my fellow writer on how to send tweets using tweepy
and was really confident that I can do it.
How to create a webscraping twitter bot in Python
#python
#web-scraping
October 23, 2020
8 mins read
The problem statement
It is really important to understand what we want to achieve otherwise we end up building something totally different. So, I divided the projects into small chunks so that it is easily achievable.- Persistence
tweet data
, tweeting date and time
and keeping the log of what all tweets have already been shared
.
- Scheduling
Consumer-producers
type scheduling was too much for this small project.
- Documentation
Persistence
I decided to use the already presentsqlite
database to store the related data for tweets.
This is how the models.py
file looks for the scheduler
app.
from django.db import models
class TwitterSchedulerModel(models.Model):
tweet = models.TextField(max_length=240)
tweet_at = models.DateTimeField()
created_at = models.DateTimeField(auto_now_add=True, editable=False)
sent = models.BooleanField(default=False)
- tweet - The tweet itself
- tweet_at - When does someone want to tweet.
- created_at - A datetime thing to know when you created the data entry( very helpful for debugging purposes).
- send - Whether the tweet was sent or not.
Scheduling
I decided to use apscheduler for this small use case. This is how the code of the scheduler looks like.import logging
import arrow
import os
import tweepy
from twitter.models import TwitterSchedulerModel
logger = logging.getLogger(__name__)
def send_tweets(consumer_key, consumer_secret, access_token,
access_token_secret):
expired_tweets = TwitterSchedulerModel.objects.filter(
sent=False, tweet_at__lte=arrow.utcnow().datetime)
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
if expired_tweets.count() == 0:
logging.info("No tweet to send as of now")
for db_tweet in expired_tweets:
logging.info('sending tweet')
api.update_status(db_tweet.tweet)
logging.info('tweet sent')
db_tweet.sent = True
db_tweet.save()
def tweet_scheduler():
if (os.environ.get('CONSUMER_KEY') or os.environ.get('CONSUMER_SECRET') or
os.environ.get('ACCESS_TOKEN') or os.environ.get('TOKEN_SECRET')):
consumer_key = os.environ.get('CONSUMER_KEY')
consumer_secret = os.environ.get('CONSUMER_SECRET')
access_token = os.environ.get('ACCESS_TOKEN')
access_token_secret = os.environ.get('TOKEN_SECRET')
send_tweets(
consumer_key, consumer_secret, access_token, access_token_secret)
else:
raise NotImplementedError('Set environment variables correctly')
tweet_scheduler
is the entry function. First, we are checking whether the environment variables are set or not.
After that, we are calling the send_tweet
function where we get all the database entries for which sent_tweet
time has already passed and use the tweepy
library to send the tweet. Finally, we update the database to save the updated value.
How to install and set it up for yourself
Clone the repo
The first step is to clone the repo. https://github.com/singh1114/schedule-tweetgit clone [email protected]:singh1114/schedule-tweet.git
Install the requirements
cd schedule-tweet
virtualenv
and install the requirements. Please read a little about virtual environment if you don’t know about it.
pip install -r requirements.txt
Run migrations to set up the database
cd scheduletweet
python manage.py migrate
Create a super user
python manage.py createsuperuser
Export the creds
Now if you were following the tutorial correctly and if you have read thetweepy
post that I shared earlier, you should have your Twitter API key and other creds handy.
If you haven’t read it already, you can visit https://developer.twitter.com/ and create an app to get all the credentials or you can read this post if you are facing problems to figure it out. If you are still facing any issue, feel free to ping me anywhere.
Once you have them you have to export them to your shell,
export CONSUMER_KEY="#"
export CONSUMER_SECRET="#"
export ACCESS_TOKEN="#"
export TOKEN_SECRET="#"
Run the server
python manage.py runserver
Open the admin window and schedule a tweet after sometime
Visit http://127.0.0.1:8000/admin to login withsuperuuser
creds and twitterschedulermodel to create a new scheduled tweet.
not_sent
state, it will trigger the tweet in the next 5 minutes when the scheduler runs.
That’s it for today’s post. If you find an issue while trying it out, do let me know in the comments section, I will be happy to help.
Possible improvements
The current system doesn’t allow us to send images in the tweets, we can accommodate for that as well. I don’t think that will be hard. Feel free to raise Pull Requests to the repo if you find any issue.Usages
We have used the software to send 50 tweets as of now and gained almost 18 followers to our profile organically.About Author
Ranvir Singh
Greetings! Ranvir is an Engineering professional with 3+ years of experience in Software development.
Please share your Feedback:
Did you enjoy reading or think it can be improved? Don’t forget to leave your thoughts in the comments section below! If you liked this article, please share it with your friends, and read a few more!