Not updating my google sheet just getting: { "sheet1": { "id": 2 } }? - python

I've posted questions here before for this code, but every time we get past one error I get a new one. I'm not getting an error this time but it's still not updating my google sheet is there an error I'm missing or is this a problem with the Sheety API? Also, I'm coding on PyCharm using a Mac🖥 and the code is from lecture 333, of 100 days of code by Dr. Angela Yu. (don't know if that helps)
#------------New_code------------#
import requests
from datetime import datetime
GENDER = "male"
WEIGHT_KG = 58.740212
HEIGHT_CM = 177.8
AGE = 13
APP_ID = "be2*****"
API_KEY = "4fa82da*************************"
exercise_endpoint = "https://trackapi.nutritionix.com/v2/natural/exercise"
sheet_endpoint = "https://api.sheety.co/0a5644021c9c3815973ccd3f25595467/myWorkouts/sheet1"
exercise_text = input("Tell me which exercises you did: ")
headers = {
"x-app-id": APP_ID,
"x-app-key": API_KEY,
}
parameters = {
"query": exercise_text,
"gender": GENDER,
"weight_kg": WEIGHT_KG,
"height_cm": HEIGHT_CM,
"age": AGE
}
response = requests.post(exercise_endpoint, json=parameters, headers=headers)
result = response.json()
today_date = datetime.now().strftime("%d/%m/%Y")
now_time = datetime.now().strftime("%X")
bearer_headers = {
"Authorization": f"Bearer {'TOKEN'}"
}
for exercise in result["exercises"]:
sheet_inputs = {
"workout": {
"date": today_date,
"time": now_time,
"exercise": exercise["name"].title(),
"duration": exercise["duration_min"],
"calories": exercise["nf_calories"]
}
}
sheet_response = requests.post(sheet_endpoint, json={"sheet1": sheet_inputs}, headers=bearer_headers)
print(sheet_response.text)
#------------New_output------------#
Tell me which exercises you did: (I entered: i ran 3 miles)
{
"sheet1": {
"id": 2
}
}
Process finished with exit code 0

Related

Adding variables together from 1 post request (python)

I have some code, it works as expected, but im having a difficult time trying to add my global_criticalvulnerabilities to a master variable, that adds up ALL post request responses
from logging import critical
from unittest import result
import requests, json
import requests
import pandas as pd
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json;charset=UTF-8',
'Authorization': 'Basic auth=='
}
payload = {
"match" : "all",
"filters" : [
{"field": "site-id",
"operator": "in",
"values": [
"22"]},
{"field": "owner-tag",
"operator": "contains",
"value":"DESKTOP_SUPPORT"},
{"field": "operating-system",
"operator": "contains",
"value":"microsoft"},
{"field": "vulnerability-category",
"operator": "does-not-contain",
"value":"microsoft_patch"},]}
global_CritiicalVulnerabilities1 = ""
global_CritiicalVulnerabilities = ""
global_SevereVulnerabilities = ""
global_ModerateVulnerabilities = ""
if global_CritiicalVulnerabilities == 0: #if nothing then continuely add up each criticalvuln from each post request/response
for page in range(1,249):
url1 = 'https://url:3780/api/3/assets/search?size=2&page=%s'%page
print(url1)
response = requests.post(url1, headers=headers, json=payload, verify=False)
json_response = response.json()
vulnerabilities = []
resources = json_response['resources']
for d in resources:
if 'vulnerabilities' in d:
vulnerabilities.append(d['vulnerabilities'])
criticalVuln = sum(x.get('critical', 0) for x in vulnerabilities)
print(vulnerabilities)
criticalVuln = str(criticalVuln)
global_CritiicalVulnerabilities1 = criticalVuln + criticalVuln
print(global_CritiicalVulnerabilities)
print("The grand total Critical Vuln: " + global_CritiicalVulnerabilities)
#print("The grand total Severe Vuln: " + totalSevere)
#print("The grand total Moderate Vuln: " + totalModerate)
Could someone help guide me in the direction i should go? I dont really want the answer right away, trying to learn and understand how i should be thinking like a computer...
im trying to add up criticalVuln to itself so it has the grand total of every critical Vulnerability
i tried this as well, and its not doing what i want it to do

how to use only strings to pull json data

So I keep running into a issue where json is asking to use a int to find pieces of data in a json response. Below is the code that works though the issue is i want to print every 'name' in the json though id have to change the [0] to 1 and then 2 ect. I tried to increment it though that ran into issue too. This could be just me overlooking something but let me know, thanks.
def BaseTesting(TarLink):
PayloadToSend = {
}
HeadersToSend = { # make sure to change your token at least once every 30 mins
'authorization': '',
'user-agent': ''
}
ReqForFriends = requests.post(TarLink, headers=HeadersToSend, data=PayloadToSend).text
LoadedJSONData = json.loads(ReqForFriends)
print(LoadedJSONData['friends'][0]['name'])
BaseTesting(TarLink="")
JSON
{
"friends":[
{
"name":"test1",
"user_id":"1132",
"type":2,
"display":"true",
},
{
"name":"test2",
"user_id":"2341",
"type":1,
"display":"true",
},
{
"name":"test3",
"user_id":"1234",
"type":2,
"display":"true",
},
}
it seems to work properly
LoadedJSONData = {
"friends":[
{
"name":"test1",
"user_id":"1132",
"type":2,
"display":"true",
},
{
"name":"test2",
"user_id":"2341",
"type":1,
"display":"true",
},
{
"name":"test3",
"user_id":"1234",
"type":2,
"display":"true",
},
]
}
for i in range(0,3):
print(LoadedJSONData['friends'][i]['name']) #test1 test2 test3

How would I get my response to the Google Assistant via Dialogflow, Actions SDK, Python, etc

I am trying to get my reply to the Google assistant as a string to search it through a Google spreadsheet and return additional information about it. Specifically, I have a Google spreadsheet with two columns, one being for the name of a thing, and another for my rating of it. I'm using ngrok and Flask to get my script's response online. The two parts I'm struggling with are...
(1) Getting my requested thing into the program.
(2) Switching the url of the webhook and/or changing the webhook so that the system can output the final result.
I am a beginner so I'm probably misusing a few terms here but anyways my code is below. I put a bunch of underscores in the places where I thought sensitive information was.
action.json >>
"actions": [
{
"description": "Welcome Intent",
"name": "MAIN",
"fulfillment": {
"conversationName": "jdii ratings"
},
"intent": {
"name": "actions.intent.MAIN",
"trigger": {
"queryPatterns": [
"What did I rate $Test:text",
"Look up $Test:text on my ratings spreadsheet"
]
},
"parameters": [
{
"name": "text",
"type": "Test"
}
]
}
}
],
"conversations": {
"jdii ratings": {
"name": "jdii ratings",
"url": "<_________>",
"fulfillmentApiVersion": 2
}
}
}
program.py >>
import random
import types
import gspread
from flask import Flask
from google.cloud import dialogflow_v2
from oauth2client.service_account import ServiceAccountCredentials
app = Flask(__name__)
wanted_thingy = "Squirt"
def get_requested_thingy_rating(requested_thingy_name):
scopes = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
credentials = ServiceAccountCredentials.from_json_keyfile_name("_______.json", scopes)
file = gspread.authorize(credentials)
sheet = file.open("JDII Ratings API")
requested_thingy_rating_final = 0.0
if not isinstance(requested_thingy_name, types.NoneType):
sheet = sheet.sheet1
thingy_list = sheet.col_values(1)
ratings_list = sheet.col_values(2)
requested_thingy_rating = 0.0
if requested_thingy_name in thingy_list:
thingy_pos = thingy_list.index(requested_thingy_name)
requested_thingy_rating = ratings_list[thingy_pos]
requested_thingy_rating_final = str(requested_thingy_rating)
# split_string = ready_string.split('\'')
# requested_thingy_rating_final = split_string[1]
print(requested_thingy_rating_final)
return requested_thingy_rating_final
#app.route("/start", methods=['POST', 'GET', 'PUT'])
def main():
response = {
"expectUserResponse": True,
"expectedInputs": [
{
"inputPrompt": {
"richInitialPrompt": {
"items": [
{
"simpleResponse": {
"textToSpeech": "What would you like to look up?",
"displayText": "What would you like to look up?"
}
}
]
}
},
"possibleIntents": [
{
"intent": "actions.intent.TEXT"
}
]
}
]
}
response_text = json.dumps(response)
return response_text
#app.route("/webhook", methods=['POST', 'GET', 'PUT'])
def main2():
global wanted_thingy
wanted_thingy_final = str(wanted_thingy)
wanted_thingy_rating = get_requested_thingy_rating(wanted_thingy_final)
print(wanted_thingy)
string = f"You rated {wanted_thingy} a {wanted_thingy_rating} out of ten."
response2 = {
"expectUserResponse": False,
"finalResponse": {
"richResponse": {
"items": [
{
"simpleResponse": {
'ssml': f'<speak>{string}</speak>'
}
}
]
}
}
}
response_text = json.dumps(response2)
return response_text
app.run()

TypeError when trying to set a DB value

I'm trying to get my Flask server to update to a Mongo Atlas DB on request. When a request is passed with the required arguments, it will post to a Discord webhook then attempt to update DB values.
Example: Going to https://(redacted for privacy)/(redacted for privacy)?iid=123&username=wow&price=22 with JUST the webhook code (doesn't touch DB) will do this:
(sent to discord webhook) and give a success message (outputs as 200 in the console).
But when I enable the DB code, the same link will through a 500 error. Anything I can do? The console outputs as;
balance = mycol.find_one({"UserID": uid})['balance']
TypeError: 'NoneType' object is not subscriptable
I don't understand why this won't work. Here's the code that works, but only posts to the webhook (commented stuff is DB related):
#balance = mycol.find_one({"UserID": uid})['balance']
#res = mycol.find_one({"UserID": uid})
#newvalues = { "$set": { "UserID": uid, "balance": int(balance) + int(cashback_amt)} }
#mycol.update_one(res, newvalues)
img_url = f"https://www.roblox.com/bust-thumbnail/image?userId={uid}&width=420&height=420&format=png"
data = {
"content" : "**New purchase!**",
"username" : "robate"
}
data["embeds"] = [
{
"description" : f"**ItemID**: `{item_id}`\n**Item Price**: `{price}`\n**Item Cashback**: `{cashback_amt}`",
"title" : "New purchase made",
"color": 65311,
"thumbnail": {"url": img_url}
}
]
result = requests.post(purclog, json = data)
return jsonify({"res": True})
And the non-working DB included code:
balance = mycol.find_one({"UserID": uid})['balance']
res = mycol.find_one({"UserID": uid})
newvalues = { "$set": { "UserID": uid, "balance": int(balance) + int(cashback_amt)} }
mycol.update_one(res, newvalues)
img_url = f"https://www.roblox.com/bust-thumbnail/image?userId={uid}&width=420&height=420&format=png"
data = {
"content" : "**New purchase!**",
"username" : "robate"
}
data["embeds"] = [
{
"description" : f"**ItemID**: `{item_id}`\n**Item Price**: `{price}`\n**Item Cashback**: `{cashback_amt}`",
"title" : "New purchase made",
"color": 65311,
"thumbnail": {"url": img_url}
}
]
result = requests.post(purclog, json = data)
return jsonify({"res": True})
Any help is severely appreciated. Have a good day!
EDIT: The UserID is defined here:
try:
uid = requests.get(f"https://api.roblox.com/users/get-by-username?username={username}").json()['Id']
except:
return
balance = mycol.find_one({"UserID": uid})['balance']

Using timestamp, json e python

This script makes the requisition fligts google every 1h, using time.sleep (3600) and generates a txt file with all phrases
he rolled over a day and a half.
I want do this properly using TIMESTAMP. Someone can help me?
import urllib
import urllib2
import json
import time
while 1:
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyA3758yM14aTX7aI9_v5AvKI2X1m56HszI"
code = {
"request": {
"passengers": {
"adultCount": 1,
"childCount": 1
},
"slice": [
{
"origin": "SSA",
"destination": "GRU",
"date": "2015-06-19",
"permittedDepartureTime":
{
"kind": "qpxexpress#timeOfDayRange",
"earliestTime": "22:00",
"latestTime": "23:00"
}
},
{
"origin": "GRU",
"destination": "SSA",
"date": "2015-06-30",
"permittedDepartureTime":
{
"kind": "qpxexpress#timeOfDayRange",
"earliestTime": "05:00",
"latestTime": "12:00"
}
}
],
"solutions": 3
}
}
#hoje = "%s" % (time.strftime("%Y_%m_%d"))
jsonreq = json.dumps(code, encoding = 'utf-8')
req = urllib2.Request(url, jsonreq, {'Content-Type': 'application/json'})
flight = urllib2.urlopen(req)
response = flight.read()
flight.close()
#print(response)
print("----------------")
texto=(response)
v_file= open("ssaGRU.json" ,"a")
#hora = time.strftime("%H:%M:%S %Z")
v_file.write(texto)
#v_file.write("[%s] Hora do json.\r\n" % (hora))
v_file.close()
time.sleep(15)
current_time = time.strftime("%H:%M", time.localtime())
v_file = open("ssaGRU.json", "a")
v_file.write(str(current_time) + ': ')
v_file.write(texto + '\n')
v_file.close()
This will print your current time before every line inputted, and adds a an empty line at the end so your data from different times doesn't stay on one line.
You can also add %m.%d.%y to current_time if you need. In case texto isn't a string, make sure you add str(texto).

Categories