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.
import random class Common: def randomText(self,characters): posibleCharacters=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','ñ','o','p','q','r','s','t','u','v','w','x','y','z',' ','1','2','3','4','5','6','7','8','9'] returnedText = "" for i in range(0,characters): returnedText = returnedText+random.choice(posibleCharacters) return returnedText
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 * import time from Common import * starttime=time.time() twitter = Twitter() common = Common() twitter.connect() while True: time.sleep(30.0 - ((time.time() - starttime) % 30.0)) twitter.tweet(common.randomText(140))
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!