Create A Twitter Bot With Python

Creating a Twitter Bot with Python and Tweepy Library

=====================================================

To create a Twitter bot that posts images, we will use the Tweepy library, which is a Python client for the Twitter API. The first step is to set up our Twitter account and obtain our access token and access secret.

Access Token and Access Secret

-----------------------------

The Tweepy library requires us to specify two parameters: the access token and the access secret. These are used to authenticate our request to the Twitter API. To get these values, we need to go to our Twitter settings page and follow the instructions provided by Twitter to obtain our access tokens.

Here's how you can do it:

```

# Import the tweepy library

import tweepy

# Set up your consumer key, consumer secret, and access token

consumer_key = 'your_consumer_key_here'

consumer_secret = 'your_consumer_secret_here'

access_token = 'your_access_token_here'

access_secret = 'your_access_secret_here'

# Set up the API variable

api = tweepy.API(auth=tweepy.OAuthHandler(consumer_key, consumer_secret),

access_token=access_token,

access_token_secret=access_secret)

```

Logging in to Twitter

------------------

The next step is to log in to our Twitter account using the `tweepy.OAuthHandler` class. This class takes our consumer key and consumer secret as parameters, which are used to authenticate our request.

Here's how you can do it:

```

# Create an API variable

api = tweepy.API(auth=tweepy.OAuthHandler(consumer_key, consumer_secret),

access_token=access_token,

access_token_secret=access_secret)

```

Moving into the Models Folder

---------------------------

After logging in to our Twitter account, we need to move into the models folder that contains all of our scraped images. We can do this by changing the current directory using the `os.chdir()` function.

Here's how you can do it:

```python

# Import the os module

import os

# Move into the models folder

os.chdir('/path/to/models/folder')

```

Looping over Images and Posting Them

-----------------------------------

Once we are in the models folder, we need to loop over each image file and post it on Twitter. We can do this using a for loop that iterates over the files in the directory.

Here's how you can do it:

```python

# Import the os module

import os

# Loop over the images in the models folder

for model_image in os.listdir():

if model_image.endswith(".jpg") or model_image.endswith(".png"):

# Post each image as media in our tweet

api.update_with_media(model_image)

```

Posting a Tweet with Media

-------------------------

The `api.update_with_media()` function takes an image file path as its parameter. This will post the image on Twitter and return a boolean value indicating whether or not the update was successful.

Here's how you can do it:

```python

# Post each image in the models folder

for model_image in os.listdir():

if model_image.endswith(".jpg") or model_image.endswith(".png"):

# Post each image as media in our tweet

api.update_with_media(model_image)

```

Sleeping for a Set Amount of Time

---------------------------------

Finally, we need to sleep for a set amount of time between tweets. This is done using the `time.sleep()` function.

Here's how you can do it:

```python

import time

# Sleep for 3 seconds before posting the next image

for model_image in os.listdir():

if model_image.endswith(".jpg") or model_image.endswith(".png"):

api.update_with_media(model_image)

time.sleep(3)

```

Conclusion

----------

Creating a Twitter bot that posts images is a fun and interesting project. By using the Tweepy library, we can easily interact with the Twitter API and post our own content. This article has shown you how to create this type of bot from scratch, including setting up your access tokens, logging in to Twitter, moving into the models folder, looping over images and posting them, and sleeping for a set amount of time between tweets.

"WEBVTTKind: captionsLanguage: entoday we are going to create a twitter bot that will post images of models onto a twitter account for us so this is what we're going to end up with when we're finished here on the left here we see a script that is going to scrape a web page for images and it will save them in a folder for us on the right here we have our have our python bot script which is going to go ahead and post those images to our twitter account at a set time interval okay so i'll run it for you guys so we can see how it works here and then we're going to go and review each line uh each line of the code line by line so here is what we are going to end up with this is the account i've got set up here called the modelbot and we're going to send out our first tweet in just a minute here so let's go ahead and get this and get this script running so here we have i'll show you guys right now i have it set at a time interval of three seconds so every three seconds is going to tweet obviously if we were running this on a separate server we would change that time interval because tweeting every three seconds might be considered a little excessive but let's go ahead and run this here so first off i want to show you guys we'll run this we'll run the script that'll scrape the images first okay so let's go ahead i'm going to show you guys the the desktop here and um just to show you so you can see the folder that we've got so right here we've got our empty folder or not empty folder but we have our two scripts in our folder so let's go ahead here and now run our script that is going to get the pictures for us okay so here we go and so right now it is going to this web page that we that i specified here and it's pulling all the photos from that web page and creating a folder that will pop up in this in this directory here so there you see our folder just got popped up and now when we open it we have all these pictures here from the website that we scraped off the website off the website alright so now that we've got those pictures let's go ahead and run our other script that is going to be the twitter bot for us okay so we've got that and now as we saw before don't currently have any tweets um for this for this twitter bot but now we're going to go ahead and run this guy right here all right and this is going to go ahead and send out tweets for us at a three second interval so let's go ahead and refresh our page here and there we go already got two tweets coming out and refresh again another tweet and there we go so again you can adjust that time interval as you want uh depending on how many tweets you want to send out and or what you're tweeting about okay so let's go back and uh close out that script before we get some serious uh twitter overload here and just one sec okay so there we go that will finish that off so now we're going to review our scripts here and so if you guys want to make this we're going to walk through step by step how you would go about doing that and so we can understand each line of the code here so we'll start with how we scrape the images from the web page so if depending on what kind of twitter bot you want to make we can or you can use different things so in this case i wanted it to send out images but you can also do there are also twitter bots that'll send out any kind of thing so some do like poetry some do memes some do a bunch of different things so whatever you guys want your twitter about to do or be you want to go ahead and get that data that it's going to that is going to be used to send out those tweets so as far as this script goes we'll review this one quickly and then get over to the to the bot itself but we have a url here that we are moving to and this is the url that has the pictures on it so you see we can go to this quickly here and we'll take a look at that all right so here's the website and it is grabbing pictures from this website here based there it is based on our url so it's grabbing these pictures scraping these pictures off the website and creating a folder for us and saving them to that so we go ahead we do that we're using the module uh we're using the request module the beautiful suit module and the os module so in this case request is a module that allows you to make requests to web pages a beautiful soup is a module for us kind of downloading the html that makes up those web pages so we can easily parse through that and find what we want and then os is used to create the folder in the directory that our scripts are in so we've got that url go to that url in our next line here we have the page so this is where we're actually requesting the url so we're requesting a response from the server on that page and then we are creating a our soup which is the html that makes up that website that we requested so once we get that we are using the bs4 uh method find all which is going to find all the images that are on that web page for us and then it is going ahead and we're going to create the directory that we want to store those images in okay so what this is doing is it's saying if the models folder does not exist in the folder that we are currently in then we want to make that folder and then otherwise we want to just change our current directory to that folder that we're in because when your python script saves files or saves uh pictures in this case to the folder it's going to save them unless you specify otherwise to the current working directory or the current folder that you're in so we go ahead and we change uh we change our current directory to the models folder that we created so next up here we have a variable that is going to be used to uh as we add our pictures we want to specify them being slightly different obviously because we don't want to overwrite the same file as we save our pictures so we have our x equals zero and we're going to increment that for each picture in order to save each picture as one two three etc okay so now we have a loop here and what we're doing with this loop is we are saying for each image that is in our uh image tags soup that we have here so this is returning us a nice list of a nice list of image tags and that but we don't have that's just the raw html we don't we want to extract the the source url from each of those um image elements okay so we're going to go ahead here and so for each image for each image in that list or for each image html element that is in that in that list then we want to go ahead here and we want to get the source so we're saying we're declaring a variable called url and we are setting that to be the source of the image so in this case we can reference the source attribute or src attribute of the of the image tags with our bs4 module by specifying the image and then specifying within within square brackets what the attribute that we want to get is so then once we have that url we want to go ahead and we want to navigate directly to that url then we want to go ahead and so if the source status code equals 200 so if we get a response there we want to go ahead and we want to open up a new file and this is the file that that is a jpeg file so you can see here with open model plus string x so we have just the model text plus the current value that our x integer is at so remember we're incrementing that in order to create new uh create new image files and we want to save that with the dot jpeg extension and we want to be able to write to that file so we're going to go ahead and we're going to create that jpeg file and we want to specify that we're going to write to it so then we're going to go ahead and we're going to say um f dot write so what this is is it's opening up this file and it's saying let's represent this file that we opened up as as f so we're going to say f dot right so we want to write to that file and then we want to write the the request that we got the content of the request that we got so that is what's going to capture the image that loads when we navigate to that url after that we want to close the file and then we want to increment x by one so we can move on to our next image file so if at any point during that loop there is some some exception thrown then we just want to continue our loop with the next picture because for some of these images uh they won't always get a proper request or there will be some other small error that occurs when we are navigating to that page that the images is located on so if that is the case then we want to go ahead and we just want to pass over and pass over that image and move to the next one okay so that does it for our our image scraping so now we're going to go ahead here and talk about our model script so this is the uh the script that creates our twitter bot so we're using three libraries in this case we're using the tweepy library which is a python library for accessing twitter via the api so in api is just an application programming interface which is essentially a lot of code that is written to directly access certain data within the uh within twitter and to be able to make certain um to be able to form certain operations such as posting new status updates posting pictures a following and a bunch of other things you can do on twitter so we're going to use the tweepy library in order to make our code more efficient next up here we have the time module which we are using to specify how much time we want to uh rest in between our tweets and then we have the os module in order to move over to our folder that is that contains our our pictures that we scraped off the web so next up here this is an important part for creating this guys so we have the credentials and the way what this is is how you log into your twitter account that your new twitter bot account that you created so if you guys are building this go ahead and create a new account on twitter and then you want to go ahead once you've created that account you want to navigate over to this page here so that's apps.twitter.com backslash app backslash new and just navigate to that page and it's going to bring this up here so what this is is you need to create a or you need to tell twitter that you're creating an application in order to get what are known as the api keys so you can access your account directly to the api interface that twitter provides so in this case you create a name for your bot that you're creating you create a description for your bot and then you can just throw in any old website you want if you want to go ahead and create a website specifically for your bot go ahead and do that and specify that there but otherwise go ahead and throw in whatever website and do make sure that you type in https colon backslash backslash not just www whatever name of the website you are creating is because otherwise it's going to throw you a little error there then you just go ahead and check this off and create your twitter application so once you do that you're going to have access to a couple of these keys here there is a tab that you want to navigate to once you're within that that will generate these keys for you so you can access the twitter api from within your script so that'll give you your consumer key your consumer secret your access token and your access secret so these are just long strings of numbers and letters that are going to be used to access your twitter api so go ahead and create variables to represent those those keys and those secrets and then go ahead and store those strings within those variables so next up here we're going to use a couple different functions from the tweepy library in order to log into our api so the first one is the oauth handler so you see tp here which we said up at the top here we want to import tweepy as tp so when we're referencing the tweepy library from within our code we can reference it just by the by tp instead of having to type out tweepy and so we have tp.o off handler which is how we're going to log into our or our authenticate with the twitter server in order to log into our account so next up here we want to take that off that that value that we are representing with auth and we want to go ahead and set the access token again this is using a function within the tweep library and that specifies two parameters which are the access token and the access secret so you go ahead and you add those in there and then you have then you're ready to log in so your next line here is to create the api variable and then go ahead and log in via the uh tweepy api function so again we specify uh tp.api with auth as our as our single parameter and remember we set the consumer key the consumer secret and the access token the access secret with these two lines above so now we've logged into our twitter api so what we want to do is post these images so in this case we want to go ahead and change the current directory that we are in to the models folder that we saved all our images that we scraped in so in this case here we are using the os dot chdir function which is basically just saying change the current folder that we are operating in to the models folder so in this case your script first starts running when it's first runs it's uh it's the current directory that it runs in is the directory that the scripts themselves are located in so remember we created that folder in that same folder that the scripts are in but now we want to move into that folder that we created that has the pictures so we're going to move into that folder with that line and then next up here we're going to loop over the files that are within that folder in order to post them each at a post each each picture because in this case they're going to be pictures at a set time interval so we go ahead here and we say for we're creating a variable called model image which is going to represent each file as we iterate over the files that are within the uh folder that we created and so we're going to say for each image that is in the or for model image in the in the directory list so we're using the uh the list dir the list dir function that is part of the os module again which will list all the files that are within our folder for us so that allows us to iterate over them and in this case we want to use again the tweepy function which is the update with media function so as far as this goes there are a couple different functions that are there multiple functions you can use for the different things you want to do on twitter with tweepy but in this case we want to use the update with media function in order to paste post a photo this can also be used to post a video or post a gif so we can go ahead and say update with media another function you can use is update status or update underscore status and then you pass a string as your parameter which is going to be just whatever text you want to post say you just wanted to send out a text based tweet you would use update status so after we go ahead and we send out our tweet then we want to go ahead and sleep so that's going to tell our script to basically pause for that amount of time and then continue running so in this case we have our loop that is going to continue to run continue to um move through the folder that contains our images and tweet them out but in between each tweet this is where you specify how much time you want how much time there should be within between each tweet so that's where you specify this value here in seconds so in this case it would be three seconds so that that about does it for how to create the bot and a couple things so moving forward for this uh with you guys if you want to create this go and or if you have created this then the folder that we created to store our images only has about 14 or 15 images i believe i think it's 14 from whatever we scraped so we've got those images but say you wanted to continually um post new content so what you would want to do here is modify the script that scrapes the pictures to continually scrape new pictures or to at a certain time of the day go ahead and request that url again and scrape the new pictures from the web page and add them to that folder so we can continue to iterate over new content and we don't have to continue to say do that by hand we can automate the entire process so that would be how you could move forward with this project and create something that continues to operate hands off so i hope you guys enjoyed this video be sure to give it a thumbs up and subscribe if you guys haven't already any questions or comments definitely leave them below this is a kind of this is a cool project to make and a great project to kind of stretch your python skills it uses a bunch of different libraries and you are using a few different functions to move around your operating system which are interesting to get a look at so yeah i hope you guys enjoytoday we are going to create a twitter bot that will post images of models onto a twitter account for us so this is what we're going to end up with when we're finished here on the left here we see a script that is going to scrape a web page for images and it will save them in a folder for us on the right here we have our have our python bot script which is going to go ahead and post those images to our twitter account at a set time interval okay so i'll run it for you guys so we can see how it works here and then we're going to go and review each line uh each line of the code line by line so here is what we are going to end up with this is the account i've got set up here called the modelbot and we're going to send out our first tweet in just a minute here so let's go ahead and get this and get this script running so here we have i'll show you guys right now i have it set at a time interval of three seconds so every three seconds is going to tweet obviously if we were running this on a separate server we would change that time interval because tweeting every three seconds might be considered a little excessive but let's go ahead and run this here so first off i want to show you guys we'll run this we'll run the script that'll scrape the images first okay so let's go ahead i'm going to show you guys the the desktop here and um just to show you so you can see the folder that we've got so right here we've got our empty folder or not empty folder but we have our two scripts in our folder so let's go ahead here and now run our script that is going to get the pictures for us okay so here we go and so right now it is going to this web page that we that i specified here and it's pulling all the photos from that web page and creating a folder that will pop up in this in this directory here so there you see our folder just got popped up and now when we open it we have all these pictures here from the website that we scraped off the website off the website alright so now that we've got those pictures let's go ahead and run our other script that is going to be the twitter bot for us okay so we've got that and now as we saw before don't currently have any tweets um for this for this twitter bot but now we're going to go ahead and run this guy right here all right and this is going to go ahead and send out tweets for us at a three second interval so let's go ahead and refresh our page here and there we go already got two tweets coming out and refresh again another tweet and there we go so again you can adjust that time interval as you want uh depending on how many tweets you want to send out and or what you're tweeting about okay so let's go back and uh close out that script before we get some serious uh twitter overload here and just one sec okay so there we go that will finish that off so now we're going to review our scripts here and so if you guys want to make this we're going to walk through step by step how you would go about doing that and so we can understand each line of the code here so we'll start with how we scrape the images from the web page so if depending on what kind of twitter bot you want to make we can or you can use different things so in this case i wanted it to send out images but you can also do there are also twitter bots that'll send out any kind of thing so some do like poetry some do memes some do a bunch of different things so whatever you guys want your twitter about to do or be you want to go ahead and get that data that it's going to that is going to be used to send out those tweets so as far as this script goes we'll review this one quickly and then get over to the to the bot itself but we have a url here that we are moving to and this is the url that has the pictures on it so you see we can go to this quickly here and we'll take a look at that all right so here's the website and it is grabbing pictures from this website here based there it is based on our url so it's grabbing these pictures scraping these pictures off the website and creating a folder for us and saving them to that so we go ahead we do that we're using the module uh we're using the request module the beautiful suit module and the os module so in this case request is a module that allows you to make requests to web pages a beautiful soup is a module for us kind of downloading the html that makes up those web pages so we can easily parse through that and find what we want and then os is used to create the folder in the directory that our scripts are in so we've got that url go to that url in our next line here we have the page so this is where we're actually requesting the url so we're requesting a response from the server on that page and then we are creating a our soup which is the html that makes up that website that we requested so once we get that we are using the bs4 uh method find all which is going to find all the images that are on that web page for us and then it is going ahead and we're going to create the directory that we want to store those images in okay so what this is doing is it's saying if the models folder does not exist in the folder that we are currently in then we want to make that folder and then otherwise we want to just change our current directory to that folder that we're in because when your python script saves files or saves uh pictures in this case to the folder it's going to save them unless you specify otherwise to the current working directory or the current folder that you're in so we go ahead and we change uh we change our current directory to the models folder that we created so next up here we have a variable that is going to be used to uh as we add our pictures we want to specify them being slightly different obviously because we don't want to overwrite the same file as we save our pictures so we have our x equals zero and we're going to increment that for each picture in order to save each picture as one two three etc okay so now we have a loop here and what we're doing with this loop is we are saying for each image that is in our uh image tags soup that we have here so this is returning us a nice list of a nice list of image tags and that but we don't have that's just the raw html we don't we want to extract the the source url from each of those um image elements okay so we're going to go ahead here and so for each image for each image in that list or for each image html element that is in that in that list then we want to go ahead here and we want to get the source so we're saying we're declaring a variable called url and we are setting that to be the source of the image so in this case we can reference the source attribute or src attribute of the of the image tags with our bs4 module by specifying the image and then specifying within within square brackets what the attribute that we want to get is so then once we have that url we want to go ahead and we want to navigate directly to that url then we want to go ahead and so if the source status code equals 200 so if we get a response there we want to go ahead and we want to open up a new file and this is the file that that is a jpeg file so you can see here with open model plus string x so we have just the model text plus the current value that our x integer is at so remember we're incrementing that in order to create new uh create new image files and we want to save that with the dot jpeg extension and we want to be able to write to that file so we're going to go ahead and we're going to create that jpeg file and we want to specify that we're going to write to it so then we're going to go ahead and we're going to say um f dot write so what this is is it's opening up this file and it's saying let's represent this file that we opened up as as f so we're going to say f dot right so we want to write to that file and then we want to write the the request that we got the content of the request that we got so that is what's going to capture the image that loads when we navigate to that url after that we want to close the file and then we want to increment x by one so we can move on to our next image file so if at any point during that loop there is some some exception thrown then we just want to continue our loop with the next picture because for some of these images uh they won't always get a proper request or there will be some other small error that occurs when we are navigating to that page that the images is located on so if that is the case then we want to go ahead and we just want to pass over and pass over that image and move to the next one okay so that does it for our our image scraping so now we're going to go ahead here and talk about our model script so this is the uh the script that creates our twitter bot so we're using three libraries in this case we're using the tweepy library which is a python library for accessing twitter via the api so in api is just an application programming interface which is essentially a lot of code that is written to directly access certain data within the uh within twitter and to be able to make certain um to be able to form certain operations such as posting new status updates posting pictures a following and a bunch of other things you can do on twitter so we're going to use the tweepy library in order to make our code more efficient next up here we have the time module which we are using to specify how much time we want to uh rest in between our tweets and then we have the os module in order to move over to our folder that is that contains our our pictures that we scraped off the web so next up here this is an important part for creating this guys so we have the credentials and the way what this is is how you log into your twitter account that your new twitter bot account that you created so if you guys are building this go ahead and create a new account on twitter and then you want to go ahead once you've created that account you want to navigate over to this page here so that's apps.twitter.com backslash app backslash new and just navigate to that page and it's going to bring this up here so what this is is you need to create a or you need to tell twitter that you're creating an application in order to get what are known as the api keys so you can access your account directly to the api interface that twitter provides so in this case you create a name for your bot that you're creating you create a description for your bot and then you can just throw in any old website you want if you want to go ahead and create a website specifically for your bot go ahead and do that and specify that there but otherwise go ahead and throw in whatever website and do make sure that you type in https colon backslash backslash not just www whatever name of the website you are creating is because otherwise it's going to throw you a little error there then you just go ahead and check this off and create your twitter application so once you do that you're going to have access to a couple of these keys here there is a tab that you want to navigate to once you're within that that will generate these keys for you so you can access the twitter api from within your script so that'll give you your consumer key your consumer secret your access token and your access secret so these are just long strings of numbers and letters that are going to be used to access your twitter api so go ahead and create variables to represent those those keys and those secrets and then go ahead and store those strings within those variables so next up here we're going to use a couple different functions from the tweepy library in order to log into our api so the first one is the oauth handler so you see tp here which we said up at the top here we want to import tweepy as tp so when we're referencing the tweepy library from within our code we can reference it just by the by tp instead of having to type out tweepy and so we have tp.o off handler which is how we're going to log into our or our authenticate with the twitter server in order to log into our account so next up here we want to take that off that that value that we are representing with auth and we want to go ahead and set the access token again this is using a function within the tweep library and that specifies two parameters which are the access token and the access secret so you go ahead and you add those in there and then you have then you're ready to log in so your next line here is to create the api variable and then go ahead and log in via the uh tweepy api function so again we specify uh tp.api with auth as our as our single parameter and remember we set the consumer key the consumer secret and the access token the access secret with these two lines above so now we've logged into our twitter api so what we want to do is post these images so in this case we want to go ahead and change the current directory that we are in to the models folder that we saved all our images that we scraped in so in this case here we are using the os dot chdir function which is basically just saying change the current folder that we are operating in to the models folder so in this case your script first starts running when it's first runs it's uh it's the current directory that it runs in is the directory that the scripts themselves are located in so remember we created that folder in that same folder that the scripts are in but now we want to move into that folder that we created that has the pictures so we're going to move into that folder with that line and then next up here we're going to loop over the files that are within that folder in order to post them each at a post each each picture because in this case they're going to be pictures at a set time interval so we go ahead here and we say for we're creating a variable called model image which is going to represent each file as we iterate over the files that are within the uh folder that we created and so we're going to say for each image that is in the or for model image in the in the directory list so we're using the uh the list dir the list dir function that is part of the os module again which will list all the files that are within our folder for us so that allows us to iterate over them and in this case we want to use again the tweepy function which is the update with media function so as far as this goes there are a couple different functions that are there multiple functions you can use for the different things you want to do on twitter with tweepy but in this case we want to use the update with media function in order to paste post a photo this can also be used to post a video or post a gif so we can go ahead and say update with media another function you can use is update status or update underscore status and then you pass a string as your parameter which is going to be just whatever text you want to post say you just wanted to send out a text based tweet you would use update status so after we go ahead and we send out our tweet then we want to go ahead and sleep so that's going to tell our script to basically pause for that amount of time and then continue running so in this case we have our loop that is going to continue to run continue to um move through the folder that contains our images and tweet them out but in between each tweet this is where you specify how much time you want how much time there should be within between each tweet so that's where you specify this value here in seconds so in this case it would be three seconds so that that about does it for how to create the bot and a couple things so moving forward for this uh with you guys if you want to create this go and or if you have created this then the folder that we created to store our images only has about 14 or 15 images i believe i think it's 14 from whatever we scraped so we've got those images but say you wanted to continually um post new content so what you would want to do here is modify the script that scrapes the pictures to continually scrape new pictures or to at a certain time of the day go ahead and request that url again and scrape the new pictures from the web page and add them to that folder so we can continue to iterate over new content and we don't have to continue to say do that by hand we can automate the entire process so that would be how you could move forward with this project and create something that continues to operate hands off so i hope you guys enjoyed this video be sure to give it a thumbs up and subscribe if you guys haven't already any questions or comments definitely leave them below this is a kind of this is a cool project to make and a great project to kind of stretch your python skills it uses a bunch of different libraries and you are using a few different functions to move around your operating system which are interesting to get a look at so yeah i hope you guys enjoy\n"