def lambda_handler(event, context):
    utils.log_lambda(event, context)

    body, bucket, _ = utils.read_s3_from_event(event)

    message = body['Body']
    cmd, ticker, count = re.split('\W+', message)

    stock_info = get_info(ticker)
    symbol = stock_info['Symbol']
    current_price = stock_info['LastPrice']

    recipient = body['From']

    portfolio_key = 'portfolio/{}.json'.format(recipient)
    try:
        portfolio = utils.read_s3(bucket, portfolio_key)
        current_portfolio = defaultdict(list, portfolio)
    except:
        current_portfolio = defaultdict(list)

    current_portfolio[symbol].append({'count': count, 'price': current_price})

    config.S3_CLIENT.put_object(Bucket=bucket, Key=portfolio_key, Body=json.dumps(current_portfolio))

    total_shares = sum(int(d['count']) for d in current_portfolio[symbol])

    sender = body['To']
    message = 'You purchased {} shares of {} @ ${}. You have a total of {} shares.'.format(count, symbol, current_price, total_shares)
    utils.send_sms(message, sender, recipient, bucket)
Beispiel #2
0
def transcribe_inbound(ws):
    print("WS connection opened")
    print("Connection accepted")
    # instancie speech_Bridge
    bridge = SpeechBridge(streaming_config)
    print("transcoder instanciation done")
    while not ws.closed:
        message = ws.receive()
        if message is None:
            bridge.shutdown()
            print("message is None")
            break
        data = json.loads(message)
        if data["event"] == "start":
            print(f"Media WS: Received event '{data['event']}': {message}")
            continue
        if data["event"] == "media":
            media = data["media"]
            chunk = base64.b64decode(media["payload"])
            bridge.fill_buffer(chunk)
        if data["event"] == "stop":
            print(f"Media WS: Received event 'stop': {message}")
            bridge.shutdown()
            time.sleep(15)
            break

    print("send SMS")
    print(bridge.transcript)
    send_sms(bridge.transcript, os.environ["MY_NUMBER"])
    print("Stopping...")
def lambda_handler(event, context):
    utils.log_lambda(event, context)

    body, bucket, _ = utils.read_s3_from_event(event)

    message = body['Body']
    stocks = re.split(r'\W+', message)

    for stock in stocks:
        if stock == 'overview':
            continue

        stock_info = {}
        try:
            stock_info = stock_api.get_info(stock)
            message = format_ticker_message(stock_info)
        except Exception as e:
            logger.exception('Could not get stock ticker info')
            message = str(e)

        recipient = body['From']
        sender = body['To']

        utils.send_sms(message, sender, recipient, bucket)

        if stock_info:
            key = 'parsed-overview/{}-{}-{}'.format(recipient, stock_info['Symbol'], body['MessageSid'])
            config.S3_CLIENT.put_object(Bucket=bucket, Key=key, Body=json.dumps(body))
Beispiel #4
0
def handle_incident():
    firststep=request.get_json()
    print(firststep)
    print(firststep["email"])
    secondstep=User.query.filter(User.email==firststep["email"]).first()
    thridstep=Service.query.filter(Service.servicetype_name==firststep["servicetype_name"]).first()
    fourthstep=Incident(user_id=secondstep.user_id,servicetype_id=thridstep.servicetype_id,latitude=firststep["latitude"],longitude=firststep["longitude"])
    db.session.add(fourthstep)
    db.session.commit()
# getting a User's zipcode by using latitude & longitude
    responsepostal = requests.get("https://maps.googleapis.com/maps/api/geocode/json",params={'latlng':firststep["latitude"]+','+firststep["longitude"],'key':'AIzaSyDnPdnUPzUc0NaVzp4hS6Y_dhPSE8rvK1s'})
    response1=responsepostal.json()
    list1=response1["results"][0]["address_components"]
    postal_code = None
    for obj in list1:
        if obj["types"][0]=="postal_code":
            postal_code = obj["long_name"]
    print(postal_code)
    if postal_code is not None:
        # its time to send the sms to everyone at this postal code
        heros_nearby = Hero.query.filter(Hero.zip_code==postal_code).all()
        for _hero in heros_nearby:
            print(_hero)
            send_sms("Hello "+_hero.first_name+", someone needs your help! please reply with "+str(fourthstep.incident_id)+" if you are willing to help", _hero.phone)   
        return "success"   
Beispiel #5
0
def get_auth_code(request, phone):
    dajax = Dajax()
    if Account.objects.filter(phone=phone).exists():
        dajax.add_data({ 'ret_code' : 1000, 'ret_msg' : u'该手机号码已绑定到其他账号,请使用一个新的手机号码!'}, 'get_auth_code_callback')
    else:
        auth_code = str(random.randint(100000, 1000000))
        send_sms(phone, u"验证码是%s,15分钟内有效" % auth_code)
        cache.set('auth_code_%s' % phone, auth_code, AUTH_CODE_TIMEOUT)
        dajax.add_data({ 'ret_code' : 0, 'ret_msg' : u'已将验证码发送到您的手机,请注意查收。'}, 'get_auth_code_callback')
    return dajax.json()
def lambda_handler(event, context):
    utils.log_lambda(event, context)

    body, bucket, _ = utils.read_s3_from_event(event)

    recipient = body['From']
    sender = body['To']

    message = 'Thanks for using hotstockbling. Enter a ticker symbol or use HELPME, DETAILS, BUY, or SELL.'
    utils.send_sms(message, sender, recipient, bucket)
Beispiel #7
0
def create_todo(user_id):
    data = request.get_json()
    print(user_id)
    new_todo = Todo(text=data["text"], complete=False, user_id=user_id, dueDate=data["dueDate"], createdDate=data["createdDate"])
    db.session.add(new_todo)
    db.session.commit()
    user = User.query.filter_by(id=user_id).first()
    send_sms("New task added! " + data["text"] + " " + data["dueDate"], user.phone)

    return jsonify({"message" : "Todo created!"})
Beispiel #8
0
def create_user():
    data = request.get_json()
    password=data["password"]
    hashed_password = generate_password_hash(password, method="sha256")
    new_user = User(public_id=str(uuid.uuid4()), name=data["name"], last=data["last"], password=hashed_password, email=data["email"], phone=data["phone"], todos=data["todos"], admin=True)
    db.session.add(new_user)
    db.session.commit()

    send_sms("Welcome! " + data["name"],data["phone"])

    return jsonify({"message":"New User Created!"})
Beispiel #9
0
def login():
    if current_user.is_authenticated and request.args.get('force') != "true":
        return redirect(url_for('home'))
    if request.method == 'POST':
        code = random_code()
        phone_number = request.form['phone_number']
        send_sms(
            phone_number=phone_number,
            message=f'Here is your super duper secret code: {code}')
        code_to_phone_number[code] = phone_number
        return redirect(url_for('code', phone_number=phone_number))
    return render_template('auth.html', action=url_for('login'), name='phone_number')
Beispiel #10
0
def inbound_phone():
    phone = utils.format_phone(flask.request.form)
    user = models.User.query.filter_by(phone=phone).one()
    if utils.unsubscribe_test(flask.request.form['Body']):
        user.phone_confirmed_at = None
        message = 'You will no longer receive messages from Love Touches'
        utils.send_sms(phone, message)
    else:
        message = models.Message(message=flask.request.form['Body'])
        user.messages.append(message)
    models.db.session.add(user)
    models.db.session.commit()
    return flask.jsonify({'status': 'ok'})
Beispiel #11
0
 def result_order(self):
     self.push(f'Заказ номер {self.order.order_id}.')
     if self.order.order_status:
         self.push(f'Статус заказа: {self.order.order_status}.')
     if self.order.track_no:
         self.push(
             'На ваш номер сейчас придет сообщение с трэк-номером для отслеживания.'
         )
         send_sms(f'Трек-номер для отслеживания {self.order.track_no}.')
     self.push(
         f'Способ доставки: {clear_html(self.order.shipping_method)}.')
     self.order_id = None
     self.say_and_listen(self.user.firstname, 'after_success')
     self.request()
Beispiel #12
0
def save_noshow(user, mobile):
    client = utils.user_to_client(user)
    record = Record.objects.get(user=user,
                                mobile=mobile,
                                waiting=True,
                                take_away=False,
                                directly_seated=False)
    record.conversion = False
    record.waiting = False
    record.seated = False
    record.no_show = True
    record.save(update_fields=['conversion', 'waiting', 'seated', 'no_show'])
    message = "We're sorry to infrom that you have been removed from the Que at %s. If any issues contact %s" % (
        client.rest_name, client.mobile)
    send_sms(mobile, message)
Beispiel #13
0
def save_takeaway(user, mobile, date):
    print "save_takeaway"
    guest = Guest.objects.get(mobile=mobile)
    rest_name = table.objects.get(user=user).rest_name
    record = Record(user=user,
                    rest_name=rest_name,
                    date=date,
                    mobile=mobile,
                    age=guest.age,
                    name=guest.name,
                    take_away=True)
    record.save()
    feed_url = '%s/f/%d/%d' % (settings.HOST, record.id, record.feed_match)
    message = "Thank you for visiting %s, your valuable feedback will be appreciated %s" % (
        record.rest_name, feed_url)
    send_sms(mobile, message)
Beispiel #14
0
def save_waiting(user, mobile, waitingtime):
    print "Save_waiting"
    guest = Guest.objects.get(mobile=mobile)
    rest_name = table.objects.get(user=user).rest_name
    record = Record(user=user,
                    rest_name=rest_name,
                    date=time_now(),
                    mobile=mobile,
                    age=guest.age,
                    name=guest.name)
    record.save()
    pr = PersonalRecord(guest=guest, restuarant=rest_name, date=time_now())
    pr.save()
    message = "Hello, Welcome to %s, your estimated waiting time is %s mins. You will be informed when your table is ready." % (
        rest_name, str(waitingtime))
    send_sms(mobile, message)
Beispiel #15
0
 def checkState1(self, value, info):
     if value['sendNum'] > 5:
         text = u"今天已经给你发送太多的短信了,明天再来吧"
         StateMachine.end(info.user)
     elif self.checkPhoneNum(info.text):
         try:
             user = WeixinUser.objects.get(phone=info.text)
             text = "这个手机号已经被使用了,请使用其他号码"
         except:
             user = None
         if user == None:
             verifyCode = str(random.randint(100000, 1000000))
             ret = send_sms(info.text, u"验证码是%s,15分钟内有效" % verifyCode)
             logger.debug("send sms return %s" % ret)
             value = {
                 'state': 2,
                 'phone': info.text,
                 'verifyCode': verifyCode,
                 "sendTime": time.time(),
                 'sendNum': value['sendNum'] + 1
             }
             self.store(info.user, value)
             text = u'我们已经将验证码发送到%s,请将收到的验证码发送给我们就完成验证,如果2分钟内没有收到短信就请输入“重新发送”,我们将重新给你发送新的验证码,如果想换手机号,就请输入“换手机号”' % info.text
     else:
         text = u"请输入正确的手机号"
     return text
Beispiel #16
0
def filter_articles(articles_scraped, articles_query):
    id = articles_query[0]['id']

    for article in articles_scraped:
        if article['title'] not in map(itemgetter('title'), articles_query):

            id += 1
            title = article['title']
            author = article['author']
            date = article['date']

            add_article = Article(id=id, title=title, author=author, date=date)

            session.add(add_article)
            session.commit()

            notification = 'New Article: {}\nBy: {}'.format(title, author)
            send_sms(notification)
Beispiel #17
0
 def POST(self, place):
     i = web.input()
     form = forms.SMSForm(i)
     if not form.validate():
         return render.sms(place, form)
     people = self.get_people(place, i.people)
     count = utils.send_sms(people, i.message)
     flash.add_flash_message("success", "Successfully sent SMS to {} people".format(count))
     return render.sms(place, form)
def run():
    log.info('Start load genres.')

    genre_translate = load()

    NEED_SMS = True
    new_genres = []
    is_first_run = not genre_translate

    log.info(f'Current genres: {len(genre_translate)}')

    for genre in Dump.get_all_genres():
        if genre not in genre_translate:
            log.info(f'Added new genre: {genre!r}')
            genre_translate[genre] = None
            new_genres.append(genre)

    if new_genres:
        text = f"Added genres ({len(new_genres)}): {', '.join(new_genres)}"
        log.info(text)

        # Если это первый запуск, то смс не отправляем
        if not is_first_run:
            if NEED_SMS:
                send_sms(text, log=log)

        log.info('Save genres')

        json.dump(
            genre_translate,
            open(FILE_NAME_GENRE_TRANSLATE, 'w', encoding='utf-8'),
            ensure_ascii=False,
            indent=4
        )

    else:
        log.info('No new genres')

    log.info('Finish!')
Beispiel #19
0
def save_checkout(user, mobile, bill, flag=0):
    print "save_checkout"
    if flag == 0:
        record = Record.objects.get(user=user,
                                    mobile=mobile,
                                    seated=True,
                                    take_away=False)
        record.seated = False
        record.bill = bill
        record.save(update_fields=['seated', 'bill'])
    elif flag == 1:  #Checkout directly seated
        record = Record.objects.get(user=user,
                                    mobile=mobile,
                                    seated=True,
                                    directly_seated=True,
                                    take_away=False)
        record.seated = False
        record.bill = bill
        record.save()
    feed_url = '%s/f/%d/%d' % (settings.HOST, record.id, record.feed_match)
    message = "Thank you for visiting %s, your valuable feedback will be appreciated %s" % (
        record.rest_name, feed_url)
    send_sms(mobile, message)
Beispiel #20
0
 def checkState1(self, value, info):
     if value['sendNum'] > 5:
         text = u"今天已经给你发送太多的短信了,明天再来吧"
         StateMachine.end(info.user)
     elif self.checkPhoneNum(info.text):
         try:
             user = WeixinUser.objects.get(phone=info.text)
             text = "这个手机号已经被使用了,请使用其他号码"
         except:
             user = None
         if user == None:
             verifyCode = str(random.randint(100000, 1000000))
             ret = send_sms(info.text, u"验证码是%s,15分钟内有效" % verifyCode)
             logger.debug("send sms return %s" % ret)
             value = {'state':2, 'phone':info.text, 'verifyCode':verifyCode, "sendTime":time.time(), 'sendNum':value['sendNum'] + 1}
             self.store(info.user, value)
             text = u'我们已经将验证码发送到%s,请将收到的验证码发送给我们就完成验证,如果2分钟内没有收到短信就请输入“重新发送”,我们将重新给你发送新的验证码,如果想换手机号,就请输入“换手机号”' % info.text
     else:
         text = u"请输入正确的手机号"
     return text
Beispiel #21
0
def send_single():
    if request.method == 'GET':
        return render_template('sms_send_single.html')

    try:
        number = '+86' + request.form['number']
        template_id = request.form.get('template_id')
        sign = request.form.get('sign')

        from app import get_credential

        if template_id and sign:
            req = prepare_send_sms(sdk_id=current_app.config['SMS_SDKAPPID'],
                                   template_id=template_id,
                                   sign=sign)
        else:
            req = prepare_send_sms(sdk_id=current_app.config['SMS_SDKAPPID'])

        resp = json.loads(send_sms([number], req=req, cred=get_credential()))
        return render_template('sms_finished.html', resp=resp)
    except Exception as ex:
        print(ex)
        return render_template('sms_send_single.html')
Beispiel #22
0
 def checkState2(self, value, info):
     if info.text == str(value['verifyCode']):
         StateMachine.end(info.user)
         user = WeixinUser.objects.filter(uid=info.user)[0]
         user.phone = value['phone']
         user.save()
         text = u'恭喜您,已经完成了验证,赶快回复“礼品”去积分商城选择礼品吧'
     elif info.text == u"重新发送":
         if time.time() < value['sendTime'] + 2 * 60:
             text = u"刚给您发送了短信,请耐心等候"
         elif value['sendNum'] > 5:
             text = u"今天已经给您发送了太多短信了,请明天再来吧"
             self.timeout = 12 * 3600
             self.store(info.user, value)
         else:
             verifyCode = str(random.randint(100000, 1000000))
             value['verifyCode'] = verifyCode
             ret = send_sms(value['phone'], u"验证码是%s,15分钟内有效" % verifyCode)
             logger.debug("send sms return %s" % ret)
             value['sendTime'] = time.time()
             value['sendNum'] += 1
             self.store(info.user, value)
             text = u"已经给您发送了一条短信,请查收"
     elif info.text == u"换手机号" or info.text == u"换手机":
         if time.time() < value['sendTime'] + 2 * 60:
             text = u'刚给你发送了短信,请2分钟后没收到,再“换手机号”'
         elif value['sendNum'] > 5:
             text = u'今天已经给你发送了太多短信了,请明天再来吧'
             self.timeout = 12 * 3600
             self.store(info.user, value)
         else:
             value['state'] = 1
             self.store(info.user, value)
             text = u"请输入新的手机号"
     else:
         text = u"您输入的验证码有误,请再看一下"
     return text
Beispiel #23
0
 def checkState2(self, value, info):
     if info.text == str(value['verifyCode']):
         StateMachine.end(info.user)
         user = WeixinUser.objects.filter(uid=info.user)[0]
         user.phone = value['phone']
         user.save()
         text = u'恭喜您,已经完成了验证,赶快回复“礼品”去积分商城选择礼品吧'
     elif info.text == u"重新发送":
         if time.time() < value['sendTime'] + 2 * 60:
             text = u"刚给您发送了短信,请耐心等候"
         elif value['sendNum'] > 5:
             text = u"今天已经给您发送了太多短信了,请明天再来吧"
             self.timeout = 12 * 3600
             self.store(info.user, value)
         else:
             verifyCode = str(random.randint(100000, 1000000))
             value['verifyCode'] = verifyCode
             ret = send_sms(value['phone'], u"验证码是%s,15分钟内有效" % verifyCode)
             logger.debug("send sms return %s" % ret)
             value['sendTime'] = time.time()
             value['sendNum'] += 1
             self.store(info.user, value)
             text = u"已经给您发送了一条短信,请查收"
     elif info.text == u"换手机号" or info.text == u"换手机":
         if time.time() < value['sendTime'] + 2 * 60:
             text = u'刚给你发送了短信,请2分钟后没收到,再“换手机号”'
         elif value['sendNum'] > 5:
             text = u'今天已经给你发送了太多短信了,请明天再来吧'
             self.timeout = 12 * 3600
             self.store(info.user, value)
         else:
             value['state'] = 1
             self.store(info.user, value)
             text = u"请输入新的手机号"
     else:
         text = u"您输入的验证码有误,请再看一下"
     return text
Beispiel #24
0
def app_initiation_api():
    data = request.get_json() if request.get_json() else {}
    if not utils.initiation_validator(data)[0]:
        return jsonify(utils.initiation_validator(data)[1])
    cellNumber = data['cellNumber']
    registerCode = str(random2.randint(10000, 99999))
    sms_result = utils.send_sms(cellNumber, registerCode)
    user = models.User.query.filter_by(cellNumber=cellNumber).first()
    if user:
        return jsonify({
            'status': 303,
            'message': {
                'phone number': cellNumber,
                'register code': registerCode,
                'userId': user.userId
            }
        })
    return jsonify({
        'status': config.HTML_STATUS_CODE['Success'],
        'message': {
            'phone number': cellNumber,
            'register code': registerCode
        }
    })
Beispiel #25
0
def send():
    if request.method == 'GET':
        return render_template('sms_send.html')

    try:
        template_id = request.form.get('template_id')
        sign = request.form.get('sign')
        if template_id and sign:
            req = prepare_send_sms(sdk_id=current_app.config['SMS_SDKAPPID'],
                                   template_id=template_id,
                                   sign=sign)
        else:
            req = prepare_send_sms(sdk_id=current_app.config['SMS_SDKAPPID'])
        data = parse_client_list(request, request.files['list'])

        from app import get_credential
        resp = json.loads(
            send_sms([v.client_number for v in data],
                     req=req,
                     cred=get_credential()))
        return render_template('sms_finished.html', resp=resp)
    except Exception as ex:
        print(ex)
        return render_template('sms_send.html')
Beispiel #26
0
def go(recipient):
    monzo = get_api()
    current_account = get_current_account(monzo)
    todays_transactions = get_todays_transactions(monzo, current_account)
    change = change_to_save(todays_transactions)
    send_sms(change, recipient)
Beispiel #27
0
def add_user_submit():
    if request.method == 'POST':
        # get the form data transmitted by Ajax
        # form is an ImmutableMultiDict object
        # https://tedboy.github.io/flask/generated/generated/werkzeug.ImmutableMultiDict.html
        form = request.form
        # member_id = form.get('member_id')
        first_name = form.get('first_name').strip()
        last_name = form.get('last_name').strip()
        other_names = form.get('other_names').strip()
        gender = form.get('gender')
        occupation = form.get('occupation').strip()
        contact_phone_1 = form.get('contact_phone_1').strip()
        contact_phone_2 = form.get('contact_phone_2').strip()
        dob = form.get('dob')
        email = form.get('email').strip()
        marital_status = form.get('marital_status')
        assembly = form.get('assembly')
        ministry = form.getlist('ministry')
        group = form.get('group')

        password = form.get('password')
        comm_email = form.get('comm_email')
        comm_sms = form.get('comm_sms')
        comm_phone = form.get('comm_phone')

        address_line_1 = form.get('address_line_1').strip()
        address_line_2 = form.get('address_line_2').strip()
        digital_address_code = form.get('digital_address_code').strip()
        region = form.get('region').strip()
        district = form.get('district').strip()
        country = form.get('country')

        try:
            member_id = utils.gen_id(assembly, ministry)
            if not member_id:
                return Response(json.dumps({
                    'status':
                    'FAIL',
                    'message':
                    'Invalid combination of ministries.'
                }),
                                status=400,
                                mimetype='application/json')
            if not utils.upload_photo(member_id):
                return Response(json.dumps({
                    'status':
                    'FAIL',
                    'message':
                    'Image error. Invalid photo.'
                }),
                                status=400,
                                mimetype='application/json')
            if utils.check_email_duplicates(email):
                return Response(json.dumps({
                    'status': 'FAIL',
                    'message': 'Email already exists.'
                }),
                                status=400,
                                mimetype='application/json')
            if utils.check_contact_duplicates(contact_phone_1):
                return Response(json.dumps({
                    'status':
                    'FAIL',
                    'message':
                    'Contact 1 already exists.'
                }),
                                status=400,
                                mimetype='application/json')
            # create new user object
            user = User(member_id=member_id,
                        first_name=first_name,
                        last_name=last_name,
                        other_names=other_names,
                        occupation=occupation,
                        email=email,
                        marital_status=marital_status,
                        assembly=assembly,
                        address_line_1=address_line_1,
                        address_line_2=address_line_2,
                        digital_address_code=digital_address_code,
                        region=region,
                        district=district,
                        country=country)
            user.set_gender(gender)
            user.set_contact_phone_1(contact_phone_1)
            user.set_contact_phone_2(contact_phone_2)
            user.set_dob(dob)
            user.set_ministry(ministry)
            user.set_group(group)
            user.set_password(password)
            user.set_comm_email(comm_email)
            user.set_comm_sms(comm_sms)
            user.set_comm_phone(comm_phone)
            # add the new user to the database and save the changes
            db.session.add(user)
            db.session.commit()

            # send confirmation email or sms
            if email:
                subject = "COP"
                msg_content = utils.compose_email_msg(member_id, password)
                utils.send_email(subject, email, msg_content)
            else:
                msg = utils.compose_sms_msg(member_id, password)
                utils.send_sms(msg, contact_phone_1)

            # return the success response to Ajax
            # return json.dumps({'status':'OK', 'message': 'successful'})
            return Response(json.dumps({
                'status': 'OK',
                'message': 'successful'
            }),
                            status=200,
                            mimetype='application/json')
        except Exception as e:
            print(e)
            print(form)
            return Response(json.dumps({
                'status': 'FAIL',
                'message': 'Fatal error'
            }),
                            status=400,
                            mimetype='application/json')
Beispiel #28
0
def other_to_host(session_id, msg, msg_type):
    info('进入好友发给自己的处理函数')
    # 判断主人是否在会话中
    if msg['FromUserName'] == Host['UserName']:
        SessionList[session_id]['HostIn'] = True

    # 主人不在会话中,则使用回复代理
    if not SessionList[session_id]['HostIn']:
        # 发送给自己的消息类型
        if msg_type == 'Text':
            send_text = msg['Text']
        else:
            send_text = msg_type
        # 好友回复了永久停止小助手
        if msg['Text'] in ReceiveNoise:
            with open('NeverList.never', 'a') as f:
                f.write(NameList[msg['FromUserName']] + '\n')
            itchat.send_msg(ReplyNoise, msg['FromUserName'])
            return
        # 好友回复了对小助手的询问
        if msg['Text'] in ReceiveWhat:
            itchat.send_msg(ReplyWhat, msg['FromUserName'])
            return
        # 好友回复聊天
        if msg['Text'] in ReceiveChat:
            SessionList[session_id]['RobotIn'] = True
            itchat.send_msg(ReplyChat, msg['FromUserName'])
            return
        # 好友回复退出聊天
        if msg['Text'] == 'stop':
            SessionList[session_id]['RobotIn'] = False
            itchat.send_msg('已退出机器人聊天!', msg['FromUserName'])
            return

        # 判断这是该好友发来的第几条消息
        if SessionList[session_id]['FriendCount'] == 1:
            SessionList[session_id]['FriendCount'] += 1
            # 发送第一条消息
            itchat.send_msg(FirstMsg, msg['FromUserName'])
            # VIP好友加送一条
            if SessionList[session_id]['VIP']:
                itchat.send_msg(
                    VIPMsgHead + NameList[msg['FromUserName']] + VIPMsgRear,
                    msg['FromUserName'])
                # 发短信通知
                try:
                    utils.send_sms(
                        '主人,你的微信VIP好友%s在微信上给你发消息:%s。快去看看吧' %
                        (NameList[msg['FromUserName']], send_text),
                        send_number)
                except Exception:
                    itchat.send_msg('阿欧,短信发不了呢,为你尝试发邮件联系喔~',
                                    msg['FromUserName'])
                    # 发邮件
                    try:
                        content = {
                            'header':
                            '微信好友%s发来消息' % NameList[msg['FromUserName']],
                            'text':
                            '主人,你的微信好友%s 在微信上给你发了消息:%s。发你短信出故障了呢!' %
                            (NameList[msg['FromUserName']], send_text)
                        }
                        utils.send_mail(content, HostUserName, KEY, ToUserName)
                    except Exception:
                        itchat.send_msg(
                            '啊,今天真是倒霉,邮件也发不出去啦,要是有急事的话,试试打电话吧:%s' %
                            send_number, msg['FromUserName'])
        # 好友发来的第二条消息,可能是对第一条的回复
        elif SessionList[session_id]['FriendCount'] == 2:
            SessionList[session_id]['FriendCount'] += 1
            # 非VIP好友
            if not SessionList[session_id]['VIP']:
                if msg['Text'] in ReceiveYes:
                    # 发短信通知
                    try:
                        utils.send_sms(
                            '主人,你的微信好友 %s 在微信上给你发消息:%s。快去看看吧' %
                            (NameList[msg['FromUserName']], send_text),
                            send_number)
                        itchat.send_msg(ReplyYes, msg['FromUserName'])
                    except Exception:
                        itchat.send_msg('阿欧,短信发不了了呢,为你尝试发邮件联系喔~',
                                        msg['FromUserName'])
                        # 发邮件
                        try:
                            content = {
                                'header':
                                '微信好友 %s 发来消息' % NameList[msg['FromUserName']],
                                'text':
                                '主人,你的微信好友 %s 在微信上给你发了消息:%s。发你短信出故障了呢!' %
                                (NameList[msg['FromUserName']], send_text)
                            }
                            utils.send_mail(content, HostUserName, KEY,
                                            ToUserName)
                        except Exception:
                            itchat.send_msg(
                                '啊,今天真是倒霉呢,邮件也发不出去啦,要是有急事的话,试试打电话吧:%s' %
                                send_number, msg['FromUserName'])
                elif msg['Text'] in ReceiveNo:
                    itchat.send_msg(ReplyNo, msg['FromUserName'])

                else:
                    # 好友回复聊天状态为True
                    if SessionList[session_id]['RobotIn']:
                        robot_reply = utils.get_response(msg['Text'], key)
                        itchat.send_msg(robot_reply, msg['FromUserName'])
            else:
                # 好友回复聊天状态为True
                if SessionList[session_id]['RobotIn']:
                    robot_reply = utils.get_response(msg['Text'], key)
                    itchat.send_msg(robot_reply, msg['FromUserName'])
        else:  # 启动机器人回复
            # 好友回复聊天状态为True
            if SessionList[session_id]['RobotIn']:
                robot_reply = utils.get_response(msg['Text'], key)
                itchat.send_msg(robot_reply, msg['FromUserName'])
Beispiel #29
0
def test_send():
    number = request.form.get('number', '+8613925114811')
    req = prepare_send_sms()
    return send_sms([number], req)