Created
May 31, 2013 19:49
-
-
Save Chavao/5687524 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# coding: utf-8 | |
''' | |
NerdFollow 0.1: Bot Python para twitter com finalidade de | |
conectar e indicar perfis. | |
Copyright (C) 2011 Felippe Regazio de Moraes | |
Este programa é software livre; você pode redistribuí-lo e/ou | |
modificá-lo sob os termos da Licença Pública Geral GNU Affero, | |
conforme publicada pela Free Software Foundation; tanto a versão | |
2 da Licença como (a seu critério) qualquer versão mais nova. | |
Este programa é distribuído na expectativa de ser útil, mas SEM | |
QUALQUER GARANTIA; sem mesmo a garantia implícita de | |
COMERCIALIZAÇÃO ou de ADEQUAÇÃO A QUALQUER PROPÓSITO EM | |
PARTICULAR. Consulte a Licença Pública Geral GNU para obter mais | |
detalhes. | |
Contato | |
twitter: @withcaffeine | |
Gmail : [email protected] | |
''' | |
import twitter | |
import random | |
import datetime | |
import time | |
#Logando no Twitter com a Conta do NerdFollowDeck | |
api = twitter.Api(consumer_key='', | |
consumer_secret='', | |
access_token_key='', | |
access_token_secret='') | |
#Este print e opcional e verifica se o login foi bem sucedido | |
#print api.VerifyCredentials() | |
#Lista de Funcoes | |
#Twittar - Twitta a mensagem do parametro 'm' | |
def Twittar(m): | |
api.PostUpdate(m) | |
print '\ntweeted\n ', m | |
#Follow - Segue o user no parametro 'u' //nao utilizar @ no user | |
def Follow(u): | |
api.CreateFriendship(u) | |
print '\nfollowed\n ', u | |
#Unfollow - logicamente, da um unfollow no parametro 'u' //tambem sem @ | |
def Unfollow(u): | |
api.DestroyFriendship(u) | |
print '\nunfollowed\n ', u | |
#Following - Mostra a lista com todos os Following | |
def Following(): | |
userlist = api.GetFriends() | |
for username in userlist: | |
print username.screen_name | |
return username.screen_name | |
#Followers - Mostra a lista com os followers | |
def Followers(): | |
userlist = api.GetFollowers() | |
for username in userlist: | |
print username.screen_name | |
return username.screen_name | |
#DiaAtual - Retorna o dia da semana em números | |
def DiaAtual(): | |
d = datetime.date.weekday(datetime.date.today()) | |
return d # 0Seg - 1Ter - 2Qua - 3Qui - 4Sex - 5Sab - 6Dom | |
#LoadBlackList - Transforma a blacklist.ff em uma lista | |
''' Na mesma pasta do bot há um arquivo, o blacklist.ff, o | |
@NerdFollow indica os perfis a partir de seus followings | |
para que possamos definir quem vai ou não ser indicado, | |
o mesmo também sempre faz uma "copia" dos followers para os | |
followings, sendo assim alguns perfis trolls, gente escrota | |
e afins que estariam seguindo o bot poderiam ser automaticamente | |
seguidos. Para evitar isso, o arquivo blacklist.ff contem os | |
perfis identificados no NerdFollow que devem ser evitados. | |
Assim o Bot nao segue, e logo não indica acidentalmente nenhum | |
perfil fantasma : ) ''' | |
def BlackList(): | |
b=open('blacklist.ff') | |
blacklist="".join(b) | |
return blacklist | |
#print blacklist | |
#FollowAll - Seguir todos os followers | |
def FollowAll(): | |
#Gerando a lista followers com todos os followers do perfil | |
#e a lista friends com todos os followings do perfil | |
followlist = api.GetFollowers() | |
#Jogo os followers em followlist | |
for username in followlist: | |
following = "".join(' '+username.screen_name) | |
friendlist = api.GetFriends() | |
#Verifica todos os seguidores do perfil | |
blacklist=BlackList(); print 'BLACKLIST\n', blacklist | |
#Cria a blacklist com os perfis que nao devem ser seguidos | |
#Verificando quem esta na blacklist | |
for username in followlist: | |
f = (username.screen_name) | |
#gera o nome do follower em questao | |
if blacklist.find(f)>0: | |
print f,' esta na blacklist' | |
else: | |
if following.find(f)<=0: | |
try: | |
Follow(f) | |
except: | |
continue | |
#NFSomeone - NF Aleatório, Escolhe 10 Nerds via Sort nos followers e da #NF | |
'''As indicações do bot devem partir da lista following do mesmo, pois assim | |
garantimos sempre #NFs de qualidade Caso as indicações partissem dos followers, | |
poderiam haver trolls e outros bot entre eles o qual o bot indicaria Ja na | |
lista following estão apenas os que podem ser indicados préviamente, caso haja | |
algum bot ou perfil duvidoso, o mesmo receberá unfollow. Assim garantimos sempre | |
um #NF de qualidade :D ''' | |
def NFSomeone(N): | |
#N é o numero de NFs que o Bot ira gerar, P é pag de followers | |
for i in range(0,N): | |
# Gerando a Lista com todos os followers | |
following=api.GetFriends() | |
F=[] | |
for username in following: | |
F.append([username.screen_name, ' ',username.description]) | |
# gera uma lista com todos os followers e descriçao | |
u = F.pop(random.randrange(0, len(F))) | |
# remove um user aleatório e sua descriacao da lista F | |
# Abaixo montamos o tweet com o #NF ou #NFW ou #NF #FF | |
T = '#NF '+'@'+"".join(u) | |
# Junta os valores em lista para que fiquem em str e adiciona #NF e o @ na mention | |
if DiaAtual()== 2: | |
#Verifica se é quarta feira, caso sim, em vez de #NF utiliza-se #NFW | |
T = '#NFW '+'@'+"".join(u) | |
print '\ntweeted: ','#NFW '+'@'+"".join(u) | |
if DiaAtual()== 4:#Verifica se é sexta feira, caso sim, Inclui também a hashtag #FF | |
T = '#NFF '+'@'+"".join(u) | |
print '\ntweeted: ','#NF #FF '+'@'+"".join(u) | |
if len(T)>140: | |
try: | |
Twittar(T[0:138]+' +') | |
#Twitta #NF + @usuario + perfil do usuario até dentro do limite de 140 caracteres. | |
print '\nTweeted: ', T[0:138]+' +' | |
except: | |
continue | |
else: | |
try: | |
Twittar(T[0:138]) | |
#Twitta #NF + @usuario + perfil do usuario até dentro do limite de 140 caracteres. | |
print '\nTweeted: ',T[0:138] | |
except: | |
continue | |
#RetweetNF - Procura por replys que contenham #NF #NFW e #NFF e da RT | |
def RetweetNF(self): | |
#Gera uma strings com os retweets anteriores contidos no arquivo retweets.ff | |
RTFile=open('retweets.ff','r') | |
retweeted=RTFile.read() | |
#Define as palavras chaves para o RT | |
Key="NF" # Comeca procurando por NFs | |
if DiaAtual() == 2: # Caso seja quarta feira, verifica por #NFWs | |
Key="NFW" | |
if DiaAtual() == 4: # Caso seja sexta feira, verifica por #NFF | |
Key="NFF" | |
replies = api.GetReplies(since_id=None) #Manda as Replys para replies | |
for reply in replies: #Procura as hashtags #NF #NFW #NFF na reply | |
RT=reply.text #Pega apenas o texto contino na reply | |
#Procura por #NF #NFW ou #NFF contindos na RT | |
if RT.find(Key)>0: | |
id = reply.id | |
if retweeted.find(str(id))>-1: | |
id = ' ' | |
pass | |
else: | |
id = ' ' | |
#Caso tenha encontrado, gera um NF | |
if id != ' ': | |
RTFile=open('retweets.ff','w') | |
RTFile.write('') | |
RTFile.write(retweeted+(str(id))+' ') | |
if not self._oauth_consumer: | |
raise TwitterError("The twitter.Api instance must be authenticated.") | |
try: | |
if int(id) <= 0: | |
raise TwitterError("'id' must be a positive number") | |
except ValueError: | |
raise TwitterError('') | |
try: | |
url = 'http://api.twitter.com/1/statuses/retweet/%s.json' % id | |
json = self._FetchUrl(url, post_data={'dummy': None}) | |
data = simplejson.loads(json) | |
self._CheckForTwitterError(data) | |
#return Status.NewFromJsonDict(data) | |
except: | |
continue | |
#==================================================================================== | |
#INICIO DO BOT | |
def main(): | |
running=True | |
while running==True: | |
print 'Bot Started\n' | |
FollowAll() | |
NFSomeone(5) | |
RetweetNF(api) | |
print '\nEsperando TimeOut 0%\n' | |
#Apos Indicar, espera 500x5 (devido ao tempo de timeout do RetweetNF(api) segundos | |
#No intervalo de 2 em 2 seg é feito uma procura por replys com NFs para RT | |
for i in xrange(0,1000): | |
print i, | |
time.sleep(1) | |
print '\nTimeOut 100% Restarting\n' | |
time.sleep(5) | |
# =================================================================================== | |
if __name__ == "__main__": | |
main()#Running |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment