def handle_message(data, table): print(data) message = str(data["message"]["text"]) chat_id = data["message"]["chat"]["id"] message_id = data["message"]["message_id"] #first_name = data["message"]["chat"]["first_name"] if '/start' in message: handle_start(chat_id=chat_id, table=table) return if '/new' in message: handle_new(message=message, message_id=message_id, chat_id=chat_id, table=table) return if '/delete' in message: handle_delete(message=message, message_id=message_id, chat_id=chat_id, table=table) return if '/list' in message: handle_list(chat_id=chat_id, table=table) return if '/force' in message: crawl_tutti(table) return #reply = 'sorry I did not quite get that' + help send_message('debug:\n' + message, chat_id) return
def send_list_message(recipient_id, title, category): data = json.dumps({ "recipient": { "id": recipient_id }, "message": { "attachment": { "type": "template", "payload": { "template_type": "generic", "elements": [{ "title": "#" + title, "buttons": [] }] } } } }) data = json.loads(data) data["message"]["attachment"]["payload"]["elements"][0]["buttons"].append({\ "type":"postback",\ "title": category.name,\ "payload": "category" + " " + str(category.id) }) data = json.dumps(data) send_message(data)
def handle_list(chat_id, table): keywords = table.get_item(Key={'id': chat_id}).get('Item').get('keywords') real_keawords = [ keyword for keyword in keywords if 'placeholder-keyword' not in keyword ] msg = 'your current keywords are: \n' + ' '.join(real_keawords) send_message(msg, chat_id)
def run(smtp_address, smtp_port, smtp_username, smtp_password, number, carrier, sender): number_dir = os.path.join(DIRNAME, RELATIVE_NUMBERS_DIR, number) if not os.path.exists(number_dir): raise RuntimeError('Path does not exist: {}'.format(number_dir)) progress_file_path = os.path.join(number_dir, PROGRESS_FILENAME) if not os.path.exists(progress_file_path): with open(progress_file_path, 'x'): pass send_message( smtp_address, smtp_port, smtp_username, smtp_password, number, carrier, sender, subject=WELCOME_SUBJECT, message=WELCOME_MESSAGE, ) file_path = get_next_file_path_for_number(number_dir) message = None attachments = () if file_path.endswith('txt'): # use first line as subject with open(file_path) as fp: subject = fp.readline().strip() message = fp.read().replace('\n', ' ').strip() else: # use file name as subject basename_parts = os.path.basename(file_path).split('.') parts = (part.replace('_', ' ') for part in basename_parts[:-2]) subject = ''.join(parts) attachments = (file_path, ) send_message( smtp_address, smtp_port, smtp_username, smtp_password, number, carrier, sender, subject, message=message, attachments=attachments, ) with open(progress_file_path, 'a') as fp: writer = csv.writer(fp) now = str(datetime.datetime.utcnow()) writer.writerow([now, file_path])
def send_text_message(recipient_id, message_text): data = json.dumps({ "recipient": { "id": recipient_id }, "message": { "text": message_text } }) send_message(data)
def webhook(): data = request.get_json() data['text'] = data['text'].lower() if "!bible" in data['text']: bible.bible_handle(data['text']) if "!weather" in data['text']: send_message(weather.retrieve_weather(data['text'])) if "hello there" in data['text']: send_message("General Kenobi!") return "ok", 200
def send_image_question_message(recipient_id, word, another_choices, do_exercise=False): question = "What's in the picture?" data = json.dumps({ "recipient": { "id": recipient_id }, "message": { "text": question } }) send_message(data) data = json.dumps({ "recipient": { "id": recipient_id }, "message": { "attachment":{ "type":"image", "payload":{ "url":BingSearchImage.get_image(word.name) } }, "quick_replies": [] } }) data = json.loads(data) payload = "Question" if do_exercise: payload = "Exercise" buttons = [] buttons.append({ "content_type":"text", "title": word.name, "payload": payload + "_True" }) for another_choice in another_choices: buttons.append({ "content_type":"text", "title": another_choice, "payload": payload + "_False_" + word.name }) random.shuffle(buttons) for button in buttons: data["message"]["quick_replies"].append(button) data = json.dumps(data) send_message(data)
def handle_start(chat_id, table): #add user to known users table.update_item(Key={'id': 0}, UpdateExpression='add chat_id :val', ExpressionAttributeValues={':val': {chat_id}}) # create user entry with table.batch_writer() as batch: row = { "id": chat_id, "keywords": {'placeholder-keyword'}, } batch.put_item(Item=row) #send welcome message welcome_msg = 'Welcome to the Tutti alert Bot \n' + help send_message(welcome_msg, chat_id)
def send(session_id, country): """ This function sends messages from Wit to Messenger. :param session_id: :param country: :return: True """ id_ = session_manager.get_session(session_id)["id"] # check if the country is missing if country is None: # at some point, I should add the text to the context in get_travel_advisory so I can access it here ### logger.error("{}, Country: Missing".format(id_)) ### send_message( id_, "Where? I'm still getting the hang of this. Try and make sure the country is spelled correctly." ) else: ### logger.info("{}, Country: {}".format(id_, country)) ### # get advisory advisory = advisory_country(country) # prepare image image = "static/adv-cat-{}.png".format(advisory["advisory_code"]) indicator = "This is a category {} warning (out of 4)".format( advisory["advisory_code"]) url = "https://travel.gc.ca{}".format(advisory["url"]) send_attachment(id_, "{}: {}".format(country, advisory["advisory"]), indicator, image, url) return True
def handle_new(message, message_id, chat_id, table): #remove new_alert command message = message.split() print(message) #make sure keyword submitted if len(message) == 1: send_reply_message('use \'/new keyword\' to submit a new keyword', message_id, chat_id) return #everything but the command is the keyword keyword = ' '.join(message[1:]) print(keyword) table.update_item(Key={'id': chat_id}, UpdateExpression='add keywords :val', ExpressionAttributeValues={':val': {keyword}}) msg = 'You will get an alert as soon as new products for ' + keyword + ' are available' send_message(msg, chat_id)
def send_audio_question_message(recipient_id, word): #get sound # sound_url = "http://dict.laban.vn/ajax/getsound?accent=uk&word=" + word.name.lower() # r = requests.get(sound_url) # r = r.json() # log(r) # # sound_link = "http://" # # if int(r["error"]) == 0: # sound_link = r["data"] data = json.dumps({ "recipient": { "id": recipient_id }, "message": { "text": "What word in this audio?" } }) send_message(data) sound_link = "http://stream.dict.laban.vn/uk/d422d0ec37672abb3f2fef58b94c608d/157765c6199/H/hello.mp3" # sound_link = word.link_pronunciation log(sound_link) data = json.dumps({ "recipient": { "id": recipient_id }, "message": { "attachment": { "type": "audio", "payload": { "url": sound_link } } } }) send_message(data)
def send_question_message(recipient_id, word, another_choices, do_exercise): question = word.name.title() + " mean?" data = json.dumps({ "recipient": { "id": recipient_id }, "message": { "text": question, "quick_replies": [] } }) data = json.loads(data) payload = "Question" if do_exercise: payload = "Exercise" buttons = [] buttons.append({ "content_type": "text", "title": word.meaning, "payload": payload + "_True" }) for another_choice in another_choices: buttons.append({ "content_type": "text", "title": another_choice, "payload": payload + "_False_" + word.meaning }) random.shuffle(buttons) for button in buttons: data["message"]["quick_replies"].append(button) data = json.dumps(data) send_message(data)
def bible_handle(passage): req = passage.replace('!bible', '') try: msg = bible_search(req) #why 2? I have no idea if (len(msg) == 2): send_message("Sorry, I couldn't find that passage!") return if (len(msg) + len(req) + 5 < 1000): send_message("{} (ESV)".format(msg)) elif len(msg) + len(req) > 2000: send_message("Too much to print... shorten your search") else: for chunk in chunks(msg, 1000): send_message(chunk) send_message("(ESV)") except: send_message("Sorry, I couldn't find that passage!")
def webhook_callback(): ### logger.info("MESSAGING EVENT RECEIVED.") ### data = request.json # ensure that callback came from a "page" object if data["object"] == "page": # go through each entry for entry in data["entry"]: # only if messaging if "messaging" in entry: # go through each messaging event for event in entry["messaging"]: # check if we have a new message if "message" in event: ### logger.info("MESSAGE RECEIVED.") ### # get sender sender = event["sender"]["id"] # get session token token = session_manager.get_session_token(sender) # try and find session existing_session = session_manager.get_session(token) # get message message = event["message"] # check to see if this is a new user/session if existing_session is None: ### logger.info("New session: {}".format(sender)) ### # mark seen send_mark_seen(sender) session_manager.create_session(sender, **{ "context": {}, "lang": 0 }) # check to see if it is a message or attachment elif "attachments" in message: ### logger.info("Attachment received from: {}".format(sender)) ### # typing... send_typing(sender) # cannot process attachments send_message(sender, "I can't do much with that, but if you send me a name of a country, I can tell you the travel advisory for it.") elif "text" in message: ### logger.info("Text received from: {}".format(sender)) ### # typing... send_typing(sender) # get session ID session_id = session_manager.get_session_token(sender) # converse response = wit.message(msg=message["text"], context={"session_id": session_id}) # respond handle_message(response, session_id) # check if we have a message delivered elif "delivery" in event: ### logger.info("MESSAGE DELIVERED.") ### # check if a message was read elif "read" in event: ### logger.info("MESSAGE READ.") ### # check if we have a postback elif "postback" in event: ### logger.info("POSTBACK RECEIVED.") ### # get sender sender = event["sender"]["id"] # get postback data postback = event["postback"] payload = postback["payload"] # what do I do? if payload == "WHAT_DO_I_DO": # typing... send_typing(sender) # cannot process attachments send_message(sender, "I want you to help you stay informed when travelling abroad. Ask me something like \"What is the current travel advisory for the Brazil?\".") else: ### logger.error("UKNOWN MESSAGING EVENT.") ### return make_response(jsonify({}), 200)
def test_invalid_body(self): ret_msg = send_message(body=100, phone="07438483904") self.assertEqual(str(ret_msg), "queued")
def test_null_phone(self): ret_msg = send_message(body="Test 2") self.assertEqual(str(ret_msg), "invalid_number")
def test_null_body_and_phone(self): ret_msg = send_message() self.assertEqual(str(ret_msg), "invalid_number")
for row in table: if (row[0] == 'Batsman' or row[0] == 'Bowler'): print( colored("{:<24} {:<8} {:<8} {:<8} {:<8} {:<8}".format( row[0], row[1], row[2], row[3], row[4], row[5]), 'cyan', attrs=['bold'])) batter = not batter else: print( colored( "{:<24} {:<8} {:<8} {:<8} {:<8} {:<8}".format( row[0], row[1], row[2], row[3], row[4], row[5]), 'white')) if (batter): msg = '\n' + row[0] + ': ' + row[1] + '(' + row[ 2] + ')' + ' ' + 'S.R. ' + row[5] message += msg else: msg = '\n' + row[0] + ': ' + row[1] + '-' + row[ 2] + '-' + row[3] + '-' + row[4] message += msg t = time.localtime() current_time = time.strftime("%H:%M:%S", t) message += ('\nThis is the latest score updated at: ' + current_time) print('\n') # replace this with the name of the contact you want to send the scorecard to send_message('name-of-contact', message, browser) time.sleep(300)
def test_valid_params(self): ret_msg = send_message(body="Test 1", phone="07438483904") self.assertEqual(str(ret_msg), "queued")
def send_word_message(recipient_id, word): data = json.dumps({ "recipient": { "id": recipient_id }, "message": { "attachment": { "type": "template", "payload": { "template_type": "generic", "elements": [{ "title": word.name, "image_url": BingSearchImage.get_image(word.name), "subtitle": word.meaning + " - " + word.pronunce + " - Example: " + word.example, }] } }, } }) send_message(data) #get sound # sound_url = "http://dict.laban.vn/ajax/getsound?accent=uk&word=" + word.name.lower() # r = requests.get(sound_url) # r = r.json() # log(r) # # sound_link = "http://" # # if int(r["error"]) == 0: # sound_link = r["data"] # sound_link = "http://stream.dict.laban.vn/uk/d422d0ec37672abb3f2fef58b94c608d/157765c6199/H/hello.mp3" sound_link = "http://api.voicerss.org/?key=2639193b13e245cb918270a1846cae5e&hl=en-us&src=" + word.name # log(sound_link) data = json.dumps({ "recipient": { "id": recipient_id }, "message": { "attachment": { "type": "audio", "payload": { "url": sound_link } }, "quick_replies": [ # { # "content_type":"text", # "title": "Say it", # "payload": "" # }, { "content_type": "text", "title": "Got it", "payload": "Word" + " " + str(word.id) } ] } }) send_message(data)
def test_null_empty_body(self): ret_msg = send_message(body="", phone="07438483904") self.assertEqual(str(ret_msg), "invalid_body")