def divide(x, y): try: result = x / y except ZeroDivisionError: logger.error("Tried to divide by zero") else: return result
def on_status(self, status): if not status.retweeted and status.user.screen_name != "thedebugducky": try: status.retweet() logger.info( f"RT successful from @{status.user.screen_name}. Status ID: {status.id}." ) except tweepy.TweepError as e: if e.args[0][0]['code'] == 327: logger.info( f"Tweet from @{status.user.screen_name} already RT'd.") else: logger.error(f"Error {e} on listener.", exc_info=True)
def create_api(): auth = tweepy.OAuthHandler(API_KEY, API_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) try: api.verify_credentials() except Exception as e: logger.error(f"Error {e} creating API.", exc_info=True) logger.info("API successfully created.") return api
def favorite_and_retweet_user_status(api, user): for status in api.user_timeline(screen_name=user, count=1): if not status.favorited: try: status.favorite() logger.info( f"@{user}'s latest status has been successfully liked.") except Exception as e: logger.error( f"{e} while attempting to favorite @{user}'s latest status.", exc_info=True) if not status.retweeted: try: status.retweet() logger.info( f"@{user}'s latest status has been successfully retweeted." ) except Exception as e: logger.error( f"{e} while attempting to retweet @{user}'s latest status.", exc_info=True)
def reply_to_mentions(api, since_id): recent_since_id = since_id replies = [ "Hi there! The debugging ducky here. How can I help you? 8)", "Hiya! How's it going? :)", "Did you just call The Debug Ducky?", "Hey there! How can I help?", "Quack, quack!!!" ] for status in tweepy.Cursor(api.mentions_timeline, since_id=since_id).items(): random_idx = randrange(5) recent_since_id = max(status.id, recent_since_id) if "this is cs50" in status.text.lower(): logger.info( f"Replying 'This is CS50!' to @{status.user.screen_name}...") try: api.update_status( status=f"This is CS50! @{status.user.screen_name}", in_reply_to_status_id=status.id) logger.info( f"Replied 'This is CS50!' to @{status.user.screen_name}.") except Exception as e: logger.info(f"{e} while replying 'This is CS50!'.") return recent_since_id elif "hello" in status.text.lower(): logger.info(f"Replying to @{status.user.screen_name}...") try: api.update_status( status=f"{replies[random_idx]} @{status.user.screen_name}", in_reply_to_status_id=status.id) logger.info( f"Replied {replies[random_idx]} to @{status.user.screen_name}." ) except Exception as e: logger.error(f"{e} while replying.", exc_info=True) return recent_since_id return recent_since_id
def predict_trend(frame, instrument, period, point, models=None, scaler=None, clear_session=True): if frame.shape[0] != FRAME_LENGTH or frame.shape[1] != FRAME_COLUMNS: logger.error("Invalid frame shape!") return "NONE" if models is None: models = load_models(instrument, period) if len(models) == 0: logger.error("Models not found!") return "NONE" if scaler is None: scaler = load_scaler(instrument, period) if scaler is None: logger.error("Scaler not found!") return "NONE" scaled_data = scaler.transform(create_features(pd.DataFrame(frame), point)) frames = [] copy_sub_frame(0, FRAME_LENGTH, scaled_data, frames) predicts = [] for model in models: predicts.append( model.predict(np.expand_dims(np.asarray(frames), axis=3))) predicts = np.concatenate(predicts) y_pred = np.zeros(3) y_pred[0] = predicts[:, [0]].mean() y_pred[1] = predicts[:, [1]].mean() y_pred[2] = predicts[:, [2]].mean() label = 2 if y_pred[0] > y_pred[1] and y_pred[0] > y_pred[2] and y_pred[0] > 0.5: label = 0 elif y_pred[1] > y_pred[0] and y_pred[1] > y_pred[2] and y_pred[1] > 0.5: label = 1 if clear_session: K.clear_session() if label == 0: return "DOWN" elif label == 1: return "UP" else: return "NONE"
try: ser = serial.Serial('/dev/ttyAMA0', 115200, timeout=1) gsm = GSM(ser) mail_sender = MailSender() while 1: msgs = gsm.read_messages() gsm.delete_messages() for i in decode_encoded_messages(msgs): try: logger.info(f'接收到短信:{i}, 开始写sms.db') with open('sms.db', 'a') as f: f.write('%s\n' % i) logger.info('写db成功,开始发送邮件') mail_sender.send( '短信通知', '%s\r\n%s\r\n%s\r\n' % (i[0], i[1], i[2])) sys.stdout.flush() time.sleep(2) except Exception: logger.error(f"发送短信出错了,跳过该条短信:{i}", exc_info=True) time.sleep(5) time.sleep(10) except Exception as e: logger.error('出错了。。。', exc_info=True) finally: ser.close()
from logger_config import logger logger = logger('employee.log', __file__, 'file') class Employee: def __init__(self, first, last): self.first = first self.last = last logger.info('Employee created: {}'.format(self.fullname)) @property def fullname(self): return '{} {}'.format(self.first, self.last) emp1 = Employee('John', 'Doe') emp2 = Employee('Jane', 'Doe') if emp1.first != 'Dilip': logger.error("Invalid first name")
def on_error(self, status_code): if status_code == 420: logger.error(f"Error {status_code} on listener.", exc_info=True) return False else: logger.error(f"Error {status_code} on listener.", exc_info=True)
myStream = tweepy.Stream(api.auth, myStreamListener) logger.info("Connecting to Stream...") myStream.filter(track=keywords, languages=['en'], is_async=True, stall_warnings=True) logger.info("Connected to Stream.") since_id = get_latest_mention_id(api) + 1 while True: logger.info("Checking mentions...") since_id = reply_to_mentions(api, since_id) logger.info("Checking @davidjmalan's tweets...") favorite_and_retweet_user_status(api, "davidjmalan") logger.info("Checking @cs50's tweets...") favorite_and_retweet_user_status(api, "cs50") logger.info("Sleeping for 1 hour...") sleep(60 * 60) logging.info("main has returned.") if __name__ == '__main__': try: main(['#CS50', '#CS50x']) except Exception as e: logger.error(f"{e} on main.", exc_info=True)