Introduction.
Twitter is one of the most widely used social media platforms in the world, with over 330 million monthly active users. It's a great place for people to share their thoughts, ideas, and opinions on various topics. However, as the number of users and tweets increases, it becomes harder to keep up with all the content that is being shared. This is where Twitter bots come in.
Twitter bots are automated programs that can perform various tasks on the platform, such as liking, retweeting, and replying to tweets. In this guide, we will show you how to create a smart Twitter bot using OpenAI's GPT-3, one of the most powerful language models available today.
Prerequisites
To follow this guide, you will need:
A Twitter account and developer account
A Python development environment
The following Python libraries: tweepy, io, PIL, os, requests, random, time, sys, openai
An OpenAI API key
Step 1: Setting up your Twitter developer account
The first thing you need to do is create a Twitter developer account. This will give you access to the Twitter API, which is needed to interact with the platform. Once you have created your developer account, you will need to create a new project and generate your API credentials (consumer key, consumer secret, access token, and access token secret).
Step 2: Setting up your Python environment
The next step is to set up your Python development environment. You will need to install the necessary libraries and create a new Python file.
# Import the necessary libraries
import tweepy
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
import os
import requests
import random
import time
import sys
import openai
Step 3: Authenticating with the Twitter API
Once we have our credentials, we can use the tweepy library to authenticate with the Twitter API. We first create an OAuthHandler object, passing in our consumer key and secret. We then set our access token and secret using the set_access_token method. Finally, we create an API object, passing in our authentication object and setting the wait_on_rate_limit attribute to True. This ensures that our bot doesn't exceed the rate limit set by Twitter.
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True)
Step 4: Setting up the Search Query
We then specify the search query we want to use to interact with tweets. In this example, we are using a combination of hashtags and keywords related to Kenya. We also set a maximum number of tweets that our bot will interact with.
search = '#UnfairKECOBOTerms OR #TaxTheRich OR Safaricom OR KCSE #andrewkibe OR #MasculinitySaturday OR #SavanisBookCentre OR #TheBookshopOfYourChoice'
maxNumberOfTweets = 1000000
Step 5: Retweeting and Liking Tweets
In this step, we use the tweepy Cursor object to search for tweets using our specified search query. For each tweet, we first check if it has been previously retweeted or liked by our bot. If not, we like the tweet and retweet it.
Here is the code snippet for this step:
for tweet in tweepy.Cursor(api.search_tweets, search).items(maxNumberOfTweets):
try:
# for each status, overwrite that status by the same status, but from a different endpoint.
status = api.get_status(tweet.id, tweet_mode='extended')
if status.retweeted == False and status.favorited == False:
print("###############################################################")
print("Found tweet by @" + tweet.user.screen_name)
tweet.favorite()
print("Liked tweet")
tweet.retweet()
print("Retweeted tweet")
In this code, we are using the tweepy Cursor object to search for tweets using the search variable we defined earlier. We are also limiting the number of tweets to maxNumberOfTweets. For each tweet, we first check if it has been previously retweeted or liked by our bot using the status variable, which is used to get the status of the current tweet. If the tweet has not been previously retweeted or liked, we like the tweet using the favorite() function and retweet it using the retweet() function.
Step 6: Generating a Reply using OpenAI's GPT-3
In this step, we use the OpenAI API to generate a reply to the tweeted text. We use the tweet text as the prompt for the GPT-3 model and set a maximum number of tokens for the response. We also set the temperature to 0.7 to make the response more diverse.
Code snippet:
prompt = textwrap.shorten(tweet.text, width=280)
response = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
max_tokens = 80,
n = 1,
stop=None,
temperature=0.7
)
reply_text = response["choices"][0]["text"]
Step 7: Sending the Reply
In this final step, we use the Twitter API to send the reply we generated in the previous step. We mention the original tweet's author and also use the in_reply_to_status_id parameter to ensure that the reply is in response to the correct tweet.
Code snippet:
api.update_status('@'+tweet.user.screen_name+''+reply_text, in_reply_to_status_id=tweet.id)
print("Replied to tweet")
Here is the final code:
import tweepy
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
import os
import requests
import random
import time
import sys
import openai
import textwrap
openai.api_key = "xxx"
#Accessing credentials from .env file
CONSUMER_KEY = "xxx"
CONSUMER_SECRET = "xxx"
ACCESS_TOKEN = "xxx"
ACCESS_TOKEN_SECRET = "xxx"
#Setting credentials to access Twitter API
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
#Calling API using Tweepy
api = tweepy.API(auth, wait_on_rate_limit=True)
#Search keyword
#got them from https://twitter-trends.iamrohit.in/kenya/nairobi
search = '#UnfairKECOBOTerms OR #TaxTheRich OR Safaricom OR KCSE #andrewkibe OR #MasculinitySaturday OR #SavanisBookCentre OR #TheBookshopOfYourChoice'
#Maximum limit of tweets to be interacted with
maxNumberOfTweets = 1000000
#To keep track of tweets published
count = 0
print("Retweet Bot Started!")
for tweet in tweepy.Cursor(api.search_tweets, search).items(maxNumberOfTweets):
try:
# for each status, overwrite that status by the same status, but from a different endpoint.
status = api.get_status(tweet.id, tweet_mode='extended')
if status.retweeted == False and status.favorited == False:
print("###############################################################")
print("Found tweet by @" + tweet.user.screen_name)
tweet.favorite()
print("Liked tweet")
tweet.retweet()
print("Retweeted tweet")
prompt = textwrap.shorten(tweet.text, width=280)
# Use the tweet text as the prompt for ChatGPT
response = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
max_tokens = 80,
n = 1,
stop=None,
temperature=0.7
)
reply_text = response["choices"][0]["text"]
# Send the reply
api.update_status('@'+tweet.user.screen_name+''+reply_text, in_reply_to_status_id=tweet.id)
print("Replied to tweet")
print("###############################################################")
#Random wait time
timeToWait = random.randint(95, 115)
print("Waiting for "+ str(timeToWait) + " seconds")
for remaining in range(timeToWait, -1, -1):
sys.stdout.write("\r")
sys.stdout.write("{:2d} seconds remaining.".format(remaining))
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("\rOnwards to next tweet!\n")
except tweepy.errors.TweepyException as e:
print(str(e))
Conclusion:
With this step-by-step guide, we have created a smart twitter bot that can interact with tweets and generate responses using OpenAI's GPT-3. The bot is able to search for tweets using a specified search query, like and retweet them, generate a response using the tweet's text as a prompt, and reply to the tweet. The use of OpenAI's GPT-3 for generating responses adds an intelligent touch to the bot, making it a powerful tool for social media interaction. You can modify the code to suit your requirements and use it for various applications like customer service, lead generation, and more.
Top comments (2)
Twitter is charging for the apis so I'm not sure what changed. Thanks Elon.