How To Create A Twitter Bot With Python | Build a Startup #4

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone in this video I'm gonna show you how to make a Twitter bot with Python first of all let me just show you what the final result is gonna look like so right now I'm in my personal twitter account at YK dojo but the Twitter account we're going to be controlling with python is gonna be this account at edit dojo instead and here's the way this account is gonna work or this spot is gonna work when you tweet at this account at edit dojo you know from either my account or your account with the hashtag hello world it's gonna respond back with the same hashtag within 15 seconds or so so let's just wait for a bit and I think I got a new tweet here let's check if that's the correct one let me just refresh the page here and it's the quick one I get hello world back to you from this account edit dojo so I'm gonna show you how I made this but you know just by changing the implementation a little bit you'll be able to do different things like for example you might say you know if someone admissions me with a certain keyword I'm gonna send them a direct message or if someone I follow mentions a certain topic then I'm gonna you know reply to that message anyway let's get started okay actually the first thing you need to do to follow this tutorial is you need to apply for developer accounts for Twitter to do that you can just you know go to your browser and then search for Twitter developer and by the way you know make sure to sign into your Twitter account first and then you know of course create a Twitter account if you don't have it yet and if you go to developer Twitter comm you see this button at the top that says apply so click that and then just follow everything that says here so choose which Twitter account you want to use here I'm gonna use another Twitter account I have here at CS so 2 4 4 so click continue and then follow everything else here and then once you go through everything you should see Terms of Service so read through it and then check these boxes or you know this first box at least and click submit application and then once you confirm your email address you're done so actually initially I thought there was gonna be a waiting period but it looks like I got the access already you might need to actually you know confirm your phone number - or wait for a few weeks but if you get the access right away you know that's great either way let's just get started with the rest of the process okay the next step is gonna be to create what's called an app within Twitter's developer website I'm gonna switch to firefox here just because you know I want to switch my Twitter accounts on Firefox I'm logged into at edit dojo like I said before we're gonna be controlling this accounts so then I'm just gonna search for Twitter developer on Google and you know find this website again and on the top right corner you should see your name and then when you hover over it you should see this one apps so click that and here you'll be able to create a new app I already have one app here edit dojo but I'm just gonna create a new app just for demonstration I think I'm just gonna call it edit dojo - and then I'll need to you know provide description website URL and so so let me just do that okay I just finished filling in everything here and by the way the reason why this app is called edit dojo is you know as some of you know it's just because I'm working on this project called edit dojo anyway once you finish that click create and then read everything click create and then your app should be created and once your app is created the next step is to check the permissions and make sure you have read and write permission because we're gonna be reading and writing tweets and then go keys and tokens and make sure you have all your keys generated so you should have consumer API keys API key API secret keys and then access token and access token secrets basically these four strings you won't be able to you know use the same keys because I'm gonna destroy these keys later but you should have your own keys here okay after that the next step is to make sure you have Python 3 on your computer because that's what we're gonna use so open your terminal or cell app and then try typing in python 3 - - version you might want to try a python that's just version 2 but let me try a python 3 version here you should see something like this if you see python 3 point something then that's good that means you have Python 3 installed on your computer now if you don't have python 3 on your system there are a few options here the first one is to obviously you know download and then install python 3 on your system but if you don't want to bother going through the process or if you have you know trouble doing that you can just use this website called python anywhere which you can find at CH dojo io / pi so this is a website where you can create a python script and run them without installing python at all so you can create a file right here in the file section just click open another file and then you know just typing in home / username in my case wacky dojo / let's say my bot dot pi and then click new file you can also run a terminal here or bash just by clicking you know this button right here and I think this website is pretty nice because you know you'll be able to use the free version of their website to follow pretty much everything in this tutorial anyway whether you use something like Python anywhere or your local environment the rest of the steps are going to be pretty much exactly the same so let's go back to our terminal and the next step of this is actually going to be a little bit tricky we're gonna be using this library called a tweet by you know Twitter for Python but the thing is it only works with Python as you can see 2.7 3.4 3.5 and 3.6 so so python 3.7 doesn't work with this library so there are a few options for getting around that issue the first option is to use a previous version of Python for example 3.7 I mean 3.6 but it turns out depending on your environment using a previous version of Python for this particular library is not the easiest option so what I would personally recommend is if you have Python 3 I mean Python 3.7 keep using Python 3.7 but use this particular command that I'm going to show you to find this command I just searched for tweet Pi Python 3.7 and then I found at this issue on github and then what you're gonna have to do is you need to install a particular version of this github repo and to do that you can use this command so I'm just gonna copy and paste it on my terminal but you'll be able to find it at you know either on this issue or at CS Dada io / Twitter anyway copy and paste that command on terminal or in console and then I'm actually gonna replace pip with PIP 3 it's you know it really depends on your environment which command you should use so I would try pip 3 first and then if it doesn't work I will try a pip install and so on so let me just try this here and this is gonna install like I said a particular version of tweet PI that should work with Python 3.7 ok so once you see this successfully installed wheat pie three point six point zero that's good go to your let's say this stop and then I create a new directory for this particular project I'm just gonna call it my bot and then go into the folder and after that we're gonna finally start creating our bot here to do that go to your editor I'm gonna use item here or Adam I'm actually not sure how to pronounce it anyway go into that folder that you just created and then create a new file let's call it my Twitter bot pi let's just write print this is my Twitter bot just to get started go back to terminal and then in the same folder type in Python 3 or Python my Twitter pot pie and this should print this this is my Twitter bot okay the next step is to import tweet pipe after installing tweet by you know with the command I showed you earlier you should be able to do that with just this imports tweet pie save this file go back to terminal and then run the same command and if you get no errors then that's good the import was successful after that go back to my Twitter bot pie in your editor and then either type in or copy and paste these commands I'm gonna put my source code in CS those are the io / Twitter so that you know you can just copy and paste these commands and we have as you can see these four variables here consumer key consumer secret access the access key and access secret these are the keys that we saw earlier so copy and paste your particular keys into those I have the consumer API key here and the API secret key here and so on and access key I mean access secret should be right here and once you have this you should have these three commands after that we're setting up this auth object using consumer key and consumer secret and then we set access token on the auth object with access key and access secret don't worry too much about what it's doing right now but the important part is after that we're setting up this object called API and we're going to be using this API object to basically you know talk to Twitter to read data from Twitter and write data into Twitter so save this file and go back to terminal and run this command again and if you get nowhere then that's good again and after that we want to be able to process all the admission tweets direct it for at edit dojo so let me go into my personal Twitter account at YK dojo and then create a bunch of new admissions for editor Jo so let me just write at edit dojo let's say tweet one so this is gonna be the first admission and then I'll say at edit dojo tweet to hashtag HelloWorld and so on let me create five of these okay so as you can see here I ended up creating six of those tweets at tweet one two three four five six and two of these have the hashtag HelloWorld tweet two and tweet six so we want to make our bot so that it responds to only those tweets with the hashtag hello world anyway let's go back to our terminal and I'm gonna start up a new Python shell here just by typing Python three just to test out some stuff in this Python shell copy the commands we've written so far all the commands we've written so far and then paste it here so this way you know we've just created the API object in this Python shell environment if you're typing API you should see something like this now let me go to tweet PI's documentation for a second you can find this page just by searching for to API documentation on Google and here you see this command API dot mentions timeline this is this is going to return all the recent missions for this account so that's what we're gonna use and there are you know different kinds of commands here and for example you have you know home time line if you want to get all the tweets from you know people you follow but here we're gonna use mentions timeline so go back to terminal and then try typing in API dot mentions timeline parentheses and then you should get you know some kind of results like this let's store this in a new variable called dimensions so here if you just print out the results just by typing in missions I think it's really hard to know what's going on because there's a lot of stuff here so what I would do here is I would just say type missions to find the type of this result you see that this is you know this class sweet pie that models that without set so what I actually did is I search for this on Google and then you know I search for like how to extract information from this set basically and then here I found this command or this comment that says tweet point without set is a subclass of pythons lists so I said okay you know it's like a list so maybe what I can do is I can do mentions square bracket zero to find the first tweet and that's actually the case but if you look at this this is still a lot of stuff so I did the same thing okay you know what's the class of this or what's the type of this one so I did that you know type parentheses measuring square bracket zero and then it turns out it's this one three point models that status so I actually went back to Google and did the same thing search for it just like that and actually you know when I search for it I didn't you know find that much useful information but I found that you know I know that this is a class and since this is a class or this is an object of this class and since this is an object we can use this trick to convert this object into a dictionary so type in you know this dots underscore underscore and the score in the score this converts this object into a dictionary and then you see that you know it has a bunch of attributes like API Jason ID ID SDR text and so on it's still kind of hard to see so what I would do here is I would extract all the keys by typing in that keys after the command that we used earlier and then you should see this these are basically the attributes of this particular class and it's much easy you know it's much easier to see you see attributes like created add ID you know this is probably the ID of the tweet and the text of the tweet and so so using this information we'll be able to you know if you wanna extract for example the texts you'll be able to just to mention this square bracket 0 which is an object dot text and this is the last weight that we sent out and then if you want to extract the ID which we're gonna use later you can just replace text with ID and then you get this and this is actually an integer I think by the way yes it is an integer so I think I went through a lot of stuff pretty quickly I really recommend you know that you I try running these same commands yourself and you know see how it goes and try to understand how everything fits together here anyway once you go through that press the up arrow key to find the command we used earlier to find all the mentions it was this one now that we know that this is the right command let's copy this command in our file my twitter bot pi and then let's use this mentions to you know print out all dimensions that we get from this command since this is just like a list you know we can iterate through it just like a list so we can do for mention a mentions and then let's just print the texts of this machine by typing a print mentioned that text and actually the ID is going to be useful later too so let's also type that in here with mention that ID plus mention dot text and since ID is an integer I mentioned that text is a string we can't do this we'll need to convert this ID into a string with the STR function and let's also add you know some spaces and maybe a hyphen here just to make it easier to see and this should print out all the mentions that we get from this command so let's save this file and let's see if that works go back to terminal and then let's keep our Python shell here and then just open a different tab of window and type in Python 3 my twitter bot dot pi let's see if it works okay it looks like it works we see a bunch of you know tweets here and the first six of these are the tweets that we created earlier okay the next thing we want to do is for each of these tweets we want to check if each of these tweets includes the hashtag hello world or not so go back to the Python terminal and then make sure that you still have this variable missions and let's just retrieve one of them mention zero let's just call this one T zero and then to get text we were able to do just teaser text we want to see you know if this includes a hashtag hello world the way I would go about it is I would first convert everything you know this string into lowercase because you know we won't just I think it's actually lower parentheses this text no actually sorry I should be a t 0 dot txt dot lower parenthesis okay so that works and the reason I want to convert it to a lowercase is because you know this hashtag hello world could be in any case right it could be all caps or it could be that you know H and W are capitalized and so or in it could be all lowercase but if we lowercase everything will be able to handle all the whole of those cases and then we want to say that is this lower lowercase version of the text include the hashtag hello world we can do that with this command quotes hello world close the quotes and then in this and this returns true if this hashtag is in there but if it's not in there for example hello world to is not in there it's going to return false so that's what we're going to use in our main file let's just copy this thing into our file here my twitter bot pi and then for mention emissions let's just do if the hashtag hello world is in the tweet instead of T zero use mention then prints will just say found hello world responding back dot dot dot let's see if this works so far by going back to the terminal and go back to the regular terminal or bash and then you know run this command again by three my twitter bot pi and let's see if that worked actually let's see just the top part we see a tweet six found hello world responding back and then we see a bunch of tweets and then tweet to hello world found hello world responding back so that's good it's working so far ok so so far I wanted to you know sort of show you the process by which I go about developing a script like this since this video is getting a little bit long let me just you know develop some more script and then once I'm done let me show you what's going on okay I wrote some more code here and for me to explain some of it you know I'll need to explain the idea of this code first so let's say you have you know these six mentions like we saw earlier tweet-tweet one two three four five six and you know with two tweets with this hashtag hello world now let's say the current time is here so these three tweets have been sent and these three tweets have it and when we run our script you know we're going to take a look at these three tweets right and then after these three tweets have been sent let's say in 15 seconds or in a minute whatever interval that you decide then we'll need to you know run our script again in that case we don't want to you know take a look at these three tweets again because we've already done that we don't want to respond to the same people over and over again so we'll need to make sure to store the ID of the last tweet and that we've seen so that's why I created a new file in the same folder called the last scene ID text so I decided to just store that ID in this file and then retrieve it every time we run our script you know it could be in a database or something but a text file is the simplest solution for this kind of stuff so I wrote these two functions for that retrieve last scene ID and store last scene ID retrieve last scene ID takes the file name you know this file name and then returns the last scene ID so if it takes this filename it's just gonna return this number as an integer and then a store last scene ID is the opposite of that it takes the new last scene ID and the file name and then it's just gonna write that new ID into this text file last scene I did text okay and if you want to play around with these functions and with the rest of the code like I said earlier you can just go to CS dojo da io / Twitter anyway let me just demonstrate to you how this whole thing works actually another thing I changed another major thing I changed is that when I goes through you know these measures I'm reversing lists that's for technical reason too but another reason is that you know it's a more natural way of thinking about it instead of going through you know tweet six to eight five two eight four we're going through you know old tweet firsts or tweets first and then responding to them first so it's gonna be you know to eat one first two three and so on okay and we're using another argument in this mentions timeline function the first argument of this function actually and that's last seen ID this way you know if the last seen ID is let's say you know the ID of this tweet let's say 91 then that API is gonna ignore this tweet and then give us you know these five tweets instead and actually I stored the idea of the first tweet in the comment right here so let me just copy and paste this ID in this you know lasting ID text that's actually what I already had but you know just to make sure we have the right ID and that way we should be able to see you know those five tweets let's see if that works and it does so we see a tweet two three four five and six and as you can see we're you know going to the oldest tweet first and then newest newest tweet last and once this is done you know this ID of tweets six should be in lassen I did that text and that's what we see here and since that's updated if we run point with Python three my Twitter but stop by again we should see no tweets because there have been no mentions you know since and the last tweet tweet six ok so so far all I've been doing is I've been just you know printing out these tweets and these comments we haven't been you know doing anything with those tweets so let me show you how to actually reply to those tweets to do that let me just you know copy the idea of the first tweet that we've seen and and go to our terminal and go to you know the Python shell again and then to respond to the particular tweet you need to use this command API dot update status and then at the username that's actually YK dojo let me just do that and then let's say hello world back to you and this is testing or this is just a test comma and then that ID so this should work let's go back to Twitter and let's see if we got it if we look at tweet one we see this new tweet hello back to you and this is just a test and that's the string that we wrote just earlier and to integrate that in our main code I'm gonna write this so after you know we make sure that HelloWorld is in the mission I'm gonna write API dot update status actually let me just copy and paste the command that we wrote earlier it was this one so copy and then go back to the editor paste it and instead of saying @ YK dojo manually I'm gonna write you know just at and then let's say plus we can actually use this command mention user dot screen underscore name plus and then let's use the hash tag here hello world back to you and then instead of using you know this ID manually I'm gonna write tweet or actually mention that ID so here let me copy the idea of the first tweet to last scene ID text and I save the file and once we run this whole thing this whole thing should work hopefully so let's go back to terminal and then run this again ok so it looks like we responded to tweet six without getting any earth let's check the result on Twitter let me refresh this page and I get hello world back to you that's actually perfect okay and the last step after this is to actually put this whole thing you know retrieving the last scene ID retrieving the missions and replying to some of them in a function and you see why in a second so put this whole thing in a function called reply to tweets just like that and then let's just put print replying to tweets da da da actually let's say retrieving and replying to tweets and then once we have this in a function if we do this it's just gonna be easier to see while true so this is gonna be an infinite loop I'll say we apply to tweets so we apply to tweets and then time that sleep 15 seconds so this stops this process for 15 seconds and then we start it after 15 seconds so this will we'll be able to you know run this function reply to tweets every 15 seconds and then to use this you need to import the time module at the beginning of this file by writing imports time and here just for testing let's change this to 2 seconds and let's see if it works go back to terminal and then run this file alright it looks like it's working and you know I just press command ctrl C to stop that and here the reason I'm comfortable enough with this code at this point is because you know I already tested everything in the function I just copy and pasted everything so it should work okay so let's change this time back to 15 seconds and once you run this in your terminal that's your BOTS but you know there's a problem here right if you just use your terminal as a bot you know you'll never be able to close it you'll never be able to go off the internet and that would be pretty billions so to solve that issue you need to put it online and actually at the easiest way to put it online I think is to use the website I mentioned earlier Python anywhere which again you can find at CSIRO slash PI let me just stop this process for now with ctrl C okay so once you sign up for Python anywhere you know just the free version is fine you'll be able to add files here in the file section so add home /yk dojo that's the home directory slash my Twitter bot dot pi I think that's the that's what the name was and I click new file and then I think there's a way to you know transfer files with git or something but for now you can just copy and paste everything in our file here so copy and paste everything here and then save click save and go back to the dashboard of Python anywhere you need to create another file actually and that was home your username slash last seen ID text so create that file and then copy the ID that you have in your last seen ID file locally click Save here and then go back to dashboard of Python anywhere again okay once you have those two files you can go to the console just click bash here this is just like the local console that we've been using so first type ls' to make sure you have my twitter bot pi and last seen ID text and then use the command that we used earlier you know I think that was a pip you or something and then the get URL to download tweet by and I think I've already done that so after that you can just do my Twitter bot up high and this should just work okay so I've been running a for a while now let's make sure this still works I'm gonna do that by going to Twitter and then by at mentioning a dojo it's dojo and then I'm gonna create two tweets the first one is gonna be tweet a with a hashtag hello world let's all cap here hello world I think that's spelled correctly and then the second tweet is gonna be tweets be without the hashtag let's say hello world okay so let's wait for 15 seconds or so let's see if it works you can actually go back to the console on Python anywhere you see you see that the spot found you know these two missions and then I think it's responding to only the first one tweet a let's wait for a bit and then let's make sure everything is correct on Twitter - yeah it looks like it's everything is correct so I don't see any replies to tweet B and I do see a reply hello world back to you on tweet a okay so this method of using Python anywhere's console works but it turns out you know every half a day or so or maybe maybe every day this console kind of shuts down and then the script just starts stops working and if you don't mind you know restarting it every half a day or so then that's fine but if you don't want to do that there are you know a few ways of going around it one is you know you could try using other cloud services maybe like digital ocean or Heroku or something but another one is actually to use Python anywhere's function called always-on tasks and apparently you know it's a function where you start up a script and then if it crashes it's just gonna you know start it automatically again so it looks like a pretty useful function you know I've been trying it for a while now and it's been working just fine so far but the thing is it's only in the paid option you know you need to pay five dollars a month so if you don't want to do that you know you should look into other options like I mentioned earlier anyway that's pretty much it for this video and I think I'm gonna keep running the script for at least for the next few weeks or so so if you add mission edit dojo with the hashtag hello world the spot might still work anyway thank you as always for watching my videos and I will see you guys in the next one
Info
Channel: CS Dojo
Views: 392,935
Rating: 4.9335728 out of 5
Keywords: twitter bot python, instagram bot python, build a startup, edit dojo, python tutorial #15, python tutorial 15, csdojo, cs dojo, python scripts, python automation, automate, automate boring stuff with python
Id: W0wWwglE1Vc
Channel Id: undefined
Length: 35min 47sec (2147 seconds)
Published: Fri Nov 09 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.