2017-02-22 8 views
0

Я порядочно новый кодер python, и я хочу создать твиттер-бот, в котором каждый раз, когда он пересматривает, он также предпочитает чириканье. Я не совсем уверен, как это сделать, но когда бот ищет, он отправляет сообщение об ошибке «индекс списка вне диапазона».Как обратный вызов сообщений об ошибках (python)

import tweepy, time, traceback 
from tweepy.auth import OAuthHandler 
from tweepy.streaming import StreamListener, Stream 

ckey = '' 
csecret = '' 
atoken = '' 
asecret = '' 

auths = OAuthHandler(ckey, csecret) 
auths.set_access_token(atoken, asecret) 
api = tweepy.API(auths) 

class listener(StreamListener): 
    def on_data(self, raw_data): 
     try: 


tweet_text = raw_data.lower().split('"text":')[1].split('","source":"')[0].replace(",", "") 
      screen_name = raw_data.lower().split('"screen_name":"')[1].split('","location"')[0].replace(",", "") 
      tweet_cid = raw_data.split('"id:')[1].split('"id_str":')[0].replace(",", "") 
#there is ment to be 4 spaces at tweet_text 


accs = [''] # banned accounts screen name goes in here 
      words = ['hate' , 'derp' , 'racist' , 'evil' , 'keemstar' , 'mario' , 'kirby'] #banned words goes in here 

     if not any(acc in screen_name.lower() for acc in accs): 
      if not any(word in tweet_text.lower() for word in words): 
       fav(tweet_cid) 
       follow(screen_name) 
       retweet(tweet_cid) 
       tweet(myinput) 
       #call what u want to do here 
       #fav(tweet_cid) 
       #retweet(tweet_cid) 
       return True 
    except Exception as e: 
     print (str(e)) # prints the error message, if you dont want it to comment it out. 
     pass 


def on_error(self, status_code): 
    try: 
     print("error" + status_code) 
    except Exception as e: 
     print(str(e)) 
     pass 


def retweet(tweet_cid): 
     try: 
      api.retweet(tweet_cid) 
      time.sleep(random.randit(range(50,900))) 
     except Exception as e: 
      print(str(e)) 
      pass 

def follow(screen_name): 
    try: 
     api.create_friendship(screen_name) 
     time.sleep(random.randit(range(50,900))) 
    except Exception as e: 
      print(str(e)) 
      pass 


def fav(tweet_cid): 
     try: 
      api.create_favourite(tweet_cid) 
      time.sleep(random.randit(range(600,1100))) 
     except Exception as e: 
      print(str(e)) 
      pass 

def unfav(tweet_cid): 
     try: 
      api.destroy_tweet(tweet_cid) 
      time.sleep(random.randit(range(8000,9000))) 
     except Exception as e: 
      print(str(e)) 
      pass 


def tweet(myinput): 
     try: 
      api.update_status(myinput) 
      time.sleep(random.randit(range(1000,4000))) 
     except Exception as e: 
      print(str(e)) 
      pass 



# tags below 
track_words = [""] #deleted all tags so easier to read 
follow_acc = [] # all username converted to user ids 

try: 
    twt = Stream(auths, listener()) 
    twt.filter(track=track_words, follow = follow_acc) 
except Exception as e: 
    print (str(e)) 
    pass 
+0

Что вы имеете в виду с обратным вызовом? Я предлагаю вам попытаться найти и исправить причину ошибки индекса вне диапазона, поскольку это довольно распространенная ошибка в python, а не любые «обратные вызовы». Это просто означает, что в какой-то момент вы пытаетесь получить доступ к элементу в списке, который не существует. Скорее всего, в одном из этих '[1] .split()', но мы не можем быть уверены, так как вы не ввели все исключение. –

+0

спасибо за редактирование, это была только ошибка при вставке :) – Shadowbladers

ответ

0

Это то, о чем вы просите? Это дает трассировку стека исключения.

import traceback 
try: 
    s='hi' 
    s=s+1 
except Exception as e: 
    print(traceback.format_exc()) 

Выход:

Traceback (most recent call last): 
    File "<stdin>", line 3, in <module> 
TypeError: cannot concatenate 'str' and 'int' objects 

Надеется, что это помогает! :)

Смежные вопросы