Hello again, welcome back to this “tutorial” about creating a Twitter bot, if you missed first part, please read it here.
So, now that we can Twit, maybe we can do some interesting things with that.
Creating random Tweets
As I wrote in the last article, one problem of tweeting “Hello World” is that you can’t twit twice the same text. In the other hand, we want the program to run all the time, tweeting different things, so we will make our program twit every x seconds a random text.
First thing is to create a class that will have some common functionalities and in there create a method that will create random texts of x characters.
returnedText = ""
for i in range(0,characters):
returnedText = returnedText+random.choice(posibleCharacters)
Even if the code is easy, here is a little explanation of how this works:
I have an array of characters that can be used for the text, and then a for from 0 to the number of desired characters it concatenates a string with new random character. In the end that string is returned.
Now that we have the functionality to send some random text, we can post tweets with a fixed delay. Here is one way to do that. Remember main file we have? Let’s work on that file and do something like this:
from Twitter import *
from Common import *
twitter = Twitter()
common = Common()
time.sleep(30.0 - ((time.time() - starttime) % 30.0))
We need time library to make it post every x time. time.time() returns the time as a floating point number expressed in seconds since the epoch, in UTC. For more information about Time library look here. Next step is to make objects of class Common and Twitter and connect to our Twitter account.
Now that we are connected we enter in an infinite loop and say sleep x seconds (in the example I putted 30, but you can put what you want) and then post a random tweet of 140 characters calling the randomText method.
If you want the code, fork it, review it, do whatever you want just clone it from here
Next time we will do some changes to our profile, see who follows us, follow people, etc. so stay tuned!