Exemplo n.º 1
0
def execute():
    while 1 == 1:
        # update indo about virtual memory
        url = "http://localhost:8081/setVirtualMemory/100"
        response = requests.post(
            url, data=get_memory_info(),
            headers=headers)  # update virtual memory info on server
        print(response)
        print("virtual info update")
        # update info about CPU
        url = "http://localhost:8081/setCPUInfoMemory/100"
        response = requests.post(
            url, data=get_cpu_info(),
            headers=headers)  # update virtual memory info on server
        print(response)
        print("cpu info update")
        url = "http://localhost:8081/setDiskInfo/100"
        response = requests.post(url, data=get_disks_info(),
                                 headers=headers)  # update disk information
        print(response)
        print("disk info update")
        url = "http://localhost:8081/setOpenPorts/100"
        response = requests.post(url, data=get_ports(),
                                 headers=headers)  # update open ports
        print(response)
        print("open ports update")
        time.sleep(10)
Exemplo n.º 2
0
    def scrap_url(self):
        while self.retrieve_url():
            blob = self.retrieve_url()
            self.web_driver.get(f"https://www.olx.pl/oferta/{blob}.html")

            offer_titlebox = self.web_driver.find_element_by_xpath(
                '//div[@class="offer-titlebox"]')

            title = offer_titlebox.find_element_by_tag_name("h1").text
            price = offer_titlebox.find_element_by_xpath(
                '//strong[@class=pricelabel]').text
            quality = self.web_driver.find_element_by_xpath(
                '//strong[@class="offer-details__value"]').text

            offer_bottombar__items = self.web_driver.find_element_by_id(
                "offerbottombar")
            create_date = offer_bottombar__items.find_element_by_tag_name(
                'em').find_element_by_tag_name('strong').text
            views = offer_bottombar__items.find_element_by_xpath(
                '//span[@class="offer-bottombar__counter"]/strong').text

            post_data = {
                "url": blob,
                "title": title,
                "price": price,
                "quality": quality,
                "created": create_date,
                "views": views
            }

            requests.post(f"{self.parent_ip}/scrapper/add_data",
                          json=json.dumps(post_data))
Exemplo n.º 3
0
def checkDiscount(request):
    if request.method == "POST":
        form = CheckDiscountForm(request.POST)

        if form.is_valid():
            s = f"{request.user.username}{form.cleaned_data.get('ammount')}{int(form.cleaned_data.get('time').timestamp())}{12345}"
            data = {
                "username": request.user.username,
                'ammount': form.cleaned_data.get('ammount'),
                'time': form.cleaned_data.get('time').timestamp(),
                'signature': hashlib.sha256(s.encode()).hexdigest()
            }

            apicall = requests.post('http://127.0.0.1:8080/checkdiscount',
                                    json=data)
            if apicall.status_code == 201 or apicall.status_code == 202:
                return render(request, 'transaction/success.html',
                              {'response': apicall.json()})
            else:
                messages.error(request, "Error, contact admin")
                return render(request, 'transaction/transaction.html',
                              {'form': form})
        else:
            messages.error(request, "Please input the correct format")
            return render(request, 'transaction/transaction.html',
                          {'form': form})
    else:
        form = CheckDiscountForm()
        return render(request, 'transaction/transaction.html', {'form': form})
Exemplo n.º 4
0
def github_oauth(request):
    grant = request.GET['code']
    state = request.GET['state']

    user_id = cache.get(state)

    if (user_id == request.user.id):
        client_id = '99483968851edaa50f7f'
        client_secret = '65737905e37e46bceae4cb8d575971b57db1d0e7'
        data = {
            'client_id': client_id,
            'redirect_uri': 'http://localhost:8080/oauth/github',
            'client_secret': client_secret,
            'code': grant
        }

        headers = {'Accept': 'application/json'}
        res = requests.post('https://github.com/login/oauth/access_token',
                            params=data,
                            headers=headers).json()
        request.user.facebook_token = res['access_token']
        request.user.save()

        emailRes = requests.get(
            'https://api.github.com/user/emails?access_token=' +
            res['access_token'])
        print(emailRes)
        return redirect('lostsoul_web:add_new_article')
Exemplo n.º 5
0
def suporte_cadastra(usuario):
    now = datetime.now()
    form = UsuarioForm(usuario)
    if form.is_valid():
        nome = form.cleaned_data['nome']
        email = form.cleaned_data['email']
        status_ativacao = form.cleaned_data['status_ativacao']
        empresa = form.cleaned_data['empresa']

        data = suporte_monta_json(nome, email, empresa, status_ativacao)
        send_mail(
            'Bem-vindo ao time TW314',
            'Olá, ' + nome +
            '! Esse e-mail foi cadastrado em nosso sistema em ' +
            str(now.day) + '/' + str(now.month) + '/' + str(now.year) +
            ' às ' + str(now.hour) + ':' + str(now.minute) +
            'hrs. Aguarde novo contato para cadastrar sua senha. Se acredita que houve um engano, por favor, entre em contado pelo e-mail [email protected] . Att, Time TW314',
            '*****@*****.**',
            [email],
            fail_silently=False,
        )
        form = requests.post('http://localhost:3000/usuario', json=data)
    else:
        form = "<h3>Campos de Usuario nao preenchidos corretamente</h3>"

    return form
def doLogin(request):
    if request.method != "POST":
        return HttpResponse("<h2> Method not allowed </h2>")

    else:
        captcha_token = request.POST.get("g-recaptcha-response")
        cap_url = "https://www.google.com/recaptcha/api/siteverify"
        cap_secret = "6LeuJf8ZAAAAAFoMGISgljZ9e9A8gVydrATMzrwE"
        cap_data = {"secret": cap_secret, "response": captcha_token}
        cap_server_response = requests.post(url=cap_url, data=cap_data)
        cap_json = json.loads(cap_server_response.text)
        if cap_json['success'] == False:
            messages.error(request, "Invalid Captcha Try Again ")
            return HttpResponseRedirect("/")

        user = EmailBackEnd.authenticate(request,
                                         username=request.POST.get("email"),
                                         password=request.POST.get("password"))
        if user != None:
            login(request, user)
            if user.user_type == "1":
                return HttpResponseRedirect('/admin_home')
            elif user.user_type == "2":
                return HttpResponseRedirect(reverse("staff_home"))
            else:
                return HttpResponseRedirect(reverse("student_home"))

        else:
            messages.error(request, "Invalid  Login Details ")
            return HttpResponseRedirect("/")
Exemplo n.º 7
0
def suporte_cadastro_servico(request):
    # Cadastro
    if request.method == "POST":
        form = SvcForm(request.POST)
        if form.is_valid():
            nome = form.cleaned_data['nome']
            descricao = form.cleaned_data['descricao']
            sigla = form.cleaned_data['sigla']
            status_ativacao = form.cleaned_data['status_ativacao']
            data = {
                'nome': nome,
                'descricao': descricao,
                'sigla': sigla,
                'status_ativacao': status_ativacao
            }
            form = requests.post('http://localhost:3000/servico/', json=data)
    else:
        form = SvcForm()

    servicos = requests.get('http://localhost:3000/servico/').json()
    ram = requests.get('http://localhost:3000/ramoAtividade').json()

    return render(request, 'home/suporte/suporte_cadastro_servico.html', {
        'servicos': servicos,
        'ram': ram,
        'form': form
    })
Exemplo n.º 8
0
def trade(appId,
          appKey,
          ordername,
          mhtOrderDetail,
          payChannelType,
          deviceType,
          notifyUrl,
          isTest,
          outputType,
          frontNotifyUrl="",
          amt="1",
          orderno='',
          channelAuthCode='',
          oriMhtOrderAmt='',
          discountAmt=''):
    paypara = {
        'funcode': 'WP001',
        'version': '1.0.0',
        'appId': appId,
        'mhtOrderType': '01',
        'mhtCurrencyType': '156',
        'mhtOrderDetail': mhtOrderDetail,
        'mhtOrderTimeOut': 3600,
        'notifyUrl': notifyUrl,
        'mhtCharset': 'UTF-8',
        'deviceType': deviceType,
        'payChannelType': payChannelType,
        'outputType': outputType,
        'mhtSignType': 'MD5'
    }
    if len(frontNotifyUrl) > 0:
        paypara["frontNotifyUrl"] = frontNotifyUrl
    if len(channelAuthCode) > 0:
        paypara['channelAuthCode'] = channelAuthCode
    timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    if len(orderno) == 0:
        orderno = timestr + '_' + ''.join(
            random.sample(string.ascii_letters, 16))
    paypara['mhtOrderStartTime'] = timestr
    paypara['mhtOrderNo'] = orderno
    paypara['mhtOrderName'] = ordername
    paypara['mhtOrderAmt'] = amt
    if len(oriMhtOrderAmt) > 0:
        paypara["oriMhtOrderAmt"] = oriMhtOrderAmt

    if len(discountAmt) > 0:
        paypara["discountAmt"] = discountAmt
    try:
        tradestr = interface.trade(appKey, paypara)
    except interface.APIInputError as ipse:
        print(ipse)
    except Exception as e:
        print(e)
        print(e.with_traceback)
    if isTest:
        url = testTradeUrl
    else:
        url = proTradeUrl
    resp = requests.post(url, tradestr)
    return urllib.parse.unquote(resp.text)
Exemplo n.º 9
0
def sendDiagnosis(age, sex, symptoms):
    url = "https://api.infermedica.com/v2/diagnosis"

    body = {
        "sex": sex,
        "age": age,
        "extras": {
            "disable_groups": True
        },
        "evidence": symptoms
    }
    parser = ConfigParser()
    parser.read('configurations.ini')

    app_id = parser.get('auth', 'app_id')
    app_key = parser.get('auth', 'app_key')

    header = {
        'Content-Type': 'application/json',
        'App-Id': app_id,
        'App-Key': app_key
    }
    # print(f'symptoms: {symptoms}, type: {type(symptoms)}')
    # print('[*] Sending diagnosis request...')
    r = requests.post(url=url, json=body, headers=header)

    return r.text
Exemplo n.º 10
0
def sendParse(message):
    url = "https://api.infermedica.com/v2/parse"

    parser = ConfigParser()
    parser.read('configurations.ini')

    app_id = parser.get('auth', 'app_id')
    app_key = parser.get('auth', 'app_key')

    header = {
        'Content-Type': 'application/json',
        'App-Id': app_id,
        'App-Key': app_key
    }

    data = {'text': message}
    # print('[*] Sending parse request...')
    r = requests.post(url=url, json=data, headers=header)
    response = loads(r.text)

    if len(response['mentions']) == 0:
        return 'We could not understand your message'
    else:
        text = []

        for mention in response['mentions']:
            if mention['type'] == 'symptom':
                # text += '+' + mention['name'] + ' [' + mention['choice_id'] + ']\n'
                new_sym = {
                    'id': mention['id'],
                    'choice_id': mention['choice_id'],
                    'initial': True
                }
                text.append(new_sym)
        return text
    def get(self, request, *args, **kwargs):
        import xml.etree.ElementTree as ET
        oid = request.GET.get("oid")
        amt = request.GET.get("amt")
        refId = request.GET.get("refId")

        url = "https://uat.esewa.com.np/epay/transrec"
        d = {
            'amt': amt,
            'scd': 'epay_payment',
            'rid': refId,
            'pid': oid,
        }
        resp = requests.post(url, d)
        root = ET.fromstring(resp.content)
        status = root[0].text.strip()

        order_id = oid.split("_")[1]
        order_obj = Order.objects.get(id=order_id)
        if status == "Success":
            order_obj.payment_completed = True
            order_obj.save()
            return redirect("/")
        else:

            return redirect("/esewa-request/?o_id=" + order_id)
    def get(self, request, *args, **kwargs):
        token = request.GET.get("token")
        amount = request.GET.get("amount")
        o_id = request.GET.get("order_id")
        print(token, amount, o_id)

        url = "https://khalti.com/api/v2/payment/verify/"
        payload = {"token": token, "amount": amount}
        headers = {
            "Authorization":
            "Key test_secret_key_f59e8b7d18b4499ca40f68195a846e9b"
        }

        order_obj = Order.objects.get(id=o_id)

        response = requests.post(url, payload, headers=headers)
        resp_dict = response.json()
        if resp_dict.get("idx"):
            success = True
            order_obj.payment_completed = True
            order_obj.save()
        else:
            success = False
        data = {"success": success}
        return JsonResponse(data)
Exemplo n.º 13
0
 def get(self, id, id_agent, serial_number, email_loggin, server_mail, port,
         mail_send, mail_send_pwd, subject):
     try:
         myobj = {
             'id': id,
             'id_agent': id_agent,
             'server_mail': server_mail,
             'port': port,
             'mail_send': mail_send,
             'mail_send_pwd': mail_send_pwd,
             'subject': subject,
         }
         response = requests.post(API_SETTING + str(id) + '/' +
                                  str(serial_number) + '/' +
                                  str(email_loggin),
                                  data=myobj)
         geodata = response.json()
         if geodata['status'] == 'false':
             return jsonify({
                 'status': 'false',
                 'msg': geodata['msg'],
                 'error': geodata['error']
             })
         return jsonify({
             'status': 'true',
             'msg': geodata['msg'],
             'error': ''
         })
     except Exception as e:
         return jsonify({
             'status': 'false',
             'msg': 'Lỗi hệ thống',
             'error': str(e)
         })
Exemplo n.º 14
0
    def get(self, request):
        organizacoes = Organizacao.objects.filter(
            pk=request.user.funcionario.organizacao.pk).values()
        lOrganizacao = []

        for organizacao in organizacoes:
            organizacaoDic = {
                'id': organizacao['id'],
                'nome': organizacao['nome'],
                'cnpj': organizacao['cnpj'],
                'endereco': organizacao['endereco'],
                'telefone': organizacao['telefone'],
                'situacao': organizacao['situacao'],
                'enviado': organizacao['enviado'],
                'pedido': False
            }
            lOrganizacao.append(organizacaoDic)

        # Envio da request
        resp = requests.post(
            url='http://127.0.0.1:8080/SAPH/saph/organizacao/configuracao/',
            data=json.dumps(organizacaoDic),
            headers={'content-type': 'application/json'})
        if (resp.status_code == 200 or resp.status_code == 201):
            org = get_object_or_404(Organizacao, pk=organizacoes[0]['id'])
            org.pedido = False
            org.save()
            return HttpResponseRedirect(reverse("page_home"))
        else:
            return HttpResponseRedirect(reverse("page_home"))
Exemplo n.º 15
0
async def uploadFile():
    JsonFile = ""
    try:
        with open("log_lookup.json", "r", encoding="utf8") as f:
            JsonFile = f.read()
    except FileNotFoundError:
        print("lookup file was not found")
        return False

    payload = {
        "sections": [{
            "name": "JSONMap",
            "syntax": "json",
            "contents": JsonFile
        }]
    }
    req = requests.post("https://api.paste.ee/v1/pastes",
                        headers=headers,
                        json=payload)
    print(req.status_code, req.reason)
    status = int(req.status_code / 100) == 2
    idVal = ""
    if status:  # get ID
        try:
            idVal = json.loads(req.text)["id"]
        except:
            status = False

    return (status, idVal)  # 2XX code
Exemplo n.º 16
0
def cadastra(empresa):
    form = EmpresaForm(empresa)

    if form.is_valid():
        ramo_atividade = form.cleaned_data['ramo_atividade']
        numero_cnpj = form.cleaned_data["numero_cnpj"]
        nome_fantasia = form.cleaned_data['nome_fantasia']
        razao_social = form.cleaned_data['razao_social']
        status_ativacao = form.cleaned_data['status_ativacao']
        cep = form.cleaned_data['cep']
        logradouro = form.cleaned_data['logradouro']
        numero_logradouro = form.cleaned_data['numero_logradouro']
        bairro = form.cleaned_data['bairro']
        cidade = form.cleaned_data['cidade']
        uf = form.cleaned_data['uf']
        email = form.cleaned_data['email']
        telefone = form.cleaned_data['telefone']
        nome_responsavel = form.cleaned_data['nome_responsavel']
        cargo_responsavel = form.cleaned_data['cargo_responsavel']
        cpf_responsavel = form.cleaned_data['cpf_responsavel']

        data = monta_json(nome_fantasia, razao_social, numero_cnpj, logradouro, numero_logradouro, bairro, cidade, uf, cep, telefone, email, nome_responsavel, cargo_responsavel, cpf_responsavel, ramo_atividade, status_ativacao)
        try:
            form = requests.post('http://localhost:3000/empresa', json=data)
        except requests.exceptions.ConnectionError: # verificar se funciona
            form = "Erro ao tentar conectar com WebService"
    else:
        form = "Campos de Empresa nao preenchidos corretamente"
    return form
Exemplo n.º 17
0
def register():

    if request.method=='GET':
        return render_template('register.html',basic={"title":"User register"})
    elif request.method=='POST':
        data = RequestProc(request).dataPckg

        dataCollection={User.email.name:data[User.email.name],
                 User.idcard.name:data[User.idcard.name],
                 User.last_name.name:data[User.last_name.name],
                 User.first_name.name:data[User.first_name.name],
                 User.user_type.name:int(data[User.user_type.name]),
                 User.passwd.name:general().gen_hash(data[User.passwd.name]),
                 User.idcard_type.name:int(data[User.idcard_type.name])}

        dataCol=User.insert(dataCollection)
        headers = {'Content-Type': 'application/json'}
        if int(data[User.user_type.name]) == 2:
            path='http://localhost:8041/api/patients'
        elif int(data[User.user_type.name]) == 1:
            path='http://localhost:8041/api/doctors'
        else:
            path = 'http://localhost:8041/api/patients'
        response_load = requests.post(path,
                                      data=json.dumps(dataCollection),
                                      headers=headers)
        if response_load.status_code != 200:
            raise Exception("There was a problem communicating with the validator.")
        elif response_load.status_code == 200:
            resp_data =json.loads(response_load.content.decode())
            if resp_data["status"]=='DONE':
                return redirect(url_for('login'))
Exemplo n.º 18
0
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = form.save()
            username = form.cleaned_data.get('username')
            user.profile.phone_number = form.cleaned_data.get("phone_number")
            user.save()

            messages.success(request, f'You Have Created An Account, {username}, please check your email for verification')

            s = username + form.cleaned_data.get('email') + '12345'
            data = {
                'username': username,
                'email': form.cleaned_data.get('email'),
                'signature': hashlib.sha256(s.encode()).hexdigest()
            }

            apicall = requests.post("http://127.0.0.1:8080/otp/create", json=data)
            if(apicall.status_code != 201):
                raise AssertionError()

            request.session['userdata'] = {
                'id': user.id,
                'username': username
            }
            return redirect(reverse("user:otp"))
    else:
        form = RegistrationForm()
    return render(request, 'user/register.html', {'form' : form})
Exemplo n.º 19
0
def home(request):
    """
    Home
    """
    cookie = request.COOKIES
    if 'currentuser' in cookie:
        if request.method == 'POST':
            token = cookie['currentuser']
            header = 'Token ' + token
            print(token)
            user = User.objects.get(username=Token.objects.get(key=token).user)
            children = user.child.all()
            name = request.POST['name']
            age = int(request.POST['age'])
            gender = request.POST['gender']
            print(gender)

            payload = {'user': user, 'name': name, 'age': age, 'gender': gender}
            obj = requests.post('http://127.0.0.1:8000/child', data=payload, headers={'Authorization': header}).json()
            print(obj)

            return render(request, 'home.html', {'user': user, 'children': children})
        else:
            token = cookie['currentuser']
            user = User.objects.get(username=Token.objects.get(key=token).user)
            children = user.child.all()
            return render(request, 'home.html', {'user':user, 'children': children})
    else:
        return HttpResponse('You are not logged in :-( ')
Exemplo n.º 20
0
 def runAd(self, req_length):
     c = self.connection
     if req_length != None:  #round their given length
         length = req_length.split(' ')[0]
         try:
             length = round(
                 int(length) / 30
             ) * 30  #div by 30 then round to nearest number, then *30 to get multiple of 30 length
             if length > 180:  #if length is greater than max length (3 mins), then set to 3 mins
                 length = 180
         except:
             c.privmsg(self.channel, 'Please input a valid ad length')
             return
     url = 'https://api.twitch.tv/helix/channels/commercial'
     headers = {
         'Client-Id': self.client_id,
         'Content-Type': 'application/json',
         'Authorization': 'Bearer ' + self.token
     }
     raw_data = '{ "broadcaster_id": "%s", "length": %d }' % (
         self.channel_id, length)
     r = requests.post(url, data=raw_data, headers=headers)
     if (r.ok):
         length = r['data'][0]['length']
         c.privmsg(self.channel, 'Running a %d sec ad' % length)
     else:
         c.privmsg(self.channel, 'Ad failed :(')
Exemplo n.º 21
0
    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        ''' Begin reCAPTCHA validation '''
        recaptcha_response = request.POST.get('g-recaptcha-response')
        data = {
            'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
            'response': recaptcha_response
        }
        r = requests.post('https://www.google.com/recaptcha/api/siteverify',
                          data=data)
        result = r.json()
        verify = result["success"]
        ''' End reCAPTCHA validation '''

        if form.is_valid():
            if verify:
                return self.form_valid(form, **kwargs)
            else:
                messages.warning(request,
                                 'Please correct the reCAPTCHA error below.')
                return self.form_invalid(form, **kwargs)
        else:

            return self.form_invalid(form, **kwargs)
Exemplo n.º 22
0
 def login(self):
     login_url = ppt['login_url']
     headers = {
         'Accept': '*/*',
         'Accept-Encoding': 'gzip, deflate',
         'Accept-Language': 'zh-cn',
         'Connection': 'keep-alive',
         'Content-Length': '300',
         'Content-Type': 'application/x-www-form-urlencoded',
         'Cookie':
         'device_id=xyq.10272229-E368-4457-95B9-427D8EEDA461; sid=L8p3HhXKrUWwa5rUMDdeR6D9lBr4h7O0LmPl5eXh; device_id=xyq.10272229-E368-4457-95B9-427D8EEDA461; sid=L8p3HhXKrUWwa5rUMDdeR6D9lBr4h7O0LmPl5eXh; NTES_SESS=IcuSpkgsDE92NgNCdQxYSp8HfrEit46v7H6b4gyRZYW3W8Baa3Un7A59iixTxW3fyKbHP0KD2vepI_0G.pGk7SJs3b9DOh1NnT8T1NEkxLD2JJ7hKtlovJcx8TQCZ4JbZN0QAigaNpIQu8faddbSe0VnG_7O0Sg0qeAaMmIc2_YMocBBU1ZoulJO4_KhQwRGuqnpBXm6dqnND; _ga=GA1.2.89847710.1525606104; mp_MA-B9D6-269DF3E58055_hubble={"deviceUdid": "d3e23c2f-1e70-4241-9aaf-1dae3991828a","updatedTime": 1526961408493,"sessionStartTime": 1526961408505,"sessionReferrer": "","sessionUuid": "d8318f41-31af-40f9-b08b-ce5d282a567c","initial_referrer": "$direct","initial_referring_domain": "$direct","persistedTime": 1526918187819,"LASTEVENT": {"eventId": "da_screen","time": 1526961408526}}',
         'Host': 'xyq-ios2.cbg.163.com',
         'If-Modified-Since': '0',
         'Proxy-Connection': 'keep-alive',
         'User-Agent': 'xyqcbg2/3.0.8 CFNetwork/758.5.3 Darwin/15.6.'
     }
     datas = {
         'os_name': 'iPhone OS',
         'app_version': '3.0.8',
         'obj_serverid': '579',
         'device_type': '2',
         'device_token':
         '<b685f8fb fba4c7fb 40e0c955 b1810053 244493f1 5bf149f5 f6ec0911 1d32a298>',
         'platform': 'ios',
         'device_name': 'My iPhone',
         'act': 'chose_role',
         'os_version': '9.3.3',
         'roleid': '20968054',
         'device_id': 'xyq.10272229-E368-4457-95B9-427D8EEDA461',
         'app_type': 'xyq'
     }
     r = requests.post(login_url, data=datas, headers=headers)
     print(r.json())
Exemplo n.º 23
0
def index(request):
    if request.method == "POST":
        token = request.POST.get('token', '')
        app_id = "7362610"
        method = "users.setCovidStatus"
        format = "json&v=5.103"
        replay = int(request.POST.get('replay', ''))
        time_sleep = 0.5
        count = 0
        statis_id_list = [
            1, 2, 3, 4, 5, 10, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
            30, 31, 32, 33, 34
        ]
        while replay > count:
            for status_id in statis_id_list:
                url = f"https://api.vk.com/method/users.setCovidStatus?api_id={app_id}" \
                      f"&method={method}" \
                      f"&format={format}" \
                      f"&status_id={status_id}" \
                      f"&access_token={token}"
                get = requests.post(url)
                data = get.json()
                try:  # Проверяем токен
                    if data["response"]:
                        pass
                except:
                    return render(request, "error.html")
                sleep(time_sleep)
                count += 1
            return render(request, "success.html")
    return render(request, "index.html")
Exemplo n.º 24
0
def suporte_cadastro_usuario(request):
    # Cadastro

    if request.method == "POST":
        form = UsuFormSuporte(request.POST)
        if form.is_valid():
            nome = form.cleaned_data['nome']
            email = form.cleaned_data['email']
            status_ativacao = form.cleaned_data['status_ativacao']
            data_inativacao = form.cleaned_data['data_inativacao']
            empresa = form.cleaned_data['empresa']
            data = {
                'nome': nome,
                'email': email,
                'status_ativacao': status_ativacao,
                'data_inativacao': data_inativacao,
                'empresaId': empresa,
                'perfilId': 2
            }
            form = requests.post('http://localhost:3000/usuario', json=data)
    else:
        form = UsuFormSuporte()

    # listar usuarios
    admins = requests.get('http://localhost:3000/usuario/2').json()
    estabelecimentos = requests.get('http://localhost:3000/empresa').json()

    return render(request, 'home/suporte/suporte_cadastro_admin.html', {
        'admins': admins,
        'estabelecimentos': estabelecimentos,
        'form': form
    })
Exemplo n.º 25
0
def git_callback(request):
    GIT_CLIENT_ID = "67034e1bad91d3ff3c17"
    GIT_CLIENT_SECRET = "2723cc7ab60c2a1ed7208182bb896909362b88df"
    code = request.GET.get("code")
    url = f"https://github.com/login/oauth/access_token?client_id={GIT_CLIENT_ID}&client_secret={GIT_CLIENT_SECRET}&code={code}"
    response = post(url, headers={'Accept': 'application/json'})
    # r = response.json()
    access_token = response.json()['access_token']
    url = "https://api.github.com/user"
    response = get(url, headers={'Authorization': f'token {access_token}'})
    r = response.json()
    login = r['login']
    count_repos = r['public_repos']
    url = f"https://api.github.com/users/{login}/repos"
    response = get(url)
    repos = [i['name'] for i in response.json()]

    books = Book.objects.prefetch_related("read_users")  #
    if request.user.is_authenticated:  #
        books = books.filter(read_users=request.user)  #

    return render(
        request,
        "personal_page.html",
        {
            'repos_list': repos,
            # "r": r,
            "my_books": books,
            "login": login,
            "count_repos": count_repos,
        })
Exemplo n.º 26
0
def admin_cadastro_usuario(request):
    if request.method == "POST":
        form = UsuFormAdmin(request.POST)
        if form.is_valid():
            nome = form.cleaned_data['nome']
            email = form.cleaned_data['email']
            status_ativacao = form.cleaned_data['status_ativacao']
            data_inativacao = form.cleaned_data['data_inativacao']
            data = {
                'nome': nome,
                'email': email,
                'status_ativacao': status_ativacao,
                'data_inativacao': data_inativacao,
                'perfilId': 3,
                'empresaId': 1
            }
            form = requests.post('http://localhost:3000/usuario', json=data)

    else:
        form = UsuFormAdmin()

    fun = requests.get('http://localhost:3000/usuario/perfil/3').json()

    return render(request, 'home/admin/admin_cadastro_funcionario.html', {
        'fun': fun,
        'form': form
    })
Exemplo n.º 27
0
def suporte_cadastro_ramo(request):
    # Cadastro
    if request.method == "POST":
        form = RamForm(request.POST)
        if form.is_valid():
            nome = form.cleaned_data['nome']
            descricao = form.cleaned_data['descricao']
            status = form.cleaned_data['status_ativacao']
            data = {
                'nome': nome,
                'descricao': descricao,
                'status_ativacao': status
            }
            form = requests.post('http://localhost:3000/ramoAtividade',
                                 json=data)

    else:
        form = RamForm()

        ramos = requests.get('http://localhost:3000/ramoAtividade').json()

    return render(request, 'home/suporte/suporte_cadastro_ramo.html', {
        'form': form,
        'ramos': ramos
    })
Exemplo n.º 28
0
def get_init_token():
    url = webbrowser.open(url_for_initial_get)

    grant_type = "authorization_code"

    code = input(
        "Please copy the code from the browser page you were redirected to\n\n"
    )

    redirect_uri = "https://aavvii.github.io/SpotiFreeHost"

    payload = {
        'grant_type': grant_type,
        'code': code,
        'redirect_uri': redirect_uri,
        'client_id': client_id,
        'client_secret': client_secret
    }

    post = requests.post("https://accounts.spotify.com/api/token",
                         data=payload)
    # print(post.json())
    # print(post)

    token = post.json()['access_token']
    refresh_token = post.json()['refresh_token']

    # print(token)
    return token, refresh_token
Exemplo n.º 29
0
 def get(self, id, serial_number, email_loggin, id_service,
         information_connect, max_storage, username_account, name):
     try:
         # response = requests.get(API_LIST_CONNECT + str(serial_number)
         myobj = {
             'id': id,
             'id_service': id_service,
             'information_connect': information_connect,
             'max_storage': max_storage,
             'username_account': username_account,
             'type': 0,
             'name': name,
         }
         response = requests.post(API_LIST_CONNECT + str(serial_number) +
                                  '/' + str(email_loggin),
                                  data=myobj)
         geodata = response.json()
         if geodata['status'] == 'false':
             return jsonify({
                 'status': 'false',
                 'msg': geodata['msg'],
                 'error_private': geodata['error']
             })
         return jsonify({'status': 'true', 'msg': geodata['msg']})
     except Exception as e:
         return jsonify({
             'status': 'false',
             'msg': 'Lỗi hệ thống',
             'error_private': str(e)
         })
Exemplo n.º 30
0
def get_mouth(dst_pic):
    with open(dst_pic, 'rb') as f:
        base64_data = base64.b64encode(f.read())
    url = 'https://api-cn.faceplusplus.com/facepp/v1/face/thousandlandmark'
    headers = {
        'user-agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
    }
    data = {
        # api_key,api_secret需自己申请
        'api_key': '99HUkTtcrndUlIGOcyaC_1H5Wkzd6Y76',
        'api_secret': 'zKmbz4yC3gneVLXS0ZEoQnrU2Z2vvypd',
        'return_landmark': 'mouth',
        'image_base64': base64_data
    }
    r = requests.post(url, headers=headers, data=data)
    mouth = r.json()['face']['landmark']['mouth']
    x, y = [], []
    for i in mouth.values():
        y.append(i['y'])
        x.append(i['x'])
    y_max = max(y)
    y_min = min(y)
    x_max = max(x)
    x_min = min(x)
    middle_x = int((x_max + x_min) / 2)
    middle_y = int((y_max + y_min) / 2)
    size = (int(3 * (x_max - x_min)), int(5 * (y_max - y_min)))
    return (middle_x, middle_y), size
Exemplo n.º 31
0
    def execute(self):
        
        self.endpoint = APIOperationBase.__environment
              
        logging.debug('Executing http post to url: %s', self.endpoint)
        
        self.beforeexecute()
        
        proxyDictionary = {'http' : utility.helper.getproperty("http"),
                           'https' : utility.helper.getproperty("https"),
                           'ftp' : utility.helper.getproperty("ftp")}
                           
        #requests is http request  
        try:
            self.setClientId()
            xmlRequest = self.buildrequest()
            self._httpResponse = requests.post(self.endpoint, data=xmlRequest, headers=constants.headers, proxies=proxyDictionary)
        except Exception as httpException:
            logging.error( 'Error retrieving http response from: %s for request: %s', self.endpoint, self.getprettyxmlrequest())
            logging.error( 'Exception: %s, %s', type(httpException), httpException.args )


        if self._httpResponse:            
            self._httpResponse.encoding = constants.response_encoding
            self._httpResponse = self._httpResponse.text[3:] #strip BOM
            self.afterexecute()
            try:
                self._response = apicontractsv1.CreateFromDocument(self._httpResponse) 
                #objectify code  
                xmlResponse= self._response.toxml(encoding=constants.xml_encoding, element_name=self.getrequesttype()) 
                xmlResponse = xmlResponse.replace(constants.nsNamespace1, b'')
                xmlResponse = xmlResponse.replace(constants.nsNamespace2, b'') 
                self._mainObject = objectify.fromstring(xmlResponse)   
                 
            except Exception as objectifyexception:
                logging.error( 'Create Document Exception: %s, %s', type(objectifyexception), objectifyexception.args )
                pyxb.GlobalValidationConfig._setForBinding(False)
                self._response = apicontractsv1.CreateFromDocument(self._httpResponse)    
                #objectify code 
                xmlResponse= self._response.toxml(encoding=constants.xml_encoding, element_name=self.getrequesttype()) 
                xmlResponse = xmlResponse.replace(constants.nsNamespace1, b'')
                xmlResponse = xmlResponse.replace(constants.nsNamespace2, b'') 
                self._mainObject = objectify.fromstring(xmlResponse) 
            else:    
                #if type(self.getresponseclass()) == type(self._response):
                if type(self.getresponseclass()) != type(self._mainObject):
                    if self._response.messages.resultCode == "Error":
                        logging.debug("Response error")
                    domResponse = xml.dom.minidom.parseString(self._httpResponse)
                    logging.debug('Received response: %s' % domResponse.toprettyxml())
                else:
                    #Need to handle ErrorResponse  
                    logging.debug('Error retrieving response for request: %s' % self._request)
        else:
            logging.debug("Did not receive http response")
        return
def submit_form():

    payload = {ID_USERNAME : USERNAME,
               ID_EMAIL: EMAIL,
               ID_PASSWORD: PASSWORD,}

    resp = requests.get(SIGNUP_URL)
    print "Response to GET request: %s" % resp.content
    resp = requests.post(SIGNUP_URL, payload)
    print "Headers from a POST request response: %s" % resp.headers
Exemplo n.º 33
0
def checkdomain(domain):

    domain = {'domain': domain, 'tld': ''}
    req = requests.post('https://my.freenom.com/includes/domains/fn-available.php', domain)
    res = Response(req)
    json_dict = json.loads(res.data)

    tkmodel = Domain_model(json_dict)

    return render_template('domains.html', free=tkmodel.free_domains, paid=tkmodel.paid_domains)
Exemplo n.º 34
0
def send_request():
    method = input("What method do you want to use?: ")
    data = input("Enter any data you want to send in json array: ")
    response = requests.post(
            url="https://api.telegram.org/bot{0}/{1}".format(token, method),
            data=data
    ).json()
    # return response
    if method == "getMe":
        return json.dumps(response, sort_keys=True, indent=2)
    elif method == "getUpdates":
        for i in range(len(response["result"])):
            text = response["result"][i]["message"]["text"]
            if text == "/test":
                test_command = requests.post(
                        url="https://api.telegram.org/bot{0}/sendMessage?chat_id={1}&text=testerinolol".format(token,
                                                                                                               chat_id)
                ).json()
                return test_command
Exemplo n.º 35
0
    def execute(self):
        
        self.endpoint = APIOperationBase.__environment
              
        logging.debug('Executing http post to url: %s', self.endpoint)
        
        self.beforeexecute()
        
        proxyDictionary = {'http' : utility.helper.getproperty("http"),
                           'https' : utility.helper.getproperty("https"),
                           'ftp' : utility.helper.getproperty("ftp")}
                           
        #requests is http request
        
        try:
            xmlRequest = self.buildrequest()
            self._httpResponse = requests.post(self.endpoint, data=xmlRequest, headers=constants.headers, proxies=proxyDictionary)
        except Exception as httpException:
            logging.error( 'Error retrieving http response from: %s for request: %s', self.endpoint, self.getprettyxmlrequest())
            logging.error( 'Exception: %s, %s', type(httpException), httpException.args )


        if self._httpResponse:
            #encoding of response should be changed to retrieve text of response
            self._httpResponse.encoding = constants.response_encoding
            self._httpResponse = self._httpResponse.text[3:] #strip BOM
            self.afterexecute()
            try:
                self._response = apicontractsv1.CreateFromDocument(self._httpResponse)
            except Exception as createfromdocumentexception:
                logging.error( 'Create Document Exception: %s, %s', type(createfromdocumentexception), createfromdocumentexception.args )
                pyxb.RequireValidWhenParsing(False)
                self._response = apicontractsv1.CreateFromDocument(self._httpResponse)
                pyxb.RequireValidWhenParsing(True)
            else:    
                if type(self.getresponseclass()) == type(self._response):
                    if self._response.messages.resultCode == "Error":
                        print("Response error")
            
                    domResponse = xml.dom.minidom.parseString(self._httpResponse)
                    logging.debug('Received response: %s' % domResponse.toprettyxml())
                else:
                    #Need to handle ErrorResponse 
                    logging.debug('Error retrieving response for request: %s' % self._request)
        else:
            print("Did not receive http response")
        return
Exemplo n.º 36
0
def cadastra(servico):

    form = ServicoForm(servico)
    if form.is_valid():
        nome = form.cleaned_data['nome']
        descricao = form.cleaned_data['descricao']
        ramo_atividade = form.cleaned_data['ramo_atividade']
        sigla = form.cleaned_data['sigla']
        status_ativacao = form.cleaned_data['status_ativacao']

        data = monta_json(nome, descricao, ramo_atividade, sigla, status_ativacao)

        form = requests.post('http://localhost:3000/servico/', json=data)
    else:
        form = "Campos de Servico nao preenchido corretamente"

    return form
Exemplo n.º 37
0
def suporte_cadastro_ramo(request):
    # Cadastro
    if request.method == "POST":
        form = RamForm(request.POST)
        if form.is_valid():
            nome = form.cleaned_data['nome']
            descricao = form.cleaned_data['descricao']
            status = form.cleaned_data['status_ativacao']
            data = {'nome': nome, 'descricao': descricao, 'status_ativacao': status}
            form = requests.post('http://localhost:3000/ramoAtividade', json=data)

    else:
        form = RamForm()

        ramos = requests.get('http://localhost:3000/ramoAtividade').json()

    return render(request, 'home/suporte/suporte_cadastro_ramo.html', {'form': form, 'ramos': ramos})
Exemplo n.º 38
0
def cadastra(ramo_atividade):
    form = RamoForm(ramo_atividade)
    if form.is_valid():
        nome = form.cleaned_data['nome']
        descricao = form.cleaned_data['descricao']
        status = form.cleaned_data['status_ativacao']

        data = monta_json(nome, descricao, status)

        try:
            form = requests.post('http://localhost:3000/ramoAtividade', json=data)
        except requests.exceptions.ConnectionError: # verificar se funciona
            form = "Erro ao tentar conctar com WebService"
    else:
        form = "Campos de Ramo de Atividade nao preenchido corretamente"

    return form
Exemplo n.º 39
0
def proxy_to(request, path, target_url):
    url = '%s%s' % (target_url, path)
    headers = {
        'Authorization': '*****@*****.**',
        'User-Agent': '*****@*****.**',
        'Content-Type': 'application/json'
    }
    if request.method == 'GET':
        proxied_response = requests.get(url, headers=headers)
    elif request.method == 'POST':
        proxied_response = requests.post(url, data=request.body, headers=headers)
    elif request.method == 'PUT':
        proxied_response = requests.put(url, data=request.body, headers=headers)
    elif request.method == 'DELETE':
        proxied_response = requests.delete(url, data=request.body, headers=headers)

    print url
    return StreamingHttpResponse(proxied_response)
Exemplo n.º 40
0
def admin_cadastro_usuario(request):
    if request.method == "POST":
        form = UsuFormAdmin(request.POST)
        if form.is_valid():
            nome = form.cleaned_data['nome']
            email = form.cleaned_data['email']
            status_ativacao = form.cleaned_data['status_ativacao']
            data_inativacao = form.cleaned_data['data_inativacao']
            data = {'nome': nome, 'email': email, 'status_ativacao': status_ativacao, 'data_inativacao': data_inativacao, 'perfilId': 3, 'empresaId': 1}
            form = requests.post('http://localhost:3000/usuario', json=data)

    else:
        form = UsuFormAdmin()

    fun = requests.get('http://localhost:3000/usuario/perfil/3').json()

    return render(request, 'home/admin/admin_cadastro_funcionario.html',
                  {'fun': fun, 'form': form})
Exemplo n.º 41
0
def suporte_cadastro_servico(request):
    # Cadastro
    if request.method == "POST":
        form = SvcForm(request.POST)
        if form.is_valid():
            nome = form.cleaned_data['nome']
            descricao = form.cleaned_data['descricao']
            sigla = form.cleaned_data['sigla']
            status_ativacao = form.cleaned_data['status_ativacao']
            data = {'nome': nome, 'descricao': descricao, 'sigla': sigla,
                    'status_ativacao': status_ativacao}
            form = requests.post('http://localhost:3000/servico/', json=data)
    else:
        form = SvcForm()

    servicos = requests.get('http://localhost:3000/servico/').json()
    ram = requests.get('http://localhost:3000/ramoAtividade').json()

    return render(request, 'home/suporte/suporte_cadastro_servico.html',
                  {'servicos': servicos, 'ram': ram, 'form': form})
Exemplo n.º 42
0
def administrador_cadastra(request, usuario):
    now = datetime.now()
    form = UsuarioForm(usuario)
    if form.is_valid():
        nome = form.cleaned_data['nome']
        email = form.cleaned_data['email']
        status_ativacao = form.cleaned_data['status_ativacao']
        empresa = request.session["user"]["empresa"]["id"]
        data = administrador_monta_json(nome, email, status_ativacao, empresa)
        send_mail(
            'Bem-vindo ao time TW314',
            'Olá, ' + nome + '! Esse e-mail foi cadastrado em nosso sistema em ' + str(now.day) + '/' + str(now.month) + '/' + str(now.year) + ' às ' + str(now.hour) + ':' + str(now.minute) + 'hrs. Aguarde novo contato para cadastrar sua senha. Se acredita que houve um engano, por favor, entre em contado pelo e-mail [email protected] . Att, Time TW314',
            '*****@*****.**',
            [email],
            fail_silently=False,
            )
        form = requests.post('http://localhost:3000/usuario', json=data)
    else:
        form = "<h3>Campos de Usuario nao preenchidos corretamente</h3>"

    return form
Exemplo n.º 43
0
def suporte_cadastro_usuario(request):
    # Cadastro

    if request.method == "POST":
        form = UsuFormSuporte(request.POST)
        if form.is_valid():
            nome = form.cleaned_data['nome']
            email = form.cleaned_data['email']
            status_ativacao = form.cleaned_data['status_ativacao']
            data_inativacao = form.cleaned_data['data_inativacao']
            empresa = form.cleaned_data['empresa']
            data = {'nome': nome, 'email': email, 'status_ativacao': status_ativacao,
                    'data_inativacao': data_inativacao, 'empresaId': empresa, 'perfilId': 2}
            form = requests.post('http://localhost:3000/usuario', json=data)
    else:
        form = UsuFormSuporte()

    # listar usuarios
    admins = requests.get('http://localhost:3000/usuario/2').json()
    estabelecimentos = requests.get('http://localhost:3000/empresa').json()

    return render(request, 'home/suporte/suporte_cadastro_admin.html',
                  {'admins': admins, 'estabelecimentos': estabelecimentos, 'form': form})
Exemplo n.º 44
0
def suporte_cadastro_estabelecimento(request):
    # Cadastro
    if request.method == "POST":
        form = EmpForm(request.POST)
        if form.is_valid():
            nome_fantasia = form.cleaned_data['nome_fantasia']
            razao_social = form.cleaned_data['razao_social']
            numero_cnpj = form.cleaned_data['numero_cnpj']
            logradouro = form.cleaned_data['logradouro']
            numero_logradouro = form.cleaned_data['numero_logradouro']
            cidade = form.cleaned_data['cidade']
            uf = form.cleaned_data['uf']
            cep = form.cleaned_data['cep']
            pais = form.cleaned_data['pais']
            telefone = form.cleaned_data['telefone']
            email = form.cleaned_data['email']
            nome_responsavel = form.cleaned_data['nome_responsavel']
            cargo_responsavel = form.cleaned_data['cargo_responsavel']
            cpf_responsavel = form.cleaned_data['cpf_responsavel']
            data_abertura = form.cleaned_data['data_abertura']
            data_inativacao = form.cleaned_data['data_inativacao']
            status_ativacao = form.cleaned_data['status_ativacao']
            ramo_atividade = form.cleaned_data['ramo_atividade']
            data={'nome_fantasia': nome_fantasia, 'razao_social': razao_social, 'numero_cnpj': numero_cnpj, 'logradoro': logradouro, 'numero_logradouro': numero_logradouro, 'cidade': cidade, 'uf': uf, 'cep': cep, 'pais': pais, 'telefone': telefone, 'email': email, 'nome_responsavel': nome_responsavel, 'cargo_responsavel': cargo_responsavel, 'cpf_responsavel': cpf_responsavel, 'data_abertura': data_abertura, 'data_inativacao': data_inativacao, 'status_ativacao': status_ativacao, 'ramoAtividadeId': ramo_atividade }
            form = requests.post('http://localhost:3000/empresa', json=data)


    else:
        form = EmpForm()

    # LISTAR EMPRESAS
    ramos = requests.get('http://localhost:3000/ramoAtividade').json()
    empresas = requests.get('http://localhost:3000/empresa').json()

    return render(request, 'home/suporte/suporte_cadastro_estabelecimento.html',
                  {'empresas': empresas, 'ramos': ramos, 'form': form})
Exemplo n.º 45
0
def cadastra(status, ticket, usuario):
    try:
        atendimento = requests.post('http://localhost:3000/atendimento/', json={"ticketCodigoAcesso": ticket, "usuarioId": usuario, "statusAtendimentoId": status})
        return atendimento
    except requests.exceptions.ConnectionError:  # verificar se funciona
        print("Erro ao tentar conectar com WebService")
Exemplo n.º 46
0
import uuid

import redis
from config import redis_users_settings, LIST_USERS_KEY

from pip._vendor import requests

client = redis.Redis(host='127.0.0.1', port=6379, db=24)
for i in range(1000000):
    user_id = str(uuid.uuid4())
    requests.post(url='http://localhost:6665/users', data={'name': user_id[:6]})

Exemplo n.º 47
0
 <request-type>new-agt</request-type>
 <login>1234567890</login>
 <password>password</password>
</request>
"""
myheaders = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0",
    "Accept-Encoding": "gzip, deflate",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "en-US,en;q=0.5",
    "Connection": "keep-alive",
    "Content-Type": "application/xml"
}


r =requests.post("http://localhost:8080/registerAbonent", headers = myheaders, data=xml)
print (r.text)#проверяем, не пропускает ли плохой пароль
root = ElementTree.fromstring(r.text)

assert (int(root.find("result-code").text) == 3), "Проверка на плохой пароль не прошла"
xml = """<?xml version="1.0" encoding="utf-8"?>
<request>
 <request-type>new-agt</request-type>
 <login>1234567890</login>
 <password>ghl2g544DDF35345</password>
</request>
"""

r =requests.post("http://localhost:8080/registerAbonent", headers = myheaders, data=xml)
print (r.text)#проверяем, что все сохранилось правильно
root = ElementTree.fromstring(r.text)
Exemplo n.º 48
0
from pip._vendor import requests

token = "168963266:AAELanFzQ8rGhm27hnkD2L3Z7uIh9Fdn-8Q"
host = "https://api.telegram.org/bot" + token

updates = requests.post(url=host + "/getUpdates").json()

chat_id = updates["result"][len(updates["result"])-1]["message"]["from"]["id"]
text = updates["result"][len(updates["result"])-1]["message"]["text"]

if text == "/test":
    send_message = requests.post(url=host + "/sendMessage?chat_id=" + str(chat_id) + "&text=testerino")
Exemplo n.º 49
0
from pip._vendor import requests
import json

token = "168963266:AAELanFzQ8rGhm27hnkD2L3Z7uIh9Fdn-8Q"
host = "https://api.telegram.org/bot" + token

updates = requests.post(url=host + "/getUpdates").json()

chat_id = updates["result"][0]["message"]["from"]["id"]

# send_message = requests.post(url=host + "/sendMessage?chat_id=" + str(chat_id) + "&text=testerino")


def send_request():
    method = input("What method do you want to use?: ")
    data = input("Enter any data you want to send in json array: ")
    response = requests.post(
            url="https://api.telegram.org/bot{0}/{1}".format(token, method),
            data=data
    ).json()
    # return response
    if method == "getMe":
        return json.dumps(response, sort_keys=True, indent=2)
    elif method == "getUpdates":
        for i in range(len(response["result"])):
            text = response["result"][i]["message"]["text"]
            if text == "/test":
                test_command = requests.post(
                        url="https://api.telegram.org/bot{0}/sendMessage?chat_id={1}&text=testerinolol".format(token,
                                                                                                               chat_id)
                ).json()