Posting to Twitter using Python | Python Twitter Bot

Posting to twitter is very easy and you can directly use twitter API or you can use any library of your choice from twitter libraries page.

Here we are going to use our programming language of choice python and python library tweepy.

Step#1

Create a twitter app from https://apps.twitter.com/

Create Tweeter Application

  1. Please select unique application name. If anyone else has created application with same name, you will get error message.
  2. You can leave callback url empty

Step#2

Create access tokens as shown below

Create Access Tokens

Step#3 Unstall tweepy

I am using Python3.6 version, use following command to install tweepy

sudo python3.6 -m pip install tweepy

 

Step#4 Write Python program.

You can use following program for referencePython. This is working fine. You can modify as suited to your coding style and requirement.

# This is a sample tweeter bot program
# version : 0.1.0


import tweepy

def get_api(key_token):
auth = tweepy.OAuthHandler(key_token['consumer_key'], key_token['consumer_secret'])
auth.set_access_token(key_token['access_token'], key_token['access_token_secret'])
return tweepy.API(auth)

def main():
# Fill in the values noted in previous step here
key_token = { 
"consumer_key" : "some_value",
"consumer_secret" : "some_value",
"access_token" : "some_value",
"access_token_secret" : "some_value" 
}

api = get_api(key_token)

tweet = "Hello, world! This is first tweeter bot tweet"
status = api.update_status(status=tweet) 

if __name__ == "__main__":
main()

 

If you want to modify it further or want to add further options such as adding image along with text message, you please to following documentation

http://docs.tweepy.org/en/v3.5.0/

Feed free to let me know your feedback.