Beispiel #1
0
def resend_otp(request):
    response_json = {}
    if request.method == "POST":
        try:
            access_token = request.POST.get(keys.KEY_TEMP_ACCESS_TOKEN)
            print access_token
            json1 = jwt.decode(str(access_token),
                               keys.KEY_TEMP_ACCESS_TOKEN_ENCRYPTION,
                               algorithms=['HS256'])
            mobile = str(json1['access_token'])
            user_instance = UserData.objects.get(mobile=mobile)

            try:
                otp = OtpData.objects.get(user=user_instance).otp
                message = 'Welcome to Kleos. Your One Time Password is ' + str(
                    otp)
                send_sms(mobile, message)

                response_json[keys.KEY_SUCCESS] = True
                response_json[keys.KEY_MESSAGE] = "OTP sent"
            except Exception as e:
                print(e)
                response_json[keys.KEY_SUCCESS] = False
                response_json[keys.KEY_MESSAGE] = "OTP sent failed " + str(e)

        except Exception as e:
            print(e)
            response_json[keys.KEY_SUCCESS] = False
            response_json[keys.KEY_MESSAGE] = "Access Token not found" + str(e)

    print(response_json)
    return JsonResponse(response_json)
Beispiel #2
0
def sms():
    if request.method != "GET":
        return make_sms_response("Invalid SMS.")

    # Get our parameters from the query string
    msg = request.args.get('Body')
    from_number = request.args.get('From')
    to_number = request.args.get('To')

    if not msg or not from_number or not to_number:
        return make_sms_response("Invalid SMS.")

    # Just to debug
    app.logger.warning("From: %s, To: %s, Message: %s\n" % (from_number, to_number, msg))
    cmd = msg.lower()
    if cmd in CONNECT_SYNONYMS:
        return users.connect(from_number)
    elif cmd in DISCONNECT_SYNONYMS:
        return users.disconnect(from_number)
    elif cmd in REFRESH_SYNONYMS:
        return users.refresh(from_number)
    elif cmd in CALL_SYNONYMS:
        return users.call(from_number)
    elif cmd in STATS_SYNONYMS:
        return users.stats(from_number)
    else:
        (peer_number, text) = users.msg(from_number, msg)
        send_sms(peer_number, text)
        return ""
Beispiel #3
0
def confirm_sms():
    if request.method == 'GET':
        user = User.query.filter_by(user_id=current_user.user_id).first_or_404()
        previous_auth_codes = AuthCode.query.filter_by(owner=user.user_id).filter_by(active=1)
        for code in previous_auth_codes:
            db.session.delete(code)
        db.session.commit()

        sms_code = generate_sms_code()
        send_sms(user.phone_number,'(469) 518-7212',sms_code)
        auth_code = AuthCode(auth_code=sms_code,auth_type='sms',sent=True,
            sent_time=datetime.datetime.now(),owner=user.user_id)
        db.session.add(auth_code)
        db.session.commit()
        flash('Enter the code sent to your phone number')
        return render_template('users/sms_activate.html')

    sms_code = (request.form['sms_code']).strip()
    user = User.query.filter_by(user_id=current_user.user_id).first_or_404()
    auth_code = AuthCode.query.filter_by(owner=current_user.user_id).filter_by(active=1).first()
    print sms_code
    print auth_code.auth_code
    if(str(auth_code.auth_code) == sms_code):
        db.session.delete(auth_code)
        if user.active != 2:
            user.active = 2
            db.session.add(user)
        db.session.commit()
    else:
        flash('The confirmation link is invalid or has expired.', 'danger')
        return render_template('users/resend_sms_activation.html')
    flash('You have confirmed your account. ', 'success')
    return redirect(url_for('authenticated.index'))
Beispiel #4
0
def call(number):
    """@number wishes to share the number with the other person."""
    if not r.exists(number):
        return build_sms("Error: You haven't connected to anyone yet.")
    peer_number = r.get(number)
    send_sms(peer_number, "The other person has shared their number: %s" % (number))
    return ""
Beispiel #5
0
    def post(self, request, **kwargs):
        try:
            slug = kwargs['account_slug']
            account = Account.objects.get(holders__in=[request.user],
                                          slug=slug)
        except Account.DoesNotExist:
            raise PermissionDenied(
                detail='No available account with name found.')

        try:
            amount = parse_money(request.data['amount'])
        except KeyError:
            raise ParseError(detail='Missing data: amount')

        try:
            contact = Contact.objects.get(user=request.user)
        except Contact.DoesNotExist:
            raise PermissionDenied(detail='No contact info for user found.')

        owed_to = kwargs['owed_to']
        owing, created = AmountOwing.objects.get_or_create(account=account,
                                                           owed_to=owed_to)
        owing.amount = amount
        owing.save()

        if amount > zero_dollars():
            message = f"There is an balance of {amount} on your account with {owed_to}"
            send_sms(contact.phone_number, message)

        return Response(status=status.HTTP_200_OK)
Beispiel #6
0
def login_user(request):
    if not request.user.is_authenticated():
        if 'user_id' in request.session:
            del request.session['user_id']
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
            mobile = request.POST['mobile']
            user = authenticate(username=username,password=password)
            if user is not None:
                if user.is_active:
                    otp = randint(100000,999999)
                    message = 'OTP for the App is '+str(otp)
                    send_sms(mobile,message)
                    otp_obj = OtpData()
                    otp_obj.mobile = mobile
                    otp_obj.otp = otp
                    otp_obj.flag = False
                    otp_obj.save()
                    #login(request,user)
                    request.session['user_id'] = user.id
                    request.session['otp_id'] = otp_obj.id
                    return render(request,'login/Otp_verify.html')
                else:
                    return render(request,'login/login_admin.html',{'error_message':'Your account has been disabled'})
            else:
                return render(request,'login/login_admin.html',{'error_message':'Invalid Username or Password. Login Again'})
        else:
            return render(request,'login/login_admin.html')
    else:
        return redirect('/firm/firm_login')
Beispiel #7
0
def send_message(li):
    body = ''
    for i in li:
        body += ('- ' + totext(i) + '\n')
    text = 'SAKAI作业如下:\n%s 一共%d个' % (body, len(li))
    sms.send_sms(16267318573, text)
    print('已发送短信到 16267318573 \n %s' % text)
Beispiel #8
0
def notify_phones_of_trigger():
    phones = prefs.get_phones()
    if len(phones) == 0:
        return
    body = 'The feeder has been triggered!'
    for num in phones:
        sms.send_sms(num, body)
    return
Beispiel #9
0
def send_notification(notif_type, username, usercontacts):
    if notif_type == 'email' and usercontacts.get('email'):
        _email = usercontacts.get('email')
        send_email(_email, '___MSG___')
    elif notif_type == 'phone' and usercontacts.get('mobile'):
        call_user(usercontacts.get('mobile'), '___MSG___')
    elif notif_type == 'sms' and usercontacts.get('mobile'):
        send_sms(usercontacts.get('mobile'), '__MSG__')
def offer_done(request):

    """Deletes the passed offer. Requires the offer id to be passed."""

    db.db_remove('offers', {'_id': ObjectId(request.form.getlist("id")[0])}, True)
    message = request.form.getlist("id")[0]+" has been claimed"
    sms.send_sms(db.phone_number, message)
    return "did it"
Beispiel #11
0
 def test_send_sms(self) -> None:
     """
     Test send_sms with the recipients specified as a string to remain
     compatibility with django-sms<=0.0.4.
     """
     send_sms('Content', '0600000000', '0600000000')
     self.assertEqual(len(sms.outbox), 1)  # type: ignore
     self.assertIsInstance(sms.outbox[0].recipients, list)  # type: ignore
Beispiel #12
0
def call(number):
    """@number wishes to share the number with the other person."""
    if not r.exists(number):
        return build_sms("Error: You haven't connected to anyone yet.")
    peer_number = r.get(number)
    send_sms(peer_number,
             "The other person has shared their number: %s" % (number))
    return ""
Beispiel #13
0
    def book(self, appointment, current_visits, worst_current_visit):
        appointment['element'].find_element_by_xpath(
            "//button[text()=' Umów ']").click()

        if len(current_visits) == 1:
            wait = WebDriverWait(self.driver, 15)
            wait.until(
                ec.visibility_of_element_located(
                    (By.XPATH,
                     "//*[text()='Umów nową wizytę lub zmień termin']")))
            self.driver.find_element_by_xpath(
                "//*[text()='Umów nową wizytę']").click()

        elif len(current_visits) == 2:
            wait = WebDriverWait(self.driver, 15)
            wait.until(
                ec.visibility_of_element_located(
                    (By.XPATH, "//*[text()='Zmień termin wizyty']")))
            available_visits = self.driver.find_elements_by_css_selector(
                'div.appointments.ng-scope div.row')
            for available_visit in available_visits:
                apo_date = available_visit.find_element_by_css_selector(
                    'div.date.ng-scope').text.strip().replace('/', '-')
                apo_time = available_visit.find_element_by_css_selector(
                    'div.time.ng-binding').text.strip()
                apo_special = available_visit.find_element_by_css_selector(
                    'div.specialty.ng_binding').text.strip()
                if apo_date == worst_current_visit[
                        'date'] and apo_time == worst_current_visit[
                            'hour'] and apo_special == worst_current_visit[
                                'specialty']:
                    available_visit.find_element_by_css_selector(
                        'i.fa.fa-square-o').click()
                    self.driver.find_element_by_xpath(
                        "//button[text()='Potwierdź zmianę wizyty']").click()

        wait = WebDriverWait(self.driver, 15)
        wait.until(
            ec.visibility_of_element_located(
                (By.XPATH, "//*[text()='Potwierdź wizytę']")))
        apo_time = self.driver.find_element_by_css_selector(
            "div.visit-date").text
        specialization = self.driver.find_element_by_id(
            'FormModel_SpecializationName').get_attribute('value')
        doc_name = self.driver.find_element_by_id(
            'FormModel_DoctorName').get_attribute('value')
        clinic = self.driver.find_element_by_id(
            'FormModel_ClinicPublicName').get_attribute('value')
        self.driver.find_element_by_id("bookAppointmentButton").click()

        print(apo_time)
        print(specialization)
        print(doc_name)
        print(clinic)

        send_sms(f'{apo_time} {specialization} {doc_name} {clinic}')

        return
Beispiel #14
0
def help():
    lon = request.args.get("lon")
    lat = request.args.get("lat")
    user_id = request.args.get("uid")
    sms.send_sms(user_id, lat, lon)
    print (str(lon), str(lat), str(user_id))
    seniorSaver.addIncident(self, str(datetime.now()), user_id, lon, lat, datetime.now(), 1)
    print ("DB updated")
    return "Message Sent"
Beispiel #15
0
def disconnect(number):
    """Remove @number from the set of waiting callers."""
    r.srem('waiting', number)
    peer = r.get(number)
    r.delete(number)
    if peer:
        r.delete(peer)
        send_sms(peer, "Your peer disconnected.")
    return build_sms("You've been disconnected and will no longer receive messages.")
Beispiel #16
0
def qr_callback(**kwargs):
    global sms_sent

    if not sms_sent:
        # 发送短信
        send_sms()
        sms_sent = True

    with open(qr_path, 'wb') as fp:
        fp.write(kwargs['qrcode'])
Beispiel #17
0
def test_locmem_backend():
    """
    test local memory backend

    """
    sms.send_sms('my text message', 'me', 'you', backend='sms.backends.locmem.SMSBackend')
    assert len(sms.outbox) == 1
    assert sms.outbox[0]['text'] == 'my text message'
    assert sms.outbox[0]['from'] == 'me'
    assert sms.outbox[0]['to'] == 'you'
def message_send(request):
    message_stuff = request.form  #.getlist('l')[0]
    message = {
        'to': message_stuff.getlist('to'),
        'from': message_stuff.getlist('from'),
        'content': message_stuff.getlist('content')
    }
    db.db_insert("messages", message)
    sms.send_sms("123456", message_stuff.getlist('content'))
    return "Message Sent"
Beispiel #19
0
def disconnect(number):
    """Remove @number from the set of waiting callers."""
    r.srem('waiting', number)
    peer = r.get(number)
    r.delete(number)
    if peer:
        r.delete(peer)
        send_sms(peer, "Your peer disconnected.")
    return build_sms(
        "You've been disconnected and will no longer receive messages.")
Beispiel #20
0
def the_job(item):
    try:
        logger.info('Running job')
        send_sms(Config.USER_PHONE_NUMBER, 'Did you remember to turn off the {}'.format(item))
        logger.info('Sent sms')
        schedule_the_job(item)
        logger.info('Scheduled job to run again')
    except:
        logger.exception('Exception occurred')
        raise
Beispiel #21
0
def message_send(request):
    message_stuff = request.form#.getlist('l')[0]
    message = {
        'to':  message_stuff.getlist('to'),
        'from': message_stuff.getlist('from'),
        'content': message_stuff.getlist('content')
    }
    db.db_insert("messages",message)
    sms.send_sms("123456", message_stuff.getlist('content'))
    return "Message Sent"
Beispiel #22
0
def the_job(item):
    try:
        logger.info('Running job')
        send_sms(Config.USER_PHONE_NUMBER,
                 'Did you remember to turn off the {}'.format(item))
        logger.info('Sent sms')
        schedule_the_job(item)
        logger.info('Scheduled job to run again')
    except:
        logger.exception('Exception occurred')
        raise
Beispiel #23
0
    def process_newest_weibo():
        """
        设置定时器: 每隔一段时间调用自身
        获取新微博: 先爬取 person 的最新一条微博, 若其已存在与数据库中, 则等待下次执行.
                                             若不存在, 则分析其情绪值, 并存入数据库中, 同时更新数据库中的统计数据
        分析情绪值: 若情绪正常, 则等待, 否则, 发送短信
        """

        # 获取新微博
        new_weibo = spider.get_newest_weibo()
        query = Weibo.select().where(
            Weibo.weibo_content == new_weibo["weibo_content"])
        print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        # 对新发出的微博进行处理
        if not query.exists():
            print('======发现新微博======')
            analyser = Analyser(user_id)
            sentiment_value = analyser.get_sentiment_value(
                new_weibo["weibo_content"])
            # 数据库操作
            db = DB()
            db.person = person
            weibo = db.store_weibo(**new_weibo)
            db.store_sentiment(weibo, sentiment_value)
            analyser.calculate()
            # 更新数据库后, 均值和方差变了, 需要再次更新
            MEAN = Person.get(Person.user_id == user_id).mean
            SD = Person.get(Person.user_id == user_id).std
            if sentiment_value not in range(MEAN - SD // 2, MEAN + SD // 2):
                message = '[{person_name}]发了一条[情绪值]为 {sentiment_value} 的微博, 内容为: {content}'.format(
                    person_name=person.username,
                    sentiment_value=sentiment_value,
                    content=new_weibo['weibo_content'],
                )
                print(message)
                print('============')
                # 发送短信
                send_sms(message)
        else:
            # 更新点赞数 转发数 和 评论数
            weibo = query[0]
            if (weibo.up_num != new_weibo['up_num']
                    or weibo.retweet_num != new_weibo['retweet_num']
                    or weibo.comment_num != new_weibo['comment_num']):
                print('微博状态发生变化, 正在更新数据库...')
                db = DB()
                db.person = person
                weibo.up_num = new_weibo['up_num']
                weibo.retweet_num = new_weibo['retweet_num']
                weibo.comment_num = new_weibo['comment_num']
                weibo.save()
                print('数据库更新完毕')

            print('======无新微博, 当前输出的是最后一条微博======')
Beispiel #24
0
def test_console_backend():
    """
    test local memory backend

    """
    capture = Capture()
    capture.begin()

    sms.send_sms('my text message', 'me', 'you', backend='sms.backends.console.SMSBackend')
    assert capture.buffer ==  'youmemy text message'

    capture.finalize(capture.buffer)
Beispiel #25
0
    def test_sms_send(self):
        sms.send_sms(tpl_id='416085',
                     content="#code#=1234&#timeout#=3",
                     recipient_list=['13311102999'])
        self.assertEquals(sms.outbox[0].message(),"#code#=1234&#timeout#=3")

        sms.send_sms(tpl_id='416085',
                     content="#code#=1234&#timeout#=3",
                     recipient_list=['13311109999','18612589999'])
        self.assertEquals(sms.outbox[0].message(),"#code#=1234&#timeout#=3")
        rl = []
        for i in range(1,102):
            rl.append('13311109999')
        self.assertRaises(AssertionError,sms.send_sms,tpl_id='416085',content='#code#=1234&#timeout#=3',recipient_list=rl)
Beispiel #26
0
def search_bug():
    url = 'http://www.goradar.cn/portal.php?mod=list&catid=4'
    r = s.get(url)
    source = soup.select('dl.bbda.cl')
    for i in source:
        title = i.dt.text
        if 'BUG' or 'bug' in title:
            date = source[0].span.text.strip().split(' ')[0]
            agency = source[0].span.text.strip().split(' ')[1]
            today = datetime.now(timezone('Asia/Shanghai')).strftime('%y-%m-%d')
            if date == today:
                text = '旅行雷达找到BUG\r%s\r%s' % (title, agency)
                print(text)
                sms.send_sms(16267318573, text)
def main():
	print("Loaded")

	sleep(0.5)
	system("clear")

	print("Face Recognition - Ready")
	display_msg("Face Recognition     Ready")

	while True:
		# If motion is detected run main authentication loop.
		if pir.motion_detected:
			system("clear")

			# Run authentication.
			auth = authenticate()

			date = "\rDate: " + utc + "\n"
			msg = None
			grant = "ACCESS GRANTED"
			deny = "ACCESS DENIED"

			if auth == "auth_err":
				print(deny)
				display_msg(deny)
				msg = date + "AUTHENTICATION ERROR\nNo known images to compare to. Access will be denied to all. Add known images to gain access."
			elif auth == "no_enc":
				print(deny)
				print("No Face Detected")
				display_msg(deny + "   No Face Detected")
			elif auth:
				print(grant)
				print("Welcome, " + name)
				display_msg(grant + "  Welcome, " + name)
				msg = date + name + " - Authenticated"
			else:
				print(deny)
				display_msg(deny)
				msg = date + "User Denied Access."

			# Send SMS with message.
			if msg:
				send_sms(text=msg)

			sleep(5)

			system("clear")

			print("Face Recognition - Ready")
			display_msg("Face Recognition     Ready")
def check_online(prev_status, current_status):
    prev_status = current_status
    user_data = session.method('users.get', {
        'user_ids': VK_USER_ID,
        'fields': 'online'
    })
    current_status = user_data[0].get('online')
    if not prev_status and current_status:
        sms.send_sms('{} {} онлайн'.format(user_data[0].get('first_name'),
                                           user_data[0].get('last_name')))
    if prev_status and not current_status:
        sms.send_sms('{} {} оффлайн'.format(user_data[0].get('first_name'),
                                            user_data[0].get('last_name')))
    return [prev_status, current_status]
Beispiel #29
0
def minder():
    data = json.loads(request.data)
    logger.info(data)

    try:
        launch, toggle, item, question = _parse_request(data['request'])
        if launch:
            speech_output = 'welcome to minder! what can i do for you today?'
            card_output = 'user launched minder'
            reprompt_message = 'what can i do for you today?'
            response = _get_echo_response(speech_output,
                                          card_output,
                                          reprompt_message,
                                          end_session=False)
        else:
            if question:
                saved_toggle = get_item(item)
                if not saved_toggle:
                    saved_toggle = 'off'
                speech_output = 'hello, the {} is {}'.format(
                    item, saved_toggle)
                card_output = 'user asked if {} is {}. we responded with {}'.format(
                    item, saved_toggle, speech_output)
                reprompt_message = ''
            else:
                speech_output = 'you\'ve turned {} the {}'.format(toggle, item)
                card_output = 'user turned {} the {}'.format(toggle, item)
                reprompt_message = ''

                if toggle == 'on':
                    schedule_the_job(item)

                if toggle == 'off':
                    logger.info('Attempting to cancel job')
                    cancel_the_job()

                set_item(item, toggle)
                send_sms(Config.PROVIDER_PHONE_NUMBER, card_output)

            response = _get_echo_response(speech_output, card_output,
                                          reprompt_message)
    except Exception as e:
        logger.error(e)
        speech_output = 'sorry, i didn\'t understand that. please try again'
        card_output = 'couldn\'t understand command from user'
        reprompt_message = 'reprompt message. how does this work?'
        response = _get_echo_response(speech_output, card_output,
                                      reprompt_message)

    return jsonify(response)
Beispiel #30
0
def get_balance():
    html = se.content
    soup = BeautifulSoup(html, "html.parser")
    #source = soup.select('div.AccountActivityPanel')
    source = soup.select('li.show-quick-view')
    deposit_balance = source[0].select('span.balanceValue')[0].text
    cridit_avaliable = source[1].select('strong.TL_NPI_L1')[0].text
    minimum_payment = source[1].select('strong.TL_NPI_L1')[6].text
    text = '''Bank of America\r
支票账户余额:%s\r
信用卡剩余额度:%s\r
最低账单付款:%s\r
    ''' % (deposit_balance, cridit_avaliable, minimum_payment)
    print(text)
    sms.send_sms(16267318573, text)
Beispiel #31
0
def linkup():
    """Links up two random people from the waiting list."""
    num_waiting = r.scard('waiting')
    if num_waiting < 2:
        # Cannot link up
        return False
    num1 = r.spop('waiting')
    num2 = r.spop('waiting')
    # our routing table
    r.set(num1, num2)
    r.set(num2, num1)
    text = "You're now connected to a random stranger!"
    send_sms(num1, text)
    send_sms(num2, text)
    return True
Beispiel #32
0
def ethereum_price_check():
    global ethereum_critical_price_notified
    while True:
        time.sleep(8)
        last_price = float(cryptowat_puller.ethereum_market_price_data['last'])
        if last_price < 100 and (not ethereum_critical_price_notified):
            sms.send_sms(
                config.destination_phone_number,
                config.destination_phone_provider, config.gmail_address_login,
                config.gmail_address_pass,
                "WARNING! Ethereum price dropped below $100!\nEthereum Price: $"
                + str(last_price) + "\n")
            ethereum_critical_price_notified = True
        elif last_price >= 100:
            ethereum_critical_price_notified = False
Beispiel #33
0
def num():
    if request.method == "POST":
        n_p = check_np()
        new_user = Number1(np=n_p, number='9016291149')

        db.session.add(new_user)
        db.session.commit()

        mycursor.execute("SELECT * FROM Number1")

        for x, y in mycursor:
            if n_p == x:
                send_sms(y)

        return redirect('/')
Beispiel #34
0
def linkup():
    """Links up two random people from the waiting list."""
    num_waiting = r.scard('waiting')
    if num_waiting < 2:
        # Cannot link up
        return False
    num1 = r.spop('waiting')
    num2 = r.spop('waiting')
    # our routing table
    r.set(num1, num2)
    r.set(num2, num1)
    text = "You're now connected to a random stranger!"
    send_sms(num1, text)
    send_sms(num2, text)
    return True
def send_mass_sms_task(actor_pk, message, to_list, unsuccessful_sms_pk=None, sender='GGSIPU', template_name='basic', *VAR):
	# To send custom message, pass template_name=''
	# Send VAR args as string.
# # # # #
	report = None
	if VAR:
		try:
			VAR = [str(i) for i in VAR]
		except:
			VAR = []
# # # # #
	for tries in range(MAX_RETRIES):
		report = send_sms(to_list, message, sender, template_name, *VAR)
		if not report:
			if tries == MAX_RETRIES-1:
				if unsuccessful_sms_pk:
					try:
						unsuccessful_sms = UnsuccessfulSMS.objects.get(pk=unsuccessful_sms_pk)
						unsuccessful_sms.save()
					except:
						UnsuccessfulSMS.objects.create(message=message, phone_numbers=','.join(set(to_list)), template_name=template_name, sender=sender, template_vars=(','.join(VAR)))
#			Continue with the loop
		else:
			try:
				SMSDeliveryReport.objects.create(actor=CustomUser.objects.get(actor_pk), message=message, recipients=','.join(set(to_list)), status=report['Status'], session_id=report['Details'])
			except:
				pass
			# It was a success. Atleast, the request was sent to the API. Not concerned with the Status of session_id.
			# That is a concern of callback url.
			if unsuccessful_sms_pk:
				try:
					unsuccessful_sms = UnsuccessfulSMS.objects.get(pk=unsuccessful_sms_pk).delete()
				except:
					pass
			break
Beispiel #36
0
 def _alarm_parse(self, alarms, mailto,
                 subject, sms_to):
     if len(alarms) == 0:
         raise Return(0)
     content = {}
     for node_name in alarms:
         alarm = alarms[node_name]
         content, serious, general = {}, [], []
         if alarm['serious']:
             content['serious'] = alarm['serious']
         if alarm['general']:
             content['general'] = alarm['general']
         if content:
             _subject = '%s_%s' %(node_name, subject)
             status = yield thread_pool.submit(
                         MailEgine.send_exception_email,
                         options.mailfrom, mailto, _subject,
                         json.dumps(content))
             if status:
                 if content.has_key('general'):
                     del content['general']
                 if content.has_key('serious') and \
                      content['serious'].has_key('warn_method') and \
                      content['serious']['warn_method'] == 'tel:sms:email':
                     del content['serious']['warn_method']
                     yield send_sms(sms_to, json.dumps(content))
                     yield send_sms_and_phone(sms_to, '%s,%s' %('serious', node_name))
def main():
	con=sqlite3.connect('birthday.db',timeout=1)
	query="select * from birthdays where valid=1 and  strftime('%m-%d', dob)=strftime('%m-%d', date()) "
	data =con.execute(query)
	for row in data:
		print row

		try:
			msg="Happy Birthday D"
			if row[5]=="Male":
				msg+="a"
			sms.send_sms(msg,str(row[4]))
			w10.notify("Boss Today is Birthday of {} I've send your greetings".format(row[1]))
		except Exception, e:
			print e
			w10.notify("Boss Today is Birthday of {} I've failed to send your greetings Sorry :(".format(row[1]))
Beispiel #38
0
def putrequests(id):
    if request.method == 'PUT':
        print(request.data)
        if not request.json:
            abort(400)
        print(request.json)
        data = request.json
        db = dbclient.createdb('request')
        doc = dbclient.getres(db, id)
        print(doc)
        doc['status'] = "IN PROGRESS"
        dbclient.updateres(doc)

        sms.send_sms(doc['number'],
                     "Your request has been update with: " + data['comment'])
        #translate
        return "SUCCESS"
def _sms_send(self, cr, uid, data, context):
    service = netsvc.LocalService("object_proxy")

    account = service.execute(cr.dbname, uid, 'smshelper.account', 'read', data['form']['account_id'])
    template = service.execute(cr.dbname, uid, 'smshelper.message_template', 'read', data['form']['template_id'])
    text = template['content']

    res_ids = service.execute(cr.dbname, uid, 'res.partner.address', 'search', [('partner_id','in',data['ids'])])
    res = service.execute(cr.dbname, uid, 'res.partner.address', 'read', res_ids, ['mobile'])

    nbr = 0
    for r in res:
        to = r['mobile']
        if to:
            sms.send_sms(account['username'], account['password'], to, text)
            nbr += 1
    return {'sms_sent': nbr}
Beispiel #40
0
def send_email():
    html = Template(Path('Template/index.html').read_text())
    email = EmailMessage()
    email['from'] = 'Ayush'
    email['to'] = '*****@gmail.com'
    email['subject'] = 'Python'

    email.set_content(html.substitute({'name': 'Ayush'}), 'html')

    with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp:
        smtp.ehlo()
        smtp.starttls()
        smtp.login('email id', 'password')
        smtp.send_message(email)
        print('sent mail')
        send_sms()
        print('sent sms')
Beispiel #41
0
    def test_sms_send(self):
        sms.send_sms(tpl_id='416085',
                     content="#code#=1234&#timeout#=3",
                     recipient_list=['13311102999'])
        self.assertEquals(sms.outbox[0].message(), "#code#=1234&#timeout#=3")

        sms.send_sms(tpl_id='416085',
                     content="#code#=1234&#timeout#=3",
                     recipient_list=['13311109999', '18612589999'])
        self.assertEquals(sms.outbox[0].message(), "#code#=1234&#timeout#=3")
        rl = []
        for i in range(1, 102):
            rl.append('13311109999')
        self.assertRaises(AssertionError,
                          sms.send_sms,
                          tpl_id='416085',
                          content='#code#=1234&#timeout#=3',
                          recipient_list=rl)
Beispiel #42
0
def endTaskGetComment(username, value):
    try:
        task = HelpTask.objects.get(helper__username=username, status=1)
        phone = task.helpee.phone
        task.status = 2  # set status to waiting for comment
        task.help_price = value
        task.save()
        sms.send_sms(phone,
                     u"به سوالات زیر با اعداد بین ۱-۴ به "
                     u"صورت یک عدد پنج رقمی پاسخ دهید\n"
                     u"۱-دانش کافی امدادگر?\n"
                     u"۲-رسیدن به موقع?\n"
                     u"۳-نحوه برخورد امدادگر?\n"
                     u"۴-لوازم کافی امدادگر?\n"
                     u"۵-دیگر موارد\n")
        return True
    except HelpTask.DoesNotExist:
        return False
Beispiel #43
0
def minder():
    data = json.loads(request.data)
    logger.info(data)

    try:
        launch, toggle, item, question = _parse_request(data['request'])
        if launch:
            speech_output = 'welcome to minder! what can i do for you today?'
            card_output = 'user launched minder'
            reprompt_message = 'what can i do for you today?'
            response = _get_echo_response(speech_output, card_output, reprompt_message, end_session=False)
        else:
            if question:
                saved_toggle = get_item(item)
                if not saved_toggle:
                    saved_toggle = 'off'
                speech_output = 'hello, the {} is {}'.format(item, saved_toggle)
                card_output = 'user asked if {} is {}. we responded with {}'.format(item, saved_toggle, speech_output)
                reprompt_message = ''
            else:
                speech_output = 'you\'ve turned {} the {}'.format(toggle, item)
                card_output = 'user turned {} the {}'.format(toggle, item)
                reprompt_message = ''

                if toggle == 'on':
                    schedule_the_job(item)

                if toggle == 'off':
                    logger.info('Attempting to cancel job')
                    cancel_the_job()

                set_item(item, toggle)
                send_sms(Config.PROVIDER_PHONE_NUMBER, card_output)

            response = _get_echo_response(speech_output, card_output, reprompt_message)
    except Exception as e:
        logger.error(e)
        speech_output = 'sorry, i didn\'t understand that. please try again'
        card_output = 'couldn\'t understand command from user'
        reprompt_message = 'reprompt message. how does this work?'
        response = _get_echo_response(speech_output, card_output, reprompt_message)

    return jsonify(response)
Beispiel #44
0
def proccess_req(request):
    phone = request.POST['from']
    text = request.POST['text'].strip()
    parts = text.split(",")

    if parts[0] == 'h':  # help task request
        while len(parts) < 7:
            parts.append("")
        result = help_process_start(phone,  # phone
                                    parts[1].strip(), parts[2].strip(),  # lat lng
                                    parts[3].strip(),  # problem
                                    parts[4].strip(),  # machine
                                    parts[5].strip(), parts[6].strip(),  # name family
                                    parts[7].strip())  # desc
        if result == 1:
            sms.send_sms(phone, u"عملیات امداد با موفقیت شروع شد")
        else:
            sms.send_sms(phone, u"امدادگر مناسبی برای شما یافت نشد")
    if parts[0].isdigit():
        doCommentDoingThings(parts[0], phone)
    return HttpResponse("OK")
Beispiel #45
0
def doCommentDoingThings(ans, phone):
    try:
        comment = UserComment()
        task = HelpTask.objects.get(helpee__phone=phone, status=2)

        comment.coming_on_time = int(ans[1])
        comment.nahve_barkhord = int(ans[2])
        comment.lavazem_kafi = int(ans[3])
        comment.danesh_kafi = int(ans[0])
        comment.other_rate = int(ans[4])

        sms.send_sms(phone, u"دیدگاه شما با موفقیت ثبت شد. با تشکر از شما")
        comment.save()
        task.user_comment = comment
        task.status = 3  # set status to help finished
        task.save()
    except HelpTask.DoesNotExist:
        pass
    except ValueError:
        sms.send_sms(phone,
                     "پیغام ارسالی از جانب شما نادرست بود!")
Beispiel #46
0
def submit():
	print HIGHLIGHT_COLOR + "RECEIVED: " + HIGHLIGHT_END + str(request.values)

	u = begin_session(request.values, no_session=True)
	if not u:
		dbgErr('request', request)
		return "Error: provide sessionId"

	if 'Body' in request.values:
		pole_number  = request.values['Body']
		if not sms.verify_pole_number(pole_number):
			dbgInfo('pole number is in wrong format. Continuing to From attr check and generic response')
		else:
			if 'Address' in request.values:
				dbgInfo('Got polenum and address')
				print u.add_history(pole_number, request.values['Address'])
				resp = "last history: " + u.get_last_history()
			else:	# use fake address
				dbgInfo('Got polenum and generated fake address')
				print u.add_history(pole_number, history.newaddr())
				resp = "last history: " + u.get_last_history()
			dbgInfo('added history. ALL history up to now', u.get_all_history())
			if 'Test' in request.values and request.values['Test'] == 'True':
				dbgInfo("Got polenum. Return JSON because of 'Test' param. last history", u.get_last_history())
				return u.get_last_history()

	if not 'From' in request.values:
		dbgWarn("no 'From' key in request. Not SMS - Not Replying")
		return render_args(request.values) + "<br>WARN: Not an SMS. Not replying"
	
	# SEND SMS
	dbgInfo("FROM DETECTED. WILL TRY TO RESPOND", request.values)
	rcpt = request.values['From']
	resp += "<hr>RECIPIENT: " + rcpt + "<br>"
	dbgInfo('FROM', rcpt)
	resp += "<h3>Twilio Response:</h3>"
	
	dbgInfo("send_sms() retval", sms.send_sms())
	return resp
Beispiel #47
0
def send_message(number, message):
    send_sms('+1 {}'.format(number), message)
    return 'success'
Beispiel #48
0
def send_query_by_sms(query):
    text = query.text + ' Please reply "' + query.name + ': value"'
    send_sms(query.user.phone, text)

    ActionLog.log("SentSMS")
Beispiel #49
0
def send_game_sms(player,game,message):
	message = message + "\n" + make_game_link(game.short,player.phone)
	send_sms(player.phone,message)
Beispiel #50
0
def timer_tick():
  phone_numbers, msg = send_pulse()
  send_sms(phone_numbers, msg)
  return "To %s %s" % (phone_numbers, msg)
Beispiel #51
0
def activate(set_label, set_message, get_con, b, num, tty, sens):
	
	w = 15
	sen = 180
	try:
		w = int(b)
	except:		
			print "error"
	try:
		sen = 300 - int(sens)
	except:		
			print "error"
	tp_num = num
	
	set_label("waiting")
	for i in range(0,w):
		time.sleep(1)
		set_label(str(w - i))
		
	set_label("Disactivate")
	camshot2 = get_image()
	camshot_old = get_image()
	cnt = 0
	cnt2 = 0
	f = 0
	while 1:
		
		s = get_con()
		if s:
			break
		min_x = 5
		min_y = 3	
		max_x = 0
		max_y = 0
		try:
			camshot2 = get_image()
			camshot = camshot2 

			pix2 = camshot.load();
			pix_old = camshot_old.load();
		except:
			continue
		width, height = camshot2.size
		i = 0
		l = [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]]
		
		for p in range(4):
			for q in range(6):
				l[p][q] = check(pix2, pix_old, q*width/6, (q + 1)*width/6, p*height/4, (p + 1)*height/4)
		for y in range(0,4):
			for x in range(0,6):
				if l[y][x] > sen:
					if min_x > x:
						min_x = x
					if min_y > y:
						min_y = y
					if max_x < x:
						max_x = x
					if max_y < y:
						max_y = y

		w1 = (width/6)*min_x
		w2 = (width/6)*(max_x + 1)
		h1 = (height/4)*min_y
		h2 = (height/4)*(max_y + 1)
		
		if (h2 - h1 >= height /4 or w2 - w1 >= width/4):
			f = 1
			cnt = cnt + 1
			if cnt == 1:
				tmp = camshot
			if cnt > 1:
				save_images(tmp, camshot)
				set_message("motion detected!!!")
				cnt = 0
				cnt2 = 0
				f = 0
				sms.send_sms(num, tty)
				time.sleep(5)
				set_message("---------------------")
		if f:
			cnt2 = cnt2 + 1 
			if cnt2 >= 10 and cnt < 2:
				f = False
				cnt = 0
				cnt2 = 0
		try:		
			camshot_old = camshot2
		except:
			continue	
		time.sleep(0.1)