コード例 #1
0
ファイル: tasks.py プロジェクト: safal20/chatbotApi
def get_scholarships_file():
    auth_token = call_auth_api()
    url = "{api_path}".format(api_path=get_secret("SCHOLARSHIP_API_URL"))
    headers = {'Content-Type': 'application/json', 'B4SAUTH': auth_token}
    response = requests.post(url, headers=headers)
    data = response.json()
    with open(get_secret("SCHOLARSHIPS_JSON_FILE"), 'w') as outfile:
        json.dump(data, outfile)
コード例 #2
0
ファイル: tasks.py プロジェクト: safal20/chatbotApi
def get_schol_info(schol_name):
    schol_id, score = helpers.get_matching_schol(schol_name)
    schol_info = {}
    if score > 60:
        schol_list = helpers.get_schol_list()
        for schol in schol_list:
            schol_nid = schol.get("nid")
            if schol_nid == schol_id:
                schol_info['Nid'] = schol_id
                schol_info["Title"] = schol.get("scholarshipName")
                if schol.get("onlineDeadline"):
                    schol_info["Deadline"] = schol.get("onlineDeadline")
                elif schol.get("deadlineDate"):
                    schol_info["Deadline"] = schol.get("deadlineDate")
                elif schol.get("offlineDeadline"):
                    schol_info["Deadline"] = schol.get("offlineDeadline")
                else:
                    schol_info["Deadline"] = "Coming Soon"
                schol_info["URL"] = get_secret("VODAFONE_PAGE").format(
                    slug=schol.get("slug"))
                for multi in schol.get("scholarshipMultilinguals"):
                    if multi.get("languageId") == 2:
                        schol_info["Eligibility"] = multi.get("applicableFor")
                        schol_info["Award"] = multi.get("purposeAward")
    return schol_info
コード例 #3
0
ファイル: views.py プロジェクト: JMorris1575/confirmation2018
def convert_tags(subject, message, user):
    """
    Converts the following tags in the message or subject line of an e-mail to their equivalent for the given user:
    [first] = first name
    [last] = last name
    [full] = full name
    [user] = username
    [pwrd] = password
    :param subject: string containing the subject line to be sent
    :param message: string containing the message to be sent
    :param user: User object containing data for the given user
    :return: a subject string and message string with all the tags filled in
    """
    user_info = {
        '[first]': user.first_name,
        '[last]': user.last_name,
        '[full]': user.get_full_name(),
        '[user]': user.username,
        '[pwrd]': get_secret(user.username.upper())
    }
    for tag in user_info.keys():
        subject = subject.replace(tag, user_info[tag])
        message = message.replace(tag, user_info[tag])

    return subject, message
コード例 #4
0
ファイル: tasks.py プロジェクト: safal20/chatbotApi
def search_scholarships(params):
    rules_list = list()
    rules_list = rules_list + helpers.convert_to_rules_by_rule(
        [params['class']], '1')
    rules_list = rules_list + helpers.convert_to_rules_by_rule(
        [params['gender']], '5')
    rules_list = rules_list + helpers.convert_to_rules_by_rule(
        [params['religion']], '4')
    rules = rules_list + helpers.convert_to_rules_by_rule(
        params['interest-area'], '7')
    post_data = {
        "email": params['email'],
        "firstName": params['first_name'],
        "lastName": params['last_name'],
        "mobileNumber": params['phone'],
        "rules": rules
    }
    print(post_data)
    url = "{api_path}".format(api_path=get_secret("USER_REGISTER_API"))
    auth_token = get_auth_token()
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + auth_token
    }
    response = requests.post(url, data=json.dumps(post_data), headers=headers)
    return response.json()
コード例 #5
0
ファイル: tasks.py プロジェクト: safal20/chatbotApi
def call_auth_api():
    try:
        url = "{auth_api}".format(auth_api=get_secret("AUTH_API"))
        response = requests.post(url)
        return response.json()['BODY']['DATA']['TOKEN']
    except Exception:
        return None
コード例 #6
0
def get_token():
    basic_send_url = 'https://kakaoapi.aligo.in/akv10/token/create/30/s/'  # 요청을 던지는 URL, 현재는 토큰생성
    # token/create/토큰 유효시간/{y(년)/m(월)/d(일)/h(시)/i(분)/s(초)}/

    # ================================================================== 토큰 생성 필수 key값
    # API key, userid
    # API키, 알리고 사이트 아이디

    sms_data={'apikey': get_secret("ALIGO_APIKEY"), #api key
            'userid': get_secret("ALIGO_ID"), # 알리고 사이트 아이디
    }

    create_token_response = requests.post(basic_send_url, data=sms_data)
    print('token_response :\n', create_token_response.json())

    return create_token_response.json()
コード例 #7
0
ファイル: tasks.py プロジェクト: safal20/chatbotApi
def call_scholarships_api(scholarship_auth_token):
    try:
        url = "{scholarship_api_url}".format(
            scholarship_api_url=get_secret("SCHOLARSHIP_API_URL"))
        headers = {'B4SAUTH': scholarship_auth_token}
        response = requests.post(url, headers=headers)
        return response.json()['BODY']['DATA']
    except Exception:
        return None
コード例 #8
0
ファイル: tasks.py プロジェクト: safal20/chatbotApi
def submit_query(params):
    url = "{api_path}".format(api_path=get_secret("QUERY_SUBMISSION_API"))
    auth_token = get_auth_token()
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + auth_token
    }
    response = requests.post(url, data=json.dumps(params), headers=headers)
    return response.json()
コード例 #9
0
ファイル: tasks.py プロジェクト: safal20/chatbotApi
def get_auth_token():
    try:
        url = "{api_path}".format(api_path=get_secret("CHATBOT_AUTH_API"))
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer'
        }
        post_data = {
            "username": get_secret("CHATBOT_USER"),
            "password": get_secret("CHATBOT_PASS")
        }
        response = requests.post(url,
                                 data=json.dumps(post_data),
                                 headers=headers)
        auth_token = response.json().get('access_token')
        return auth_token

    except Exception:
        return None
コード例 #10
0
ファイル: tasks.py プロジェクト: safal20/chatbotApi
def update_user_rule(user_id, rule):
    url = "{api_path}".format(api_path=get_secret("ADD_USER_RULE").format(
        user_id=user_id, rule=rule))
    auth_token = get_auth_token()
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + auth_token
    }
    response = requests.post(url, headers=headers)
    return response
コード例 #11
0
ファイル: tasks.py プロジェクト: safal20/chatbotApi
def update_user(user_id, field, value):
    post_data = {field: value}
    url = "{api_path}".format(
        api_path=get_secret("UPDATE_USER_DETAILS").format(user_id=user_id))
    auth_token = get_auth_token()
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + auth_token
    }
    response = requests.post(url, headers=headers, data=json.dumps(post_data))
    return response
コード例 #12
0
ファイル: tasks.py プロジェクト: safal20/chatbotApi
def find_schol_userid(user_id):
    url = "{api_path}".format(api_path=get_secret("SCHOLARSHIPS_USER").format(
        user_id=user_id))
    auth_token = get_auth_token()
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + auth_token
    }
    response = requests.get(url, headers=headers)
    data = response.json().get('data')
    return data
コード例 #13
0
ファイル: tasks.py プロジェクト: safal20/chatbotApi
def call_scholarship_detail_api(scholarship_nid, scholarship_auth_token):
    try:
        url = "{scholarship_detail_api_url}/{nid}".format(
            scholarship_detail_api_url=get_secret(
                "SCHOLARSHIP_DETAIL_API_URL"),
            nid=scholarship_nid)
        headers = {'B4SAUTH': scholarship_auth_token}
        response = requests.get(url, headers=headers)
        return response.json()['BODY']['RECOMENDED'][0]
    except Exception:
        return None
コード例 #14
0
ファイル: tasks.py プロジェクト: safal20/chatbotApi
def get_missing_fields(user_id):
    missing_fields = []
    url = "{api_path}".format(api_path=get_secret("MISSING_FIELDS_API").format(
        user_id=user_id))
    auth_token = get_auth_token()
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + auth_token
    }
    response = requests.get(url, headers=headers)
    data = response.json().get('data')
    if data:
        missing_fields = data.get('missingFields')

    return missing_fields
コード例 #15
0
ファイル: tasks.py プロジェクト: safal20/chatbotApi
def call_third_party_api(post_data):
    try:
        api_key = "Bearer {api_ai_key}".format(
            api_ai_key=get_secret("API_AI_KEY"))
        url = "{api_path}".format(api_path=api_ai)
        headers = {
            'Content-Type': 'application/json',
            'Authorization': api_key
        }
        response = requests.post(url,
                                 data=json.dumps(post_data),
                                 headers=headers)
        return response.json()
    except Exception:
        return None
コード例 #16
0
ファイル: tasks.py プロジェクト: safal20/chatbotApi
def get_user_details(user_id):
    url = "{api_path}".format(api_path=get_secret("USER_DETAILS").format(
        user_id=user_id))
    auth_token = get_auth_token()
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + auth_token
    }
    response = requests.post(url, headers=headers)
    data = response.json().get("data").get("BODY").get("DATA")
    user = data.get("USER")
    name = user.get("FIRST_NAME") + " " + user.get("LAST_NAME")
    email = user.get("EMAIL")
    phone = user.get("MOBILE_NUMBER")

    return {"name": name, "email": email, "phone": phone}
コード例 #17
0
 def post(self, request):
     print("I've gotten to the post method of MailCompose.")
     recipients = request.POST.getlist('family_member')
     orig_subject = request.POST['subject']
     orig_message = request.POST['message']
     for member in recipients:
         user = User.objects.get(username=member)
         password_key = user.username.upper()
         password = get_secret(password_key)
         subject, message = translate_tags(orig_subject, orig_message,
                                           user.first_name, user.username,
                                           password)
         send_mail(
             subject,
             message,
             '*****@*****.**',
             [user.email],
             fail_silently=False,
         )
     return redirect('gift_list')
コード例 #18
0
    def post(self, request):
        recipients = request.POST.getlist('family_member')
        template = EmailTemplate.objects.get(name='invitation')
        orig_message = template.template
        for member in recipients:
            user = User.objects.get(username=member)
            password_key = user.username.upper()
            password = get_secret(password_key)
            subject, message = translate_tags(
                "<name>'s Login Information for this Year's Family Christmas Website",
                orig_message, user.first_name, user.username, password)

            send_mail(
                subject,
                message,
                '*****@*****.**',
                [user.email],
                fail_silently=False,
            )
        return redirect('gift_list')
コード例 #19
0
def send_friend_msg(aligo_token, msg):
    basic_send_url = 'https://kakaoapi.aligo.in/akv10/friend/send/' # 요청을 던지는 URL, 친구톡 전송


    # ================================================================== 친구톡 보낼 때 필수 key값
    # API key, userid, token, senderkey, sender, receiver_1, subject_1, message_1
    # API키, 알리고 사이트 아이디, 토큰, 발신프로파일 키, 발신번호, 수신번호, 친구톡 제목, 친구톡 내용
    #
    # ================================================================== 친구톡 보낼 때 선택 key값
    # senddate, advert, image, image_url, recvname_1, button_1,
    # 예약일, 광고분류(기본Y), 첨부이미지, 첨부이미지에 삽입되는 링크,수신자 이름, 버튼 정보,
    # failover, fimage, fsubject_1, fmessage_1, testMode
    # 실패시 대체문자 {전송여부/첨부이미지/제목/내용}, 테스트 모드 적용 여부(기본N)
    #


    sms_data={'apikey': get_secret("ALIGO_APIKEY"),  #api key
            'userid': get_secret("ALIGO_ID"),  # 알리고 사이트 아이디
            'token': aligo_token['token'],  # 생성한 토큰
            'senderkey': get_secret("ALIGO_SENDERKEY"),  # 발신프로파일 키
            'sender' : msg['sender'],  # 발신자 연락처,
            #'senddate': '19000131120130',  # YYYYMMDDHHmmss
            'advert': 'N',  # 광고분류(기본Y)
            #'recvname_1': '홍길동1', # 수신자 이름
            #'failover': 'Y or N', # 실패시 대체문자 전송 여부(템플릿 신청시 대체문자 발송으로 설정하였더라도 Y로 입력해야합니다.)
            #'fsubject_1': '대체문자 제목', # 실패시 대체문자 제목
            #'fmessage_1': '대체문자 내용', # 실패시 대체문자 내용
            #'testMode': 'Y or N' # 테스트 모드 적용여부(기본N), 실제 발송 X
            }

    if len(msg['receiver']) == 1:
        sms_data['receiver_1'] = msg['receiver']  # 친구톡 수신자
        sms_data['subject_1'] = msg['content'][:30]  # 친구톡 제목
        sms_data['message_1'] = msg['content']  # 친구톡 내용
    else:
        cur = 0
        for receiver in msg['receiver']:
            cur += 1
            sms_data['receiver_' + str(cur)] = receiver
            sms_data['subject_' + str(cur)] = msg['content'][:30]
            sms_data['message_' + str(cur)] = msg['content']

    try:
        # -------------------------------------------------------------------------------------------------
        # BUTTON
        #
        # name: 버튼명,
        # linkType: 버튼 링크타입(DS:배송조회, WL:웹링크, AL:앱링크, BK:봇키워드, MD:메시지전달),
        # linkTypeName : 버튼 링크 타입네임, ( 배송조회, 웹링크, 앱링크, 봇키워드, 메시지전달 중에서 1개)
        # linkM: 모바일 웹링크주소(WL일 때 필수), linkP: PC웹링크 주소(WL일 때 필수),
        # linkI: IOS앱링크 주소(AL일 때 필수), linkA: Android앱링크 주소(AL일 때 필수)

        button_info = {'button': [{'name': msg['weblink']['btn_name'],  # 버튼명
                                   'linkType': 'WL',  # DS, WL, AL, BK, MD
                                   'linkTypeName': '웹링크',  # 배송조회, 웹링크, 앱링크, 봇키워드, 메시지전달 중에서 1개
                                   'linkM': msg['weblink']['weblink_mobile'],  # WL일 때 필수
                                   'linkP': msg['weblink']['weblink_pc']  # WL일 때 필수
                                   # 'linkI': 'IOS app link', # AL일 때 필수
                                   # 'linkA': 'Android app link' # AL일 때 필수
                                   }]}
        sms_data['button_1'] = json.dumps(button_info)  # 버튼 정보
    except:
        pass

    try:
        sms_data['image_url'] = msg['img']['img_link']  # 첨부이미지에 삽입되는 링크
        # s3_base = 'https://ilhwa-pharm.s3.ap-northeast-2.amazonaws.com/media/friendstalk/'
        # images = {'image': s3_base + msg['img']['img_url'].name}  # 첨부 이미지 경로
        # print("경로명 :    ", images)
        images = {'image' : open(msg['img']['img_url'], 'rb')}
        # images.update({'fimage': open(image['path'], 'rb')}) # 실패시 첨부이미지 경로
        # =================================================================================================
        # 첨부 이미지 포함 전송
        friend_send_response = requests.post(basic_send_url, data=sms_data, files=images)
    except TypeError:
        # =================================================================================================
        # 첨부 이미지 없이 전송
        friend_send_response = requests.post(basic_send_url, data=sms_data)

    print('send_response : \n', friend_send_response.json())

    return friend_send_response.json()
コード例 #20
0
ファイル: tasks.py プロジェクト: safal20/chatbotApi
import json

import requests
from . import helpers

from config.settings.base import get_secret

api_ai = get_secret("API_AI")


def call_third_party_api(post_data):
    try:
        api_key = "Bearer {api_ai_key}".format(
            api_ai_key=get_secret("API_AI_KEY"))
        url = "{api_path}".format(api_path=api_ai)
        headers = {
            'Content-Type': 'application/json',
            'Authorization': api_key
        }
        response = requests.post(url,
                                 data=json.dumps(post_data),
                                 headers=headers)
        return response.json()
    except Exception:
        return None


def call_auth_api():
    try:
        url = "{auth_api}".format(auth_api=get_secret("AUTH_API"))
        response = requests.post(url)
コード例 #21
0
ファイル: celery.py プロジェクト: tiusty/Cocoon
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from config.settings.base import get_secret

# set the default
# Loads the settings file via the secrets file settings
os.environ["DJANGO_SETTINGS_MODULE"] = get_secret('DJANGO_SETTINGS_MODULE')

app = Celery('config')

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()


@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

コード例 #22
0
from pymongo import MongoClient
from config.settings.base import get_secret

password = get_secret("DB_PASSWORD")
username = get_secret("DB_USER")
db_name = get_secret("DB_NAME")
db_host_mongo = get_secret("DB_HOST")

mongo_uri = "mongodb+srv://{username}:{password}@{host}/{db_name}".format(
    username=username, password=password, host=db_host_mongo, db_name=db_name)

client = MongoClient(mongo_uri)
database = client[db_name]
コード例 #23
0
ファイル: constants.py プロジェクト: tiusty/Cocoon
from django.conf import settings

from config.settings.base import get_secret

# Docusign account variables
REDIRECT_URI = "https://bostoncocoon.com"

# Docusign variables dependent on settings file
if settings.DEBUG:
    OAUTH_BASE_URL = get_secret("OAUTH_BASE_URL_DEV")
    BASE_URL = get_secret('BASE_URL_DEV')
    USER_ID = get_secret('USER_ID_DEV')
    ACCOUNT_ID = get_secret('ACCOUNT_ID_DEV')
    INTEGRATOR_KEY = get_secret('INTEGRATOR_KEY_DEV')
    DOCUSIGN_KEY = "DOCUSIGN_PRIVATE_KEY_DEV"
    AUTHENTICATION_VALUE = get_secret('AUTHENTICATION_VALUE_DEV')

    # Templates in dev
    PRE_TOUR_TEMPLATE_ID = 'd77cb639-fc56-434b-8aa7-5b6052ae2465'
else:
    OAUTH_BASE_URL = get_secret("OAUTH_BASE_URL_PROD")
    BASE_URL = get_secret('BASE_URL_PROD')
    USER_ID = get_secret('USER_ID_PROD')
    ACCOUNT_ID = get_secret('ACCOUNT_ID_PROD')
    INTEGRATOR_KEY = get_secret('INTEGRATOR_KEY_PROD')
    DOCUSIGN_KEY = "DOCUSIGN_PRIVATE_KEY_PROD"

    # Authentication value is needed for production
    AUTHENTICATION_VALUE = get_secret('AUTHENTICATION_VALUE_PROD')

    # Templates in prod