Learn to Code via Tutorials on Repl.it!

← Back to all posts
How to use Tweepy in Python!
CoolJames1610 (556)

How to use Tweepy in Python!

(CAN USE THIS TO MAKE A DISCORD TWITTER BOT!)

Please note that this tutorial isn't an in-depth tutorial on Tweepy.
Click this link to go to the offical docs


Hey there, I am back with another tutorial!

My MongoDB tutorial was very popular so I've decided to make a tutorial on Tweepy!


What is Tweepy?

Tweepy is a Python library for accessing the Twitter API.

What can I use Tweepy for?

You can use Tweepy to analyse tweets and for automation

How do I apply for a Twitter Developer Account?

You can sign up here

But wait a sec, how do I actually use tweepy?

Well that's what I am here to tell you about :)


Using Tweepy

So the first thing you are going to do is....

import tweepy

WOWOWOWOW - who would have guessed? xD

To even use Tweepy, (after you have got a dev account), you need to authorise :D

To make sure that your bot can only be used by yourself, once you generate the Access token & access token secret you cannot see what it is unless you generate a new set. This is to ensure that your bot cannot be hacked into if your account gets breached.

Now lets move onto the CODING!!!


Now here is the authentication script

auth = tweepy.OAuthHandler("[API KEY]", "[API SECRET KEY]")

This is the first part of the authentication
Next, you will imput your access token & access token secret. Without this, you cannot use Tweepy.

auth.set_access_token("[ACCESS TOKEN]", "[ACCESS TOKEN SECRET]")

To ensure that nobody can look inside your repl and steal your information, I would recommend having your repl set to PRIVATE or storing keys inside a .env file if you do not have the hacker plan.

Now the last part is to set up the API:

api = tweepy.API(auth)

And now you are connected!

So, in this tutorial I wil lbe showing you three different things:

  • Getting latest tweet by a user
  • Getting real-time data from Twitter
  • Replying to the real-time data from Twitter

Getting latest tweet by a user

Now this is incredibly simple.

All we have to do is to get the user by their name:

acc = api.get_user("MrBeast")

Now we can try and get the 'long' version of the tweet (more than about 200 characters) but if we cannot, we just use the normal version:

try:
  m = acc.status.extended_tweet.full_tweet 
except:
  m = acc.status.text

Then we can just print out 'm'.


Getting real-time data from Twitter

This is a bot more complicated.

First we use the in-built class feature of Tweepy to initialise the stream.

class TweetListener(tweepy.StreamListener):
  def __init__(self, api, limit = 10):
    self.tweet_count = 0
    self.TWEET_LIMIT = 0
    super().__init__(api)

Read up on the docs if you want more information :)

Then we want to collect the tweets and we do this by:

def on_status(self, status):
  try:
    tweet_text = status.extended_tweet.full_text
  except:
    tweet_text = status.text
  self.tweet_count += 1
  return self.tweet_count != self.TWEET_LIMIT

Notice that we used the same method to get the tweets as in the first example.

We can also add

def on_connect(self):
  print("Connected!")

Just so that we know if connection to the API is successful.

Then the last bit of this stream is to start it.

api = tweepy.API(auth)
tweet_listener = TweetListener(api)
tweet_stream = tweepy.Stream(auth=api.auth, listener=tweet_listener)
tweet_stream.filter(track=["@MrBeast"], is_async=True)

We use the API to make sure that we are authenticated and then we can set up the stream.

Twitter has rules over this and you can only get so many messages in like 15 minutes so we can add a filter so that we do not bombard and run out of tweets to get. We can use track to only get messages from a certain person or without the '@', a keyword.


Replying to the real-time data from Twitter

This is a custom bit that I built myself. You may find something similar online but I doubt it.

So, we go back to the on_status function and we add a bit to it so we can tweet from Python.

def on_status(self, status):
  try:
    tweet_text = status.extended_tweet.full_text
  except:
    tweet_text = status.text
  keywords = ["Please add", "add", "please add"]
  print(f"Screen name: {status.user.screen_name}")
  print(f"     Status: {tweet_text}")
  print(f"   Tweet_ID: {status.id_str}")
  for each in keywords:
    if each in tweet_text:
      api.update_status(status="Thank you for your feedback ❤️", in_reply_to_status_id=status.id_str,)
      print("replied! :D")
    break
  print()
  self.tweet_count += 1
  return self.tweet_count != self.TWEET_LIMIT

So, after we identity whether the tweet an be extended or not, we have some keywords that we want to reply to if the tweet contains them.

print(f"Screen name: {status.user.screen_name}")
print(f"     Status: {tweet_text}")
print(f"   Tweet_ID: {status.id_str}")

Screen name is the author like MrBeast or Twitter who has sent the tweet.
Status is the tweet that they have sent.
Tweet_ID is the ID of the tweet. This is the most important part as it allows us to reply to it.

for each in keywords:
  if each in tweet_text:
    api.update_status(status="Thank you for your feedback ❤️", in_reply_to_status_id=status.id_str,)
    print("replied! :D")
  break
print()

Now we loop over each entity in the keywords list. Then we check whether each can be found in the tweet.
We use the api.update_status() to tweet out from our program.
status refers to what we want to say and in_reply_to_status_id is the command we can use to specifically reply to a tweet.

Note that is you do not use in_reply_to_status_id then your program will reply to all tweets that contain your keywords. Twitter does not allow you to carelessly tweet out and your account may be blocked.

We can add print("replied! :D") so that we know our program has done what we wanted it to.


And that's it! Remember to check out the docs and the Twitter's developer policy!

I hope you have enjoyed found this tutorial useful!

If you have any questions about Tweepy or you would like me to try and create a program for you then please comment! Thanks :D

Running the project won't work btw :P but use the code to start your own :)

Here is the template

Here is the project

Thanks,
@CoolJames1610

Commentshotnewtop
ernopp (2)

Hey

Did you find a way to run this bot continuously using repl.it?

I wrote a similar bot (https://repl.it/@ernopp/ShopOnSmile-Python) but then had to host it on heroku because if I use uptime robot to regularly open the repl to run it, it won't have the right auth so can't grab the ENV variables. Did you find a way to get around that?

Cheers

CoolJames1610 (556)

@ernopp I've used uptime robot and it has worked perfectly for me :)
awesome bot btw :P

ernopp (2)

@CoolJames1610 huh.. would you mind describing / showing how you store your API keys? my issue seemed to be that uptime robot didn't have the right authentication to load the .env file

CoolJames1610 (556)

@ernopp I stored my private info in a .env file. Then I used flask so that the uptime robot could ping the website repl makes and that's how your bot will run continuously.

ZDev1 (367)

There is an error in your project

CoolJames1610 (556)

@ZDev1 you are not supposed to run the project xD

ZDev1 (367)

@CoolJames1610 but u link it in the post
so I do

CoolJames1610 (556)

@ZDev1 bruh but i said at emd of project that running project wont work

CoolJames1610 (556)

@ZDev1 nope i wrote that before

firefish (308)

Discord twitter bot. Hm........