def post(self): active_subs = Subscription.get_active_subscriptions() items = json.loads(self.request.get('items')) logging.debug('before parsing, memory: %s' % runtime.memory_usage().current()) parser = RentParser() parsed_items = [] for item in items: try: parsed = parser.parse(item) ret = RentRecord.add_record(parsed) except Exception as e: logging.error(repr(e)) parsed_items.append(parsed) logging.debug('after parsing, memory: %s' % runtime.memory_usage().current()) user2message = filter_items(parsed_items, active_subs) for user, item in user2message.items(): logging.debug('user: %s has %d messages' % (user, len(item))) User.update_user_items(user, item) url = get_short_url(user) if not url: url = site_config.url + '?user=%s' % user msg = [u'新找到%d条租房信息。' % len(item), u'点击以下链接查看:', url] messenger.send_message(user, '\n'.join(msg))
def webhook(): payload = request.get_data() for sender, message in messenger.messaging_events(payload): print "Incoming from %s: %s" % (sender, message) response = bot.respond_to(message) print "Outgoing to %s: %s" % (sender, response) messenger.send_message(FACEBOOK_TOKEN, sender, response) return "ok"
def webhook(): data=request.get_json() log(data) if data['object']=='page': for entry in data['entry']: for messagingEvent in entry['messaging']: senderId=messagingEvent['sender']['id'] if messagingEvent.get('message'): if 'text' in messagingEvent['message']: messageText=messagingEvent['message']['text'] if 'nlp' in messagingEvent['message'] and len(messagingEvent['message']['nlp'])>0 : response=generateReply(messageText,id=senderId,nlp=messagingEvent['message']['nlp']) else: response=generateReply(messageText,id=senderId) send_message(senderId,response) return "ok",200
def webhook(): payload = request.get_data() for sender, message in messenger.messaging_events(payload): print "Incoming from %s: %s" % (sender, message) # response = bot.respond_to(message) if "hi" in message: response = "hello: type 1:for play music 2: for youtube arijit singh" print "Outgoing to %s: %s" % (sender, response) messenger.send_message(FACEBOOK_TOKEN, sender, response) if "1" in message: response = "playing now" print "Outgoing to %s: %s" % (sender, response) call(["/usr/bin/rhythmbox-client", "--play"]) messenger.send_message(FACEBOOK_TOKEN, sender, response) if "2" in message: response = "playing arijit singh youtube" print "Outgoing to %s: %s" % (sender, response) call([ "/usr/bin/google-chrome", " https://www.youtube.com/watch?v=Z7hD0TUV24c" ]) messenger.send_message(FACEBOOK_TOKEN, sender, response) return "ok"
def webhook(): payload = request.get_data() for sender, message in messenger.messaging_events(payload): print("Incoming from "+str(sender)+": "+str(message)) client.run_actions(sender, message, {}) if done: print("Outgoing to "+str(sender)+": "+str(messageToSend )) len_of_msg=len(str(messageToSend)) print(str(len_of_msg)) if len_of_msg>=319: msg = str(messageToSend).split('\n') print(len(msg)) for x in range(int(len(msg)-2)): print(msg[x]) messenger.send_message(FACEBOOK_TOKEN, sender, msg[x]) else: messenger.send_message(FACEBOOK_TOKEN, sender, messageToSend) else: print("Outgoing to " + str(sender) + ": " + 'some problem interpreting') #print "Outgoing to %s: %s" % (sender, 'some problem interpreting') messenger.send_message(FACEBOOK_TOKEN, sender, 'some problem interpreting') return "ok"
def webhook(): print "DEBUG: WEBHOOK STARTS" #global know_id_flag #global Bot payload = request.get_data() for sender, message in messenger.messaging_events(payload): print("Incoming from %s: %s") % (sender, message) sender = str(sender) # if bot exists if sender not in bot: bot[sender] = Bot() bot[sender].fbid = sender data = check_andrew_ID(bot[sender].fbid) if bot[sender].andrewID != None and data["andrewID"] != "": bot[sender].andrewID = data["andrewID"] elif bot[sender].andrewID == None and data["andrewID"] != "": bot[sender].andrewID = data["andrewID"] response = "Welcome to ScottyAsks" + data["andrewID"] bot[sender].user.first_name = data["first_name"] bot[sender].user.last_name = data["last_name"] bot[sender].user.btc_address = data["btc_address"] bot[sender].user.btc_value = data["btc_value"] response = "welcome!" if bot[sender].andrewID == None: response = "Welcome to ScottyAsks. What is your Andrew ID?" bot[sender].andrewID = '' elif bot[sender].andrewID == '': data = send_unknown_id(bot[sender].fbid, str(message)) if data == "": response = "What is your Andrew ID?" else: print "hitting this" bot[sender].user.andrewID = data["andrewID"] bot[sender].user.first_name = data["first_name"] bot[sender].user.last_name = data["last_name"] bot[sender].user.btc_address = data["btc_address"] bot[sender].user.btc_value = data["btc_value"] else: response = bot[sender].respond_to(message) # user_info_dict = check_andrew_ID(sender) # curr_user_andrew_ID = user_info_dict["andrewID"] # # # # if (bot_exists(sender)): # print "DEBUG: BOT EXISTS" # # find existing bot set bot to it # curr_bot = bot[sender] # curr_bot.text = message # response = curr_bot.respond_to(message) # else: # no existing bot # bot[sender] = Bot() # if user_info_dict["andrewID"] != '': # print "DEBUG: BOT DOESNT EXIST, RECORD EXISTS" # # create new bot with info received from get # # only if record already exists in the db # curr_bot = bot[sender] # curr_bot.user.first_name = user_info_dict["first_name"] # curr_bot.user.last_name = user_info_dict["last_name"] # curr_bot.user.btc_address = user_info_dict["btc_address"] # curr_bot.user.btc_value = user_info_dict["btc_value"] # curr_bot.andrewID = curr_user_andrew_ID # response = curr_bot.respond_to(message) # else: # # no record exists, ask the user for AndrewID # if bot[sender].andrewID == None: # print "DEBUG: BOT DOESNT EXIST, RECORD DOESNT EXIST, ASK USER FOR ANDREWID" # # entering this the first time before the user gave us the andrewID # response = "We don't know you. What is your Andrew ID?" # bot[sender].andrewID = '' # else: # print "DEBUG: BOT DOESNT EXIST, RECORD DOESNT EXIST, GOT ANDREW ID, ASK DB FOR INFO" # # user entered andrewID # curr_user_andrew_ID = str(message) # # if (send_unknown_id(sender,curr_user_andrew_ID) == ""): # # andrewID is wrong # bot[sender].andrewID = None # #know_id_flag = True # else: # #curr_bot = Bot() # bot[sender].andrewID = curr_user_andrew_ID # user_info_dict["andrewID"] = curr_user_andrew_ID # #know_id_flag = False # # else: # # response = curr_bot.respond_to(message) print("Outgoing to %s: %s") % (sender, response) messenger.send_message(FACEBOOK_TOKEN, sender, response) return "ok"
def execute(): global cfg logger.info('Loading configurations') try: with open("config.yml", 'r', encoding='utf8') as ymlfile: cfg = yaml.safe_load(ymlfile) except FileNotFoundError: logger.critical('To execute this script it is necessary config.yml') exit() scopes = [ "https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets', "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive" ] credentials = ServiceAccountCredentials.from_json_keyfile_dict( load_keyfile_dict(), scopes) client = gspread.authorize(credentials) sheet = client.open(cfg['google']['sheet_name']).sheet1 deliveries = [] for item, values in cfg['itens'].items(): deliveries += process_delivery(sheet, item, values['weekday']) logger.info("Found {}".format(len(deliveries))) if (len(deliveries) > 0): client = MongoClient(os.environ['MONGO_URL']) database = client['alerts'] user_collection = database['users'] for delivery in deliveries: user = user_collection.find_one( {"spreadsheet_identifier": delivery['person_name']}) if (user != None): if ("alert_weekday" in user and user['alert_weekday'] != None and user['alert_weekday'] != "" and str(datetime.date.today().weekday()) == user['alert_weekday']): if ('email' in user and user['email'] != None and user['email'] != ""): delivery['sent'] = messenger.send_email(user, delivery) if ('alert_telegram' in user and user['alert_telegram']): delivery['sent'] = messenger.send_message( user, delivery) logger.info('Nome: {}, Quantidade: {}, Valor: {}'.format( delivery['person_name'], delivery['quantity'], delivery['value'])) else: logger.info( 'Do not send notification today {} to {}, configuration = {}' .format(datetime.date.today().weekday(), delivery['person_name'], user['alert_weekday'])) else: logger.info('Não há usuário cadastrado') logs_collection = database['logs'] log_id = logs_collection.insert_many(deliveries) logger.info('Insert {} log registers into database'.format( len(deliveries))) client.close()