Simple Twitter Bot With Python Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
twitter bot with python video this is philosophy girl she absolutely loves philosophy and tweeting and today we're gonna be creating her from scratch so we're gonna use the twitter api google sheets as a database python and the google cloud scheduler now just knowing these things alone will get you really far for example if you know google sheets and python you can automate a lot of your workplace tasks and do just other cool stuff at the end of the day google sheets is just a database that's very user friendly but when you can control it with code it's kind of like a superpower now add the twitter api into the mix and you can build bots for anything you can build quote bots that grow to tens of thousands of followers you could add an upstream web scraper that actually pulls data down into your sheet like bitcoin prices and then tweets them out or you can build an entire app on top of the twitter api one example of that is tweetdeck which got so big twitter actually acquired it my point is we're covering a lot of good stuff so when you become a millionaire after watching this video just promise to send me an email so here's our plan we're going to be using google sheets and in our sheet we're going to have all the tweets we're going to want to post in the future so we'll read from the sheet and then use python kind of like glue to then write those tweets or post them through the twitter api to keep things simple we'll be manually adding the tweets as a user but you could also add a scraper upstream if you wanted to automate even more so three core pieces the sheets api python libraries and twitter api it also wouldn't be complete unless we set it up to run automatically with a cron scheduler deployed in the cloud now we've got a lot to cover so let's get started okay if you know the steps this is pretty damn easy so let's go through them one by one and i've got several tabs open here let's start with google sheets itself so if you just type in google sheets python and go to the first result that should say python quickstart then it gives you a really easy way to start a new project and connect it to python in just a few steps that'll bring us to this page i'll just scroll down and click this big blue button enable google sheets api and this will take us to a pop-up that lets us create a new project so let's name our i'll name mine philosophy dash girl you can name yours whatever you want the next screen is desktop app that's fine and now we're all set so we just want to click this link that says api console that'll bring us to this dashboard and there's one more thing we want to enable so we go to this enable button right here we search for drive click google drive api and then enable that too i forgot to say make sure you're logged in with the google account that you also want to create your sheets in okay that'll bring us back to the dashboard now we want to go to credentials on the left hand side once that loads up look at the service accounts tab and click manage service accounts then we'll go to create service account at the top here and we'll call this one python dash code then hit create and then hit done okay we've got our service account so let's click into it and the last thing we need to do is scroll down and add a new key so we'll go add key create new key and we'll get that key in json and then hit create now you'll see that downloaded a file for us this file is very important so don't lose track of it okay now let's switch over to the tab where i've searched for g spread which is a python library so i'm just going to open up the documentation for that and we can see that g spread is a python api for google sheets at this point switch over to your favorite code editor mine is vs code and we'll create a new python project so you can do that in whatever directory you want so i'll make a new directory philosophy dash girl change in that and then i'm going to create a python virtual and called vmv which just allows us to install dependencies like this g spread library so then i want to make sure that directory is open in vs code okay so we have that single file let's create another file called main.py let's open up our terminal again and make sure that virtualmin is active which it is now we can pip install g spread and while that's working let's copy the starter code from gspread and we can actually see that install instruction here and then copy the quick example so that library finished and then i'll paste in the example code just resize this so you can see okay and it's all there and now this is where we need that json that we downloaded from our service account so so i'm just going to drag mine directly into my code directory and then i'll just right click and rename it credentials.json now for g spread we're going to pass in a string that points to our service cap account credentials and since it's in the same directory i can just pass in a string with the file name and that should work just fine okay now time to actually create our google sheet so let's just do that at sheets.google.com create a new blank spreadsheet and you can name it whatever you want so i'll just name mine philosophy dash girl and then this step is very important you want to go back to your credentials hope you didn't close it yet copy your service account email from this field here and then share it with your service account email and make sure you click it when it uh shows you the drop down and then hit send now we've got all the pieces so let's go back over to vs code let's only leave in the first example that should be updating a spreadsheet and we gotta make sure the spreadsheet name matches the one we have here so mine is philosophy dash girl and then it'll be sheet 1 which is the tab right down here so i'll save that and i'll run this file with python main.py and we're hoping for no errors it looks like nothing happened but when we jump back over we'll see that this code actually from our file here has been loaded okay so i'll just delete that and it's really cool to do this in python because now what i can do is comment this out and i can load this file with an interactive shell so i can just do dash i and then the file name and now i can just execute any command i want from my python so if i wanted to do that same worksheet dot update and then update a1 i can i can now pass in any actual values that i want so i can say hello comma worlds and then just send that through the shell we got a return value and if i jump back over look boom that's pretty cool for this project though we're going to have tweets kind of like this so a header column and then we'll just type in a bunch of tweets below this like i love philosophy we can do an emoji there and then we can just keep writing tweets in here so let's just read the next tweet cell a2 which will be this tweet that we just typed in so the syntax is like this i'll just copy this and then our interactive shell is still going but uh we replace worksheet with wks because that's what we define it as here and then remember our cell is going to be a to a2 and we're actually reading our values so we can now hard code this in here and we can call it next underscore tweet tweet equals worksheet a cell a2 dot value so that code is good to go now we've loaded our tweet into a variable and eventually we're going to want to post tweet through twitter api that comes a bit later and then finally we're going to want to delete row on success so if we've already sent this tweet from our spreadsheet we don't want to send it again so let's just remove this row and then move all the rows up so let's just type a second tweet below it to make sure that's working so much heart heart okay this feels kind of weird i'm writing these fake tweets okay now let's just see if we can delete a row and i'm just going to go worksheet dot and then look for that method maybe there's one for delete row delete rows exactly so let's do delete row and i guess it would be what does this take deletes the row at an index so it'll probably be index 2 is going to be my guess but let's see if that works as we anticipated to by first writing it in the console so in the console i'm going weeks our worksheet delete row two and yeah it does exactly what we wanted so it deletes the row and then moves the row below it up we are getting a warning that this delete row is epic deprecated so please use delete rows instead uh so we will change that but otherwise this should be fine okay we're all set with linking google sheets and python and like i said you can do a ton of automation stuff just with that combination now let's get into linking twitter and first we'll just create a new account you don't need to see me creating accounts so i'm just going to skip ahead a little bit here all right we've actually got our account created we are philosophy girl five i might change that later and we just got a picture here uh that i found on a new no copyright image site so just be careful if you're stealing someone's picture it can get a little bit dicey but the site i used was called pixabay p-i-x-a bay that actually connected the api you can google search twitter api and you want to scroll down to the one that says apply for access then click the button apply for a developer account and you want to make sure your avatar is the account that you want to link to so you can put whatever options you want here but i'll just show you the ones i usually do which is hobbyist then i do exploring the api and then get started okay so you just have to fill out some fields i'm going to go through these quickly [Music] do unfortunately guys i hit a major speed bump at this point because every time i've applied for a twitter developer account in the past i was instantly approved but i was also in the us and now that i'm in ukraine well it seems like it's a different story so rather than just waiting who knows how long to get approved i decided to use one of my old twitter developer accounts now i know you're disappointed because you really wanted to see philosophy girl come to life but unfortunately i chose to finish the video instead of waiting so hope you don't mind too much all right let's get back into it so i logged into my other account for now that already has developer account access and uh i log in and i get this so apparently twitter doesn't really like ukraine uh i don't know anyway i guess we're switching to a socrates bot halfway through sorry to disappoint but i'm in my developer portal dashboard here which you'll see is developer twitter.com en portal dashboard and uh you can just go to projects and apps and overview and then you just want to create a new project and then create an app within that project and i'm sure you can figure out how to do that now the important part here is you want to go to keys and tokens and then you're going to have a bunch of credentials here so you're going to have consumer keys you're going to have auth tokens so let's just stay here and keep this open now i'm going to go to my next tab and this is almost the last one and we're gonna search twitter python in google and i'm gonna scroll down to the one that says twitter pi p okay and similar to our g sheet library we're gonna install this twitter library like so with a pip install twitter right there and then we have uh some more sample code like this so let's jump back over to our code let's interrupt or close our shell and let's pip install twitter now let's copy some of this documentation uh importing it at the top and then passing in our secrets like so this will leave the service account above okay for twitter we've got four distinct secrets we're gonna have to pull each one of these from the uh twitter developer dashboard so consumer key i'm going to hit regenerate or you can generate it for the first time if you've created this project and api key is going to go in token so i'll just set variables like so and i'm going to delete these after so don't even uh don't even try to steal mine secret okay and then we have two more variables here and we're going to get those from access token and secret so regenerate yes regenerate and uh yes we will do consumer key just like that all right and then access token secret is going to be consumer secret right and you probably want to put these in a different file a secrets file that's your prerogative all right back to the twitter documentation let's see if we can actually just connect in the first place so so we can actually just comment out all the google spreadsheet business and just test the twitter stuff so i'm saving that and then i'm gonna do python main py and i had these the wrong way around so these are the tokens my bad my bad my bad and this is the token secret and then the consumer key consumer secret boom and that worked nice nice nice nice so we are in and now we just go back to the docs and we see if the status update works so t statuses update and we just change to test and let's see if that posts a status i'm breathing heavily now things are getting interesting my god we did it it wasn't even that hard so yes in a given project keys and tokens you just generate api key and secret you generate access token and secret and you paste those in yeah it's kind of annoying let's be honest but we have all the fundamental pieces that we need so here's all we need to do guys just put this status update where we have the comment so let's comment everything back in and we're getting next tweet and then we post tweet through twitter api so t status is update and then we set this instead to a variable next tweet now let's make sure our spreadsheet is up to date we probably want to rename this socratesbot and then i'll change the name here okay and uh yeah socrates can tweet hearts right it's fine so let's see if it all works together and this is really the moment of truth and now if we refresh our twitter so much there it is and our row was deleted so we can just add a hundred tweets to this list and every time this file runs it's gonna pull a new tweet out it's going to push it into twitter but how do you make it run automatically well that's the last and final step and for that we have to go back to where we started which is the google cloud platform console let's go to consolecloudgoogle.com just as i have it typed here and this is going to take us to the home page of the google cloud console that we were previously on the api tab of okay so this is taking us to our dashboard and we're still logged into the philosophy girl project so let's scroll down on the left sidebar and go to cloud functions unfortunately we have to enable billing to have cloud functions functional so you're gonna have to do that but you won't be charged for anything and i've already set this up in advance so i'm just going to use the same account and if you're thinking oh i don't want to put in billing info and you're going to give up here just do it google cloud is so useful to play around with and like i said if you do things correctly you're never going to get charged okay once you've linked your billing account you'll be brought to a page like this google cloud functions create function and this is going to be really simple because we've already typed out all of our code now what we're going to do here is do a function called post dash tweet region is not important because we're not talking to a client we're just running everything on the server uh trigger type we're gonna do cloud pub sub okay that's very important and then pub sub topic well we're gonna create a new topic and we'll just call that topic send tweet and don't forget that topic name actually let's make it a post tweet just to match our function name so i'll just create a new topic post dash tweet okay now don't forget to hit save on the trigger tab which i did not do and then go to next all right now we have an inline editor and we will want to change our runtime from node.js to match the version of python that we have i believe we're running three and so you can just choose 3.7 or 3.8 and it shouldn't really you know cause you any issues actually now you're gonna get this saying cloud build api is required to use the runtime so we can just enable that and then you can also enable that from the apis and services tab so if you go search for cloud build then click then just enable and you want to be careful enabling some of these apis by scrolling down to the building and we'll notice that for the first two hours of building building then this api is actually free so we've enabled it for this project let's jump back into cloud functions cloud functions and we'll create our function again from scratch and again we'll do post dash tweet pub sub we'll do post tweet topic save next all right let's change that run time to python 37 and a couple important things we're going to want to do here let's change this function name to post underscore tweet we can just delete all this and paste in exactly what we have in our main.py file okay i'm just gonna paste all that in and what we're really trying to do here uh then sorry we could also move the imports to the top like so and fundamentally what we're trying to do here is uh just replicate this folder that we have locally uh into google cloud platform so we will also want to create a new file called credentials.json to match our local environment and then we'll just copy everything in credentials.json and paste it in here okay last thing we have to do requirements.txt so we can do pip freeze in our terminal and then do a little angle bracket which will pipe the result of our dependencies into a requirements.txt file and then wow we have more than i expected but we can just copy and then paste this one for one so we'll see that we have our main libraries here g spread and we have twitter and then the other ones you may not need but i just like to get all of them just in case okay last thing we just need an entry point to match the name of our function so let's change it from hello pub sub to post tweet and then deploy now before you move on you're going to want to wait and make sure that this deploys correctly because as always with coding if you get one part wrong then none of it's going to work so let's just wait for that to finish and then we can see what happens and by the way if you do have an error you can go to actions here and then view logs and it may give you some useful info but it may not and that's one of the problems with google cloud platform is uh you don't always get detailed error information okay and this time it worked and we can see our executed function was post tweet right here so with that we are ready to move on to cloud scheduler which is just gonna run this function automatically at different times a day for us so think of what we have so far in the console as this code living on a server somewhere but uh how do we actually run as we were running it before with python main.py and when and this is what the scheduler does and we can see that the definition is a fully managed cron job service and the cron job is just the way we define how our function runs so we're going to do this create job and where would you like them to live us central same as our functions and this takes about a minute so plenty of waiting in this project alright great so we're ready to go so let's do post dash tweet uh now we have frequency which is going to be a cron expression so if you've never written a cron expression before it's really easy just go to the site crontab.guru but i'll be honest with you i always just google exactly what i want to do so i google like once per day cron and then i click and do the result how to run cron once daily at 10 pm and you'll pretty much easily find it like so 0 22 and then star star and you just want to verify that with this generator so add 2200 yeah exactly right and we do want to tweet once per day so let's just copy this and paste it into our scheduler definition so boom good to go let's just do my local time here ukraine and uh target this is the important one pub sub now topic okay this is the reason we gotta remember a topic because it doesn't give us an auto fill so we're gonna do the post dash tweet topic and the payload it doesn't matter so let's just make it true okay create so the way this works is the scheduler is sending a message out on the channel post tweet and the function is listening for that message so as soon as it hears the message it's going to run the code and that's why the argument doesn't matter but we could pass custom parameters that's all the code we deleted at the beginning of our cloud function definition so before we run this as a test let's just put one tweet in here and do testing scheduler enter and then let's go back and moment of truth this is gonna tell us if our whole code is working or not let's do run now okay so we successfully ran the um scheduler side we sent the message but did we receive it well we can actually go back to our function and we can view logs or we can just go to our account and refresh fingers crossed and there it is so everything is now running in the cloud and because we put the cron expression into our code it's going to run every day at that time so this is the whole project guys you can build any twitter bot to tweet automatically with this method but keep in mind each one of these pieces is super valuable so just knowing scheduler just knowing cloud functions google sheets or twitter api those things alone are useful and you can build projects with each one but when you put it all together you can build something really really cool so i hope you guys enjoyed that video let me know what you thought and if you build anything cool that's similar definitely send me an email or dm me on instagram by the way guys i'm aaron jack sf software engineer turned remote developer if you're serious about learning the code check out some of the links below videos i've done in the past programs i'm working on now and you might find it useful okay with that said i'll see you guys in the next one
Info
Channel: Aaron Jack
Views: 14,355
Rating: 4.9649124 out of 5
Keywords: programming, web development, learn programming, learn to code, coding, software development, become a software developer, python, web scraping, twitter api, google sheets api, python tutorial, coding tutorial, fun coding tutorial, google cloud scheduler, bot tutorial, build a bot, twitter bot, learn python, python project, python projects, coding project
Id: 83o6rU5XArs
Channel Id: undefined
Length: 27min 8sec (1628 seconds)
Published: Fri Jan 22 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.