As part of my job, I will be running various social media campaigns especially using Twitter. When I meant, social media campaign, you often
- Harvest Tweets based on various keywords
- Post multiple tweets on your Twitter Account
- Follow multiple users
- Re-tweet the tweet from another user.
Even-though, there are a number of 3rd party software like TweetDeck for doing the same, I prefer to do it through my own custom software as it provides more flexibility. In this tutorial, you will learn how to tweet using Python. I will be using Tweepy package in Python to post tweets.
Example : At the end of this tutorial, you will learn how to send a tweet using Tweepy in Python.
Step 1 : First, you need to create a new App.
- Go to Twitter Apps, here is the link : https://apps.twitter.com/ and login using your Twitter Credentials
- Click on Create New App.
- Enter the Application name, description and the website URL. You can leave the Callback URL empty.
- Obtain the Consumer key and Consumer Secret Key. Make sure, that the Twitter App has the read and write permission.
- Also, generate the Access token and the Access Token secret. It is important that, you keep all these keys a secret. Do not share keys with anyone. You can always regenerate the Access Token and Access Token Secret.
Step 2 : Import Tweepy
In this example, we will be using Tweepy to post tweets to your Twitter account. You can install Tweepy using the command:
1
|
pip install tweepy
|
Step 3 : When you are tweeting, please make sure, that the number of characters is less than 140 characters. Here is the complete Python script to post the tweet “Hello, how are you doing today”.
Please note you can send a simple text message as well as HTML. It is much better to prepare email templates in HTML and replace the placeholders with relevant information in the templates.
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
|
import tweepy
def login_to_twitter(consumer_key, consumer_secret, access_token, access_token_secret):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
ret = {}
ret['api'] = api
ret['auth'] = auth
return api
def post_tweets():
consumer_key = 'your-consumer-key'
consumer_secret = 'your-consumer-secret'
access_token = 'your-access-token'
access_token_secret= 'your-access-token-secret'
message = "Hello,\nHow are you doing today"
api = login_to_twitter(consumer_key, consumer_secret, access_token, access_token_secret )
ret = api.update_status(status=message)
if __name__ == '__main__':
post_tweets()
|
I hope, you find this article very useful. If you have any doubts or have any comments concerning this tutorial, Please leave a comment or contact me. I would be glad to help.