def send_delays(): if session['user']: if mta.service_status().has_delays(): message = 'there are some f*****g delays' else: message = 'there are no f*****g delays' user = db.getUser(session['user']) sms.send_message(message, int(user['phone'])) return redirect("/")
def text_changes(changes): ## texts formatted changes to user ## accepts list of changes as parameter message = "" changes = sorted(changes, key=lambda x: x[0]) ## sort by course name courses = list(set([x[0] for x in changes])) currCourse = "" for change in changes: if change[0] != currCourse: message += "-- {} --\n".format(COURSE_NAMES[change[0]]) currCourse = change[0] message += "{}\n[{} - {}]\n".format(change[2], change[3], change[4]) message = message.strip() ##print(message) sms.send_message(message) return
def process_sms(self, sms, user_group='sys_public'): language = sms.get_language_from_sms() # Set user language preference sms.set_user_language_preference(language=language) control_word = sms.get_control_word_from_sms() action_word = sms.get_action_word_from_sms() try: translation.activate(language) if language == 'en': if user_group == 'sys_admin': sms_control_translations = SmsControl.objects.all() elif user_group == 'sys_reporter': sms_control_translations = SmsControl.objects.filter(Q(group__name='sys_public') | Q(group__name='sys_reporter')) else: sms_control_translations = SmsControl.objects.filter(group__name='sys_public') else: if user_group == 'sys_admin': sms_control_translations = SmsControlTrans.objects.select_related().filter( sms_control_locale__language_code__iexact=language, ) elif user_group == 'sys_reporter': sms_control_translations = SmsControlTrans.objects.select_related().filter( Q(sms_control__group__name='sys_public') | Q(sms_control__group__name='sys_reporter'), sms_control_locale__language_code__iexact=language, ) else: sms_control_translations = SmsControlTrans.objects.select_related().filter( sms_control_locale__language_code__iexact=language, sms_control__group__name='sys_public', ) # No message text received if not sms.message: reply_message = render_to_string('sms_control/reply/null_message.txt', {'sms_control_translations': sms_control_translations, 'language': language,}) return send_message(smart_str(reply_message), [sms.from_number,]) # No control word available if not control_word: reply_message = render_to_string('sms_control/reply/invalid_request.txt', {'sms_control_translations': sms_control_translations, 'language': language,}) return send_message(smart_str(reply_message), [sms.from_number,]) # General help message if control_word == 'help': reply_message = render_to_string('sms_control/reply/help.txt', {'sms_control_options': sms_control_translations, 'language': language,}) return send_message(smart_str(reply_message), [sms.from_number,]) # Control word + help. Ex. 'subscribe help' if action_word == 'help': reply_message = render_to_string('sms_control/reply/' + str(control_word) + '_help.txt', {'language': language,}) return send_message(smart_str(reply_message), [sms.from_number]) # Subscribe if control_word == 'subscribe': ss = shlex.shlex(smart_str(sms.message)) ss.whitespace += ',' location_uid_args = list(ss)[1:] location_objects = [] for location_uid in location_uid_args: try: location = Location.objects.get(uid__iexact=location_uid) location_objects.append(location) except: pass # DEMO Default Location UID subscription # if not location_uid_args: default_location_uid = getattr(settings, 'DEFAULT_LOCATION_UID', None) if default_location_uid: try: location = Location.objects.get(uid__iexact=default_location_uid) location_objects.append(location) except: pass # End DEMO # if not location_objects: # No valid locations received reply_message = render_to_string('sms_control/reply/subscribe_location_error.txt', {'language': language,}) return send_message(smart_str(reply_message), [sms.from_number]) # Get profile and user objects try: profile = Profile.objects.select_related().get(mobile=sms.from_number) user = profile.user except Profile.DoesNotExist: user = User(username=sms.from_number) user.set_unusable_password() user.save() profile = Profile(user=user, mobile=sms.from_number) profile.save() subscribed_locations = [] for location_object in location_objects: try: location_subscription = LocationSubscription.objects.get( user=user, location=location_object, ) location_subscription.phone_subscription = True location_subscription.save() subscribed_locations.append(location_object) except LocationSubscription.DoesNotExist: location_subscription = LocationSubscription( user=user, location=location_object, email_subscription=LocationSubscription.EMAIL_NONE_FREQ, phone_subscription=True, ) location_subscription.save() subscribed_locations.append(location_object) except: pass if not subscribed_locations: return True reply_message = render_to_string('sms_control/reply/subscribe_success.txt', {'subscribed_locations': subscribed_locations, 'language': language,}) return send_message(smart_str(reply_message), [sms.from_number,]) # UnSubscribe if control_word == 'unsubscribe': # Set anonymous variable try: profile = Profile.objects.select_related().get(mobile=sms.from_number) anonymous = False except: profile = None anonymous = True ss = shlex.shlex(smart_str(sms.message)) ss.whitespace += ',' location_uid_args = list(ss)[1:] location_objects = [] if not anonymous and 'all' in location_uid_args: try: location_subscriptions = LocationSubscription.objects.select_related().filter( user=profile.user, phone_subscription=True, ) for ls in location_subscriptions: location_objects.append(ls.location) if not location_objects: # User not subscribed to any locations reply_message = render_to_string('sms_control/reply/unsubscribe_no_subscriptions_error.txt', {'language': language,}) return send_message(smart_str(reply_message), [sms.from_number]) except: pass else: for location_uid in location_uid_args: try: location = Location.objects.get(uid__iexact=location_uid) location_objects.append(location) except: pass if not location_objects: # No valid locations received reply_message = render_to_string('sms_control/reply/unsubscribe_location_error.txt', {'language': language,}) return send_message(smart_str(reply_message), [sms.from_number]) # Get profile and user objects try: profile = Profile.objects.select_related().get(mobile=sms.from_number) user = profile.user except: reply_message = render_to_string('sms_control/reply/unsubscribe_no_account_error.txt', {'language': language, 'sms': sms}) return send_message(smart_str(reply_message), [sms.from_number]) unsubscribed_locations = [] for location_object in location_objects: try: location_subscription = LocationSubscription.objects.get( user=user, location=location_object, ) location_subscription.phone_subscription = False location_subscription.save() unsubscribed_locations.append(location_object) except LocationSubscription.DoesNotExist: unsubscribed_locations.append(location_object) except: pass if not unsubscribed_locations: return True reply_message = render_to_string('sms_control/reply/unsubscribe_success.txt', {'unsubscribed_locations': unsubscribed_locations, 'language': language,}) return send_message(smart_str(reply_message), [sms.from_number,]) # Report if control_word == 'report': # Set anonymous variable try: profile = Profile.objects.select_related().get(mobile=sms.from_number) anonymous = False except: profile = None anonymous = True ss = shlex.shlex(smart_str(sms.message)) ss.whitespace += ',' location_uid_args = list(ss)[1:] location_objects = [] for location_uid in location_uid_args: try: location = Location.objects.get(uid__iexact=location_uid) location_objects.append(location) except: pass if not location_objects: if anonymous: # No valid locations received reply_message = render_to_string('sms_control/reply/report_location_error_anonymous.txt', {'language': language,}) return send_message(smart_str(reply_message), [sms.from_number]) else: try: ls = LocationSubscription.objects.select_related().filter( user=profile.user, phone_subscription=True, ).order_by('-location__published_date')[0] try: location_post = LocationPost.active_objects.filter( type=LocationPost.WATER_QUALITY_TYPE, location=ls.location, ).order_by('-published_date')[0] if location_post.chlorine_level >= Decimal('0.50') and location_post.chlorine_level < Decimal('2.00'): safe_water = True else: safe_water = False except: location_post = None safe_water = None reply_message = render_to_string('sms_control/reply/report.txt', {'location': ls.location, 'location_post': location_post, 'safe_water': safe_water, 'language': language}) return send_message(smart_str(reply_message), [sms.from_number]) except: reply_message = render_to_string('sms_control/reply/report_location_error.txt', {'language': language,}) return send_message(smart_str(reply_message), [sms.from_number]) else: for location_object in location_objects: try: location_post = LocationPost.active_objects.filter( type=LocationPost.WATER_QUALITY_TYPE, location=location_object, ).order_by('-published_date')[0] if location_post.chlorine_level >= Decimal('0.50') and location_post.chlorine_level < Decimal('2.00'): safe_water = True else: safe_water = False except: location_post = None safe_water = None reply_message = render_to_string('sms_control/reply/report.txt', {'location': location_object, 'location_post': location_post, 'safe_water': safe_water, 'language': language}) result = send_message(smart_str(reply_message), [sms.from_number]) if not result: return False return True # Status if control_word == 'status': try: profile = Profile.objects.select_related().get(mobile=sms.from_number) ls = LocationSubscription.objects.select_related().filter( user=profile.user, phone_subscription=True, ) except: ls = [] reply_message = render_to_string('sms_control/reply/status.txt', {'location_subscriptions': ls, 'language': language}) return send_message(smart_str(reply_message), [sms.from_number]) ### Reporter Class ### # Update if control_word == 'update': """ Example of update sent from a reporter "131009 g 15 gd 0" 131009 - location uid g - shorthand for source type 15 - 1.5 chlorine % gd - organization code 0 - shorthand remarks """ if user_group == 'sys_admin' or user_group == 'sys_reporter': ss = shlex.shlex(smart_str(sms.message)) update_args = list(ss)[1:] try: profile = Profile.objects.select_related().get(mobile=sms.from_number) user = profile.user except: reply_message = render_to_string('sms_control/reply/update_unknown_user_error.txt', {'language': language,}) return send_message(smart_str(reply_message), [sms.from_number]) try: location = Location.objects.get(uid__iexact=update_args[0]) except: reply_message = render_to_string('sms_control/reply/update_location_error.txt', {'language': language,}) return send_message(smart_str(reply_message), [sms.from_number]) try: water_source_type = WaterSourceType.objects.get(mobile_shorthand_code__iexact=update_args[1]) except: water_source_type = None try: chlorine_level_list = list(update_args[2]) chlorine_level = Decimal(str(chlorine_level_list[0]) + str('.') + str(''.join(chlorine_level_list[1:]))) except: reply_message = render_to_string('sms_control/reply/update_chlorine_level_error.txt', {'language': language,}) return send_message(smart_str(reply_message), [sms.from_number]) try: provider = Provider.objects.get(mobile_shorthand_code__iexact=update_args[3]) except: provider = None try: reporter_remark_code = int(update_args[4]) reporter_remark = LocationPostReporterRemarks.objects.get(code=reporter_remark_code) remark = reporter_remark.text except: try: remark = update_args[4] except: remark = '' try: location_post = LocationPost( user=user, location=location, type=LocationPost.WATER_QUALITY_TYPE, content=remark, water_source_type=water_source_type, provider=provider, chlorine_level=chlorine_level, status=LocationPost.ACTIVE_STATUS, published_date=sms.sent_date, ) location_post.save() reply_message = render_to_string('sms_control/reply/update.txt', {'language': language, 'location_post': location_post,}) return send_message(smart_str(reply_message), [sms.from_number]) except: reply_message = render_to_string('sms_control/reply/update_failed.txt', {'language': language,}) return send_message(smart_str(reply_message), [sms.from_number]) else: reply_message = render_to_string('sms_control/reply/invalid_request.txt', {'sms_control_options': sms_control_translations, 'language': language,}) return send_message(smart_str(reply_message), [sms.from_number]) ### Admin Class ### # Stats if control_word == 'stats': if user_group != 'sys_admin': reply_message = render_to_string('sms_control/reply/invalid_request.txt', {'sms_control_options': sms_control_translations, 'language': language,}) return send_message(smart_str(reply_message), [sms.from_number]) location_posts = LocationPost.active_objects.filter( type=LocationPost.WATER_QUALITY_TYPE, published_date__gte=(datetime.datetime.now() - datetime.timedelta(days=1)), ) users = User.objects.filter(is_active=True, groups__name='sys_public') locations = Location.active_objects.all() reply_message = render_to_string('sms_control/reply/stats.txt', { 'locations_posts_count': location_posts.count(), 'users_count': users.count(), 'locations_count': locations.count(), 'language': language,} ) return send_message(smart_str(reply_message), [sms.from_number]) return True except Exception, e: logger.error("Error processing sms id: %d. Error is %s", (sms.id, e)) return False
body_str += f"* {item.name_full} vacancies: {item.vacancies} rents: {item.rents}\n" else: body_str += "None\n" #Split the message if over 800 chars long, split the texts if len(body_str) > 1200: start_index = 0 ending_index = 600 while (ending_index < len(body_str)): str_segment = "" if (ending_index > len(body_str)): str_segment = body_str[start_index:] else: str_segment = body_str[start_index:ending_index] recipients = json.loads(os.environ["NUMBERS"]) sms.send_message(recipients, str_segment) start_index = ending_index ending_index += 600 else: recipients = json.loads(os.environ["NUMBERS"]) sms.send_message(recipients, body_str) with open("/home/pi/dev/apt-get/database.json", "w") as database: json.dump(database_list, database, default=lambda o: o.__dict__, indent=2) logging.info("################ FINISHED ################")
def worker(self, *args, **kwargs): while True: try: location_post_id = self.work_queue.get_nowait() location_post = LocationPost.objects.get(id=location_post_id) logger.info("Starting water_quality_notification_mobile processing for LocationPost id: %d" % location_post.id) except Exception, e: time.sleep(20) continue if location_post.chlorine_level >= Decimal('0.50') and location_post.chlorine_level < Decimal('2.00'): safe_water = True else: safe_water = False try: location_subscriptions = LocationSubscription.objects.select_related().filter( location=location_post.location, phone_subscription=True, user__is_active=True, user__profile__id__isnull=False, ).exclude(user__profile__mobile='') logger.info("Found %d mobile subscriptions for %s location" % (location_subscriptions.count(), location_post.location)) for location_subscription in location_subscriptions: # Have we already sent a notification??? try: existing_log = LocationPostNotificationLog.objects.get( user=location_subscription.user, location_post=location_post, notification_type=LocationPostNotificationLog.MOBILE, ) logger.info("Already sent mobile notification to %s for LocationPost id %d" % (location_subscription.user, location_post.id)) continue except: pass profile = location_subscription.user.get_profile() language = profile.language translation.activate(language) reply_message = render_to_string('water_quality_notification/sms/mobile.txt', { 'location': location_post.location, 'location_post': location_post, 'safe_water': safe_water, 'language': language}) sms_result = send_message(smart_str(reply_message), [profile.mobile]) if sms_result: location_post_notification_log = LocationPostNotificationLog( user=location_subscription.user, location_post=location_post, notification_type=LocationPostNotificationLog.MOBILE, ) location_post_notification_log.save() logger.info("Successfully sent mobile notification for LocationPost id %d to %s" % (location_post.id, location_subscription.user)) translation.deactivate() location_post.water_quality_notification_mobile_status = LocationPost.COMPLETE_STATUS location_post.save() except Exception, e: logger.error("Error processing water_quality_notification_mobile for LocationPost id %d: %s" % (location_post.id, e))
currCourse = change[0] message += "{}\n[{} - {}]\n".format(change[2], change[3], change[4]) message = message.strip() ##print(message) sms.send_message(message) return oldData = [] loginData = read_login() lastTime = datetime.datetime.now() sms.send_message("Grade checker service has started running.") while True: session = login(loginData) data = get_all_assignments(session) if oldData == []: oldData = data changes, oldData = find_changes(oldData, session) if (len(changes) > 0): print("CHANGES: {}".format(changes)) print("Found {} changes. Notifying user.".format(len(changes))) text_changes(changes) now = datetime.datetime.now()
def test(): if request.method == "GET": sms.send_message("hello there", 9174350162) if request.method == "POST": print "haven't set up receiving messages yet"
# database_connection('insert into watch_list (bid, occurences) values (%s, 1)', 'insert', bid) # else: # # print(check[0]) # for check in checks: # # print(check) # # occurences = int(check['occurences']) + 1 # database_connection('update watch_list set occurences = %s where bid = %s', 'update',int(check['occurences']) + 1, bid) # database_connection('IF NOT EXISTS (select * from missing_occurences where (bid = %s and acknowledged_timestamp IS NULL)) THEN insert into missing_occurences (bid, timestamp, receiverid) values (%s,%s,%s); END IF', 'insert', bid, bid, timestamp, receiverid) check = database_connection( 'select * from missing_occurences where bid = %s and date = %s', 'select', bid, date_obj) if check == []: database_connection( 'insert into missing_occurences (bid, date, time, receiverid) values (%s,%s,%s, %s)', 'insert', bid, date_obj, time_obj, receiverid) # database_connection('insert into missing_occurences (bid, timestamp, receiverid) values (%s,%s,%s)', 'insert', bid, timestamp, receiverid) # Preconfigured string for text message to be sent text = "Elderly {} is has gone missing at {}. Please check up on the elderly.".format( name, receiverid) # SMS function for staff in staffs: number = '+' + staff['contact'] # print(text) sms.send_message(text, number) # print('end')