How to build an A.I powered Twitter Bot using Tweepy python library 2022

Welcome back! Today’s blog is about how you can create an A.I powered Twitter bot using the well-known python library Tweepy, which will generate tweets on its own without your interaction, is not that amazing? Imagine that you have a bot creating tweets on a topic for you 24 hours even if you are sleeping!

Github: https://github.com/kachkolasa/twitter-bot

Example

Before we start let’s see some examples of the tweets that the bot generated.

How to create a twitter bot using tweepy python library 2022
How to create a twitter bot using tweepy python library 2022

Look at those cool tweets, I even didn’t know about the Reactstrap but my bot knows about it. I only told my bot to generate tweets on CSS libraries and it generated it automatically and even tweeted it on its own. I feel like Tony Stark 😉

If you prefer Video then please watch this otherwise you can continue the blog post 🙂

What libraries we will be using?

This Twitter bot was possible because of two free python libraries, Tweepy and OpenAI.

Tweepy: We will be using Tweepy to interact with our Twitter account and publish new tweets. There is a lot of things you can do with Tweepy but for now, we are only going to use it to publish tweets.

You can install Tweepy using this command: pip install tweepy

OpenAI: OpenAI is awesome! We will use OpenAI to generate the tweets, we will only give it the topic or subject that you want to tweet on and it will generate the tweets automatically, here is another fun fact, it can also generate tweets on a hashtag!

You can install OpenAI using this command: pip install openai

Let’s start coding the Twitter bot

Before we start, you will need to get some API keys from the Twitter developer, the keys we need are API Key, API Key Secret, Access Token, and Access Token Secret. You will need to create a project and then an app within that project. Another thing to be remembered is that you will need to upgrade your account from Essential to Elevated so that we can publish tweets using our Twitter bot. And to do that you have to go to Products > Twitter API v2 > Elevated (under the title of the page) and then you will need to fill out a form that one of the developers of Twitter will read and respond to you. They usually say that it takes 48 hours to reach but for me, it was just a few hours.

And also you will need to get the API key for OpenAI, you will need to sign up and then click on the profile icon on the top right corner and then click on view API keys, and then you should see your API key.

Now let’s import the python libraries:

  1. import tweepy, openai, random

As described before OpenAI will generate the tweets and Tweepy will publish them. And the random library will just select a random topic from a list.

Now let’s start TwitterBot() class

  1. class TwitterBot():
  2.  
  3. api_key ="YOUR API KEY FROM TWITTER"
  4. api_key_secret ="YOUR API KEY SECRET FROM TWITTER"
  5. access_token="YOUR ACCESS TOKEN FROM TWITTER"
  6. access_token_secret="YOUR ACCESS TOKEN SECRET FROM TWITTER"
  7.  
  8.  
  9. #OpenAI
  10. openai.api_key = "OPEN AI KEY"

In the above codes, we are just creating a class naming it TwitterBot(), and then we are just assigning some values to api_key, api_key_secret, access_token, access_token_secret variables. The next thing we did is setting up the API key for OpenAI using the openai.api_key method.

Now let’s connect with the Tweepy library

  1. class TwitterBot():
  2.  
  3. api_key ="YOUR API KEY FROM TWITTER"
  4. api_key_secret ="YOUR API KEY SECRET FROM TWITTER"
  5. access_token="YOUR ACCESS TOKEN FROM TWITTER"
  6. access_token_secret="YOUR ACCESS TOKEN SECRET FROM TWITTER"
  7.  
  8.  
  9. #OpenAI
  10. openai.api_key = "OPEN AI KEY"
  11.  
  12.  
  13. # Connecting to Twitter
  14. auth = tweepy.OAuthHandler(api_key, api_key_secret)
  15. auth.set_access_token(access_token, access_token_secret)
  16. api = tweepy.API(auth, wait_on_rate_limit=True)

The codes added to the bottom are connecting with Twitter using the Tweepy library.

  1. class TwitterBot():
  2.  
  3. api_key ="YOUR API KEY FROM TWITTER"
  4. api_key_secret ="YOUR API KEY SECRET FROM TWITTER"
  5. access_token="YOUR ACCESS TOKEN FROM TWITTER"
  6. access_token_secret="YOUR ACCESS TOKEN SECRET FROM TWITTER"
  7.  
  8.  
  9. #OpenAI
  10. openai.api_key = "OPEN AI KEY"
  11.  
  12.  
  13. # Connecting to Twitter
  14. auth = tweepy.OAuthHandler(api_key, api_key_secret)
  15. auth.set_access_token(access_token, access_token_secret)
  16. api = tweepy.API(auth, wait_on_rate_limit=True)
  17.  
  18.  
  19. # Creating Tweets
  20. prompts = [
  21. {
  22. "hashtag": "#meme",
  23. "text": "post a meme on twitter bots"
  24. },
  25. {
  26. "hashtag": "#technology",
  27. "text": "tweet something cool for #technology"
  28. },
  29. {
  30. "hashtag": "@kachkol_asa",
  31. "text": "tweet something cool for @kachkol_asa from twitter"
  32. },
  33. ]

Now we are creating the prompts for OpenAI or you can say the topics, and also we are adding some hashtags. You can add yours as well, of course, just change the hashtag and text or add new ones to the list.

  1. class TwitterBot():
  2.  
  3. api_key ="YOUR API KEY FROM TWITTER"
  4. api_key_secret ="YOUR API KEY SECRET FROM TWITTER"
  5. access_token="YOUR ACCESS TOKEN FROM TWITTER"
  6. access_token_secret="YOUR ACCESS TOKEN SECRET FROM TWITTER"
  7.  
  8.  
  9. #OpenAI
  10. openai.api_key = "OPEN AI KEY"
  11.  
  12.  
  13. # Connecting to Twitter
  14. auth = tweepy.OAuthHandler(api_key, api_key_secret)
  15. auth.set_access_token(access_token, access_token_secret)
  16. api = tweepy.API(auth, wait_on_rate_limit=True)
  17.  
  18.  
  19. # Creating Tweets
  20. prompts = [
  21. {
  22. "hashtag": "#meme",
  23. "text": "post a meme on twitter bots"
  24. },
  25. {
  26. "hashtag": "#technology",
  27. "text": "tweet something cool for #technology"
  28. },
  29. {
  30. "hashtag": "@kachkol_asa",
  31. "text": "tweet something cool for @kachkol_asa from twitter"
  32. },
  33. ]
  34.  
  35. def __init__(self):
  36. error = 1
  37. while(error == 1):
  38. tweet = self.create_tweet()
  39. try:
  40. error = 0
  41. self.api.update_status(tweet)
  42. except:
  43. error = 1

Now let’s define the __init__ method, what this method is doing is that it generate a tweet using the create_tweet() method (which we need to define later), and then publishing the tweet using the update_status() method in Tweepy. It also checks if there was an error in the process like if the text was so much then it will generate another one.

  1. class TwitterBot():
  2.  
  3. api_key ="YOUR API KEY FROM TWITTER"
  4. api_key_secret ="YOUR API KEY SECRET FROM TWITTER"
  5. access_token="YOUR ACCESS TOKEN FROM TWITTER"
  6. access_token_secret="YOUR ACCESS TOKEN SECRET FROM TWITTER"
  7.  
  8.  
  9. #OpenAI
  10. openai.api_key = "OPEN AI KEY"
  11.  
  12.  
  13. # Connecting to Twitter
  14. auth = tweepy.OAuthHandler(api_key, api_key_secret)
  15. auth.set_access_token(access_token, access_token_secret)
  16. api = tweepy.API(auth, wait_on_rate_limit=True)
  17.  
  18.  
  19. # Creating Tweets
  20. prompts = [
  21. {
  22. "hashtag": "#meme",
  23. "text": "post a meme on twitter bots"
  24. },
  25. {
  26. "hashtag": "#technology",
  27. "text": "tweet something cool for #technology"
  28. },
  29. {
  30. "hashtag": "@kachkol_asa",
  31. "text": "tweet something cool for @kachkol_asa from twitter"
  32. },
  33. ]
  34.  
  35. def __init__(self):
  36. error = 1
  37. while(error == 1):
  38. tweet = self.create_tweet()
  39. try:
  40. error = 0
  41. self.api.update_status(tweet)
  42. except:
  43. error = 1
  44.  
  45.  
  46. def create_tweet(self):
  47. chosen_prompt = random.choice(self.prompts)
  48. text = chosen_prompt["text"]
  49. hashtags = chosen_prompt["hashtag"]
  50.  
  51. response = openai.Completion.create(
  52. engine="text-davinci-001",
  53. prompt=text,
  54. max_tokens=64,
  55. )
  56.  
  57. tweet = response.choices[0].text
  58. tweet = tweet + " " + hashtags
  59. return

Now comes the most interesting part, to generate the tweets using A.I. The create_tweet() method is randomly selecting a topic from the prompts list and then creating some text (tweet). That is possible because of OpenAI, we are using the text-davinci-001 engine to generate the tweet, there are much more engines and other parameters in OpenAI, I strongly suggest checking on OpenAI Playground.

Now we have an A.I powered Twitter bot ready, we only need to run the TwitterBot() class, and boom, it will do all the things on its own. Here are the final codes:

  1. import openai, tweepy, random
  2.  
  3. class TwitterBot():
  4.  
  5. api_key ="YOUR API KEY FROM TWITTER"
  6. api_key_secret ="YOUR API KEY SECRET FROM TWITTER"
  7. access_token="YOUR ACCESS TOKEN FROM TWITTER"
  8. access_token_secret="YOUR ACCESS TOKEN SECRET FROM TWITTER"
  9.  
  10.  
  11. #OpenAI
  12. openai.api_key = "OPEN AI KEY"
  13.  
  14. # Connecting to Twitter
  15. auth = tweepy.OAuthHandler(api_key, api_key_secret)
  16. auth.set_access_token(access_token, access_token_secret)
  17. api = tweepy.API(auth, wait_on_rate_limit=True)
  18.  
  19. # Creating Tweets
  20. prompts = [
  21. {
  22. "hashtag": "#meme",
  23. "text": "post a meme on twitter bots"
  24. },
  25. {
  26. "hashtag": "#technology",
  27. "text": "tweet something cool for #technology"
  28. },
  29. {
  30. "hashtag": "@kachkol_asa",
  31. "text": "tweet something cool for @kachkol_asa from twitter"
  32. },
  33. ]
  34.  
  35.  
  36. def __init__(self):
  37. error = 1
  38. while(error == 1):
  39. tweet = self.create_tweet()
  40. try:
  41. error = 0
  42. self.api.update_status(tweet)
  43. except:
  44. error = 1
  45.  
  46. def create_tweet(self):
  47. chosen_prompt = random.choice(self.prompts)
  48. text = chosen_prompt["text"]
  49. hashtags = chosen_prompt["hashtag"]
  50.  
  51. response = openai.Completion.create(
  52. engine="text-davinci-001",
  53. prompt=text,
  54. max_tokens=64,
  55. )
  56.  
  57. tweet = response.choices[0].text
  58. tweet = tweet + " " + hashtags
  59. return tweet
  60.  
  61.  
  62. twitter = TwitterBot()
  63. twitter.create_tweet()

Thanks for reading this article, you can also read: How to make money as a web developer and How to become a web developer without any degree.

1 thought on “How to build an A.I powered Twitter Bot using Tweepy python library 2022”

Leave a Comment

Index