def food_jokes(): api = sp.API("356a7bee2cc2417b9b37ea217d35247b") response = api.get_a_random_food_joke() data = response.json() return data['text'] # # food_jokes()
def get_key(self, key): """ Gets the api key and sets it to active :return: None """ self.api = sp.API(key) self.apiKey_url = "?apiKey=" + self.key self.active = True
def getFoodWords(text): api_key = os.environ['SPOON_API_KEY'] api = sp.API(api_key) response = api.detect_food_in_text(self.description) data = response.json() foodwords= [] for a in data['annotations']: foodwords.append(a['annotation']) return foodwords
def get_data(maxcal, mincal, ingredients=None): """ Recieves 50 recipes in given colories range that contain complementary included ingredient, then writes down data into file and returns file name """ api = spoonacular.API('738087f315ba454490f58e521168dcb7') if ingredients: info = api.search_recipes_complex('', number=20, maxCalories=maxcal,\ minCalories=mincal, includeIngredients=ingredients, fillIngredients=True,\ addRecipeNutrition=True, ignorePantry=True) else: info = api.search_recipes_complex('', number=20, maxCalories=maxcal,\ minCalories=mincal, fillIngredients=True, addRecipeNutrition=True,\ ignorePantry=True) data = info.json() js = json.dumps(data, indent=2) with open(f'work/resources{maxcal}-{mincal}.txt', mode='w') as result: result.write(js) return f'work/resources{maxcal}-{mincal}.txt'
def searchRecipes(query, extended=True): #initilize api_key and spoonacular object api_key = os.environ['SPOON_API_KEY'] api = sp.API(api_key) #request recipes from spoonacular using query if query=="random": #get one random recipe response = api.get_random_recipes(True,1) data = response.json() recipes = data["recipes"] else: #get recipes based on query response = api.search_recipes_complex(query) data = response.json() recipes = data["results"] #extract recipe id(s) from json response ids="" for rec in recipes: ids+=""+str(rec["id"])+"," #use id(s) to capture a more detailed json response about a recipe response = api.get_recipe_information_bulk(ids) data = response.json() #create a list of recipe objects that are intialized by the json objects in data recipes = [] #check if search failed try: if data['status'] == 'failure': return recipes #if there is no status then it was succesful, create recipes except: for recipeJson in data: recipes.append(Recipe(recipeJson,extended)) return recipes
from multiprocessing import Process import time from datetime import datetime import smtplib import storage import spoonacular as sp # Start Spoonacular API https://github.com/johnwmillr/SpoonacularAPI # Dashboard to view usage: https://spoonacular.com/food-api/console#Dashboard sp_api = sp.API(storage.SPOONACULAR_API_KEY) #### Functions that allow for CLI interface # Function that updates an item in the database def update_item( food, cmd ): # Asks name of item to update (TODO: Parse information from initial command and ask remaining info) item_name = input("Name: ") # Gets appropriate item r_item = food.find_one({"name": item_name}) if r_item is not None: # Asks for quantity (TODO: Ask to update other fields) quantity = input("Quantity: ") if int(quantity) == 0: remove_item(food, "remove", item_name) else: food.update_one({"_id": r_item.get("_id")}, {"$set": {"quantity" : quantity }}) return 1
import spoonacular as sp import pandas as pd from collections import defaultdict ID = 0 MISSING = 4 PRICE = 5 VEGETARIAN, VEGAN, GLUTEN, DAIRY = 2, 3, 4, 5 FILTERS_DICT = {'vegetarian': VEGETARIAN, 'vegan': VEGAN, 'gluten_free': GLUTEN, 'dairy_free': DAIRY, 'None': None} DATA = ['id', 'recipe_name', 'recipe_image', 'nb_missed_ing', 'missed_ing', 'missing_prices', 'total_missing', 'instructions', 'price_per_serving', 'vegetarian', 'vegan', 'gluten_free', 'dairy_free'] #foogoo = sp.API("18b4d68fbd11492f8ac5fd4c771d2b44") KEY="2ffbb1fbe2574e1582c693a246614403" foogoo = sp.API(KEY) def get_recipe(list_ing): """Takes a list of ingredients as inputs. Returns a list of recipe ids, recipe names, number of missing ingredients, and the missing ingredients. """ response = foogoo.search_recipes_by_ingredients(list_ing) data = response.json() recipe_name = [data[i]["title"] for i in range(len(data))] recipe_id = [data[i]["id"] for i in range(len(data))] nb_missed_ing = [data[i]["missedIngredientCount"] for i in range(len(data))] missed_ing = [[el['name'] for el in data[i]['missedIngredients']] for i in range(len(data))] recipe_images = [data[i]['image'] for i in range(len(data))] return list(zip(recipe_id, recipe_name, recipe_images, nb_missed_ing, missed_ing))
import re import en_core_web_md import nltk import pytesseract import spoonacular as sp from nltk.corpus import brown from PIL import Image brown = brown.words(categories=brown.categories()) nlp = en_core_web_md.load() foogoo = sp.API("18b4d68fbd11492f8ac5fd4c771d2b44") def preprocess(text): """ Preprocess text in different way to use in the get_ingredient_receipt function to amplify recognition input : text output : preprocessed text """ text = re.sub(r'[0-9]', '', text) text = re.sub(r'[\@\.\!\?\:\,\"\/\\\#\%\[\]\^\_\&\'\(\)\+\-\|\~\;\=\^\*]', '', text) tokens_text = nltk.word_tokenize(text) new_string = [] for word in tokens_text: if word in brown or len(word) > 2: new_string.append(word) return " ".join(new_string) def get_ingredient_receipt(img_path):
import spoonacular as sp import json from pandas.io.json import json_normalize import pandas as pd import pathlib #API Key api = sp.API('a3dc0c4c374149b29dfba84a54dec14c') #zomato api key: 760e6dfad78b661b5a418129adbdb04c #Output path setup parent = pathlib.Path.cwd() / 'RecipeScraping' / 'Spoonacular' outputpath = parent / 'spoonacular_output.json' csvpath = parent / 'spoondata_mediterranean.csv' #API Query Settings query = '' number = 10 sort = 'popularity' offset = 10 cuisine = 'mediterranean' #Calling the API, sending results to JSON file and interpreting into dataframe response = api.search_recipes_complex(query, sort = sort,\ sortDirection = 'desc', number = number, addRecipeInformation = True,\ fillIngredients = True, cuisine = cuisine, offset = offset) data = response.json() outputfile = open(outputpath, 'w') json.dump(data, outputfile, indent=4) outputfile.close() spoondata = json_normalize(data['results'])
import spoonacular as sp api = sp.API("19fb5e376e2647d78ec112501cb0c3f2") # Parse an ingredient response = api.parse_ingredients("3.5 cups King Arthur flour", servings=1) data = response.json() print(data[0]['name']) #>>>"flour" # Detect text for mentions of food response = api.detect_food_in_text("I really want a cheeseburger.") data = response.json() print(data['annotations'][0]) #>>>{"annotation": "cheeseburger", "tag":"dish"} # Get a random food joke response = api.get_a_random_food_joke() data = response.json() print(data['text']) #>>>"People are a lot less judgy when you say you ate an 'avocado salad' instead of a bowl of guacamole."
from flask import Flask, request, jsonify, Blueprint import urllib.request, json import ssl import spoonacular as sp from flaskr.model.Food import Food #import model.Food as Food api = sp.API("1d3e932738da4cbf928deb8be3c96629") ssl._create_default_https_context = ssl._create_unverified_context foodSearch_page = Blueprint('foodSearch_page', __name__, template_folder='templates') @foodSearch_page.route("/home/food", methods=['POST']) def foodInfo(): data = request.get_json() food_name = data['body'] response = api.guess_nutrition_by_dish_name(food_name) food_dict = response.json() if 'message' in food_dict: return jsonify({"state": "Not enough data for an informed guess."}) food_info = Food(food_dict) list = [ food_info.food_calories, food_info.food_calories_range, food_info.food_protein, food_info.food_protein_range, food_info.food_fat, food_info.food_fat_range, food_info.food_carbs, food_info.food_carbs_range ]
from sklearn.metrics.pairwise import cosine_similarity from xml.etree import ElementTree as ET import tensorflow as tf from tensorflow.keras import models, backend, layers import urllib.request import numpy import cv2 kern = aiml.Kernel() kern.setTextEncoding(None) kern.bootstrap(learnFiles="chatbot/mybot-basic.xml") model = models.load_model("cnn/model.h5") APIkey = "13ffaf56553e48faab0c6ce7762f2e1c" spoon_api = sp.API(APIkey) print("Welcome to food bot") patterns = [] tree = ET.parse("chatbot/mybot-basic.xml") all_pattern = tree.findall("*/pattern") for pattern in all_pattern: if "*" not in pattern.text: patterns.append(pattern.text) classnames = [] with open("cnn/food41/meta/meta/classes.txt") as reader: for line in reader: classnames.append(line.strip())
"""CRUD operations.""" import os from random import choice from model import db, connect_to_db, Ingredient, Inventory, Recipe, MealPlan import spoonacular as sp api = sp.API(os.environ['apiKey']) def add_ingredient(name, location): """add ingredient""" ingredient = Ingredient(name=name, location=location) db.session.add(ingredient) db.session.commit() return ingredient def add_recipe(name, ingredients, url, cook_time="n/a", image="none"): """add recipes with required ingredient(s)""" recipe = Recipe(name=name, ingredients=ingredients, url=url, cook_time=cook_time, image=image) db.session.add(recipe) db.session.commit() return recipe
import os import requests import json import spoonacular as sp # set keys for authentication # Hidden API key guide: https://towardsdatascience.com/how-to-hide-your-api-keys-in-python-fb2e1a61b0a0 API_SECRET = os.environ.get('SECRET_KEY') api = sp.API(API_SECRET) api_root = 'https://api.spoonacular.com/' headers = {'Content-Type':'application/json'} # API authentication class search_API(): def __init__(self, api_key): """ Spoonacular API call :param api_key: key prvided by spoonacular (str) """ self.api_key = os.environ.get('SECRET_KEY') self.api_root = 'https://api.spoonacular.com/' def requests(self, path, method='GET', endpoint=None, query_=None, params_=None, json_=None): """ Make a request to the API """ uri = self.api_root + path if params_: params_['apiKey'] = self.api_key else:
#! spoonacular.py # Script to get 5 random recipies import spoonacular as sp import json def jprint(obj): text = json.dumps(obj, sort_keys=True, indent=4) print(text) api = sp.API("7e44755f4fa74d75ab82245e8dda7522") def getrecipe(): response = api.get_random_recipes('1') data = response.json()['recipes'] # Recipe name title = [] for d in data: titlename = d['title'] title.append(titlename) # Ingredients ingredients = [] for ingred in data: ingedient = ingred['extendedIngredients'] for single in ingedient:
import spoonacular as sp api = sp.API("ec9eb3bb895e4078bb61b9e7b9cf05e7") unwantedUnits = ['large', 'larges', 'serving', 'servings', 'smalls', 'small'] def loadFridgeContent(): with open("exampleFridgeContent.txt", "r") as f: data = f.readlines() contents = {} for rawData in data: spl = rawData.split("$") contName = spl[0] contAmount = spl[1] contUnit = spl[2] contents[contName] = [contAmount, contUnit] return contents def generateRecipes(contents): ingList = "" for item in contents: ingList += item + "," ingList = ingList[0:(len(ingList) - 2)] recipesJsonList = api.search_recipes_by_ingredients(ingredients=ingList, number=5, ranking=1).json() recipes = []
from random import * from flask import Flask, request from pymessenger.bot import Bot import requests import csv import random import spoonacular as sp #To connect to spoonacular API in order to get a random joke api = sp.API("8fb217867404486192e99424e58bcb10") #Connection to messenger app = Flask(__name__) ACCESS_TOKEN = 'EAADFDulpZCEkBALbsO0oRZBvcITAN6YSOInDpFQIzpkZAZA1xtG9taDD7IjRAVE1mI5bZBkHJke7ZA3OTLwWYmeJdPDFypZCwDoR1zhVBzgks5HkkMwpwES33GNuvqfZCNSZAzSbqF4XOjnex5gp8F5gU1fiSZCGAowh7XeM1aFSG4TgZDZD' VERIFY_TOKEN = 'blabla' bot = Bot(ACCESS_TOKEN) @app.route("/", methods=['GET', 'POST']) def receive_message(): data = read_csv() welcomes = ["hello", "Hello", "Hi", "hi","Again","again"] first_message = "Hello, what type of recipe do you want? Please Write : salty, sugary or surprise ? You can restart at any time writing the word again" salty1 = ["Enter a code (for ex s1)", "s1 random salty", "s2 Healthy salty", "s3 Comfort Salty", "s4 More options"] salty1final = "\n".join(salty1) salty2 = ["Enter a code (for ex t1)", "t1 random American", "t2 American and healthy", "t3 random Asian", "t4 Asian and healthy", "t5 Random Italian", "t6 Italian and healthy", "t7 Random French", "t8 French and healthy"] salty2final = "\n".join(salty2) sugar1 = ["Enter a code (for ex i1)", "i1 random sugar", "i2 Healthy sugary", "i3 Comfort sugary", "i4 More options"] sugar1final = "\n".join(sugar1) sugar2 = ["Enter a code (for ex v1)", "v1 random American", "v2 American and healthy", "v3 random Asian", "v4 Asian and healthy", "v5 Random Italian", "v6 Italian and healthy", "v7 Random French", "v8 French and healthy"] sugar2final = "\n".join(sugar2) list_p = create_list()
from threading import Thread import logging import ratings import spoonacular as sp # Enable logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) logger = logging.getLogger(__name__) # Instantiate spoonacular api api_instance = sp.API("7622a72decf948a0b1fb094128e2f884") def help_command(update: Update, context: CallbackContext) -> None: """Send a message when the command /help is issued.""" command_options = "As your gastronomic companion, there many things I can do. You can use these anytime.\n\n<b>substitute</b> (Type an ingredient in chat): Where's the <i>LAMB SAUCE?</i>\n<b>/trivia</b>: Don't be an idiot sandwich.\n<b>/hungry</b>: It's delicious.\n<b>/joke</b>: Very funny!\n<b>/end</b>: **** me, what do you think?" update.message.reply_text(command_options, parse_mode=ParseMode.HTML) def trivia_command(update: Update, context: CallbackContext) -> None: """Return a random food trivia.""" try: # Get Random food trivia api_response = api_instance.get_random_food_trivia() result = "Here's a touch of <b>Ramsii's knowledge</b> for you.\n\n" + api_response.json()['text'] logger.info(f"Here is the result: {result}")
from flask import Flask, render_template, request import spoonacular as sp import app_config from functions import getRecipes # initializing api apiKey = app_config.key api = sp.API(apiKey) # initializing app app = Flask(__name__) # using one app route @app.route('/results', methods=['POST']) def sortRecipes(): # request the input, using the input for our API ingredients = request.form['ingredients'] ingredientsStringed = str(ingredients) # returns only the top 3 results as of right now response = api.search_recipes_by_ingredients(ingredientsStringed, number=3) recipeJson = response.json() recipeList = [] for item in recipeJson: recipeList.append(getRecipes(item)) return render_template('results.html', recipeList=recipeList, ingredients=ingredientsStringed) # recipeList=recipeList)
from difflib import SequenceMatcher import spoonacular as sp import emoji from spacy.lang.en import English from telebot import types from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton from src.chatter import Statement from src.randomEmoji import random_emoji, UNICODE_VERSION listOfKeys = [ "aa9cc6861144497a9ce2ab7ffa864984", "8f73d348bf9d4f01b24731f418c9f6b2", "bba58a1c79234e139e3785c6fbceb313", "d41d43631cb8475198df1d900e17dc44" ] api = sp.API("8f73d348bf9d4f01b24731f418c9f6b2") def similar(a, b): return SequenceMatcher(None, a, b).ratio() class ingredientChosser(object): def __init__(self, **kwargs): pass @staticmethod def can_process(statement, state, mongo): if similar(statement.text, "ingredients") > 0.8: return True return False
from twilio.twiml.messaging_response import MessagingResponse from flask import Flask, request, redirect from collections import defaultdict import spoonacular as sp import os api = sp.API(os.environ.get('SPOONACULAR_KEY')) app = Flask(__name__) def welcome_message(): """ Returns a simple welcome message :return: welcome message """ return 'Hello! Welcome to the very simple recipe finder. Please enter an ingredient or cuisine:' def goodbye_message(): """ Returns a goodbye message :return: goodbye message """ return 'Thank you, Goodbye!' def help_message(): """ Returns a help message. Provides possible endpoints for the user :return: a help message
def main(): f = open('settings.json', ) data = json.load(f) photoRef = data["Photo_Reference"] api = sp.API(data["API_Key"]) print( "Nice meal! I think that the following ingredients may be in the meal:" ) prediction = ImagePrediction() prediction.setModelTypeAsResNet() prediction.setModelPath( "./training-data/resnet50_weights_tf_dim_ordering_tf_kernels.h5") prediction.loadModel() try: predictions, percentage_probabilities = prediction.predictImage( "./images/" + photoRef, result_count=8) except Exception as e: print( "Oops that didn't work :(\nMake sure you are referencing the file properly." ) excludeFile = open("./dict/exclude.txt", "r") exclude = excludeFile.read() ingredients = [] for i in range(len(predictions)): if (predictions[i] not in exclude): ingredients.append(predictions[i].replace('_', ' ')) for i in range(len(ingredients)): if (i == len(ingredients) - 1): print("and " + ingredients[i]) else: print(ingredients[i] + ", ", end="") waitAnim() # get how expensive each ingredient is print( "\nOk ok nice nice, let me guess how expensive the ingredients in that meal was!" ) totalPrice = thisPrice = 0 for i in range(len(ingredients)): response = api.parse_ingredients(ingredients[i], servings=1) data = response.json() try: thisPrice = float(data[0]['estimatedCost']['value']) * 10 if (i == 0): print( f"Ok I think the {ingredients[i]} was {int(thisPrice)} cents" ) else: print(f"and the {ingredients[i]} was {int(thisPrice)} cents") except: print( f"Ok I have no idea how much the {ingredients[i]} would cost.") thisPrice = 0 totalPrice += thisPrice totalPrice = int(totalPrice) / 100 waitAnim() print( f"\nOk the results are in!\nI guess cost for that meal's raw ingredients was about ${totalPrice} American." )
import spoonacular as sp import re import config api = sp.API(config.api_key) num_recipes = 25 response = api.get_random_recipes(number=num_recipes) data = response.json() titles = open("data/titles.txt", "a+") instructions = open("data/instructions.txt", "a+") titles_and_instructions = open("data/titles_and_instructions.txt", "a+") for i in range(num_recipes): title = data['recipes'][i]['title'] steps = data['recipes'][i]['instructions'] # remove extra whitespace steps = re.sub('\s+', ' ', steps).strip() # TODO: consider issue of adding spaces to floating point numbers # add spaces after periods steps = re.sub(r'\.(?! )', '. ', steps) print(title) print(steps) titles.write(title + '\n') instructions.write(steps + '\n')
import json import boto3 import datetime import requests # from requests_aws4auth import AWS4Auth import spoonacular as sp # def lambda_handler(event, context): api = sp.API("43ebbf5785aa40b0a6777bf4349bde6c") resultData = [] response = api.get_random_recipes(number=1) message = response.json() result = message['recipes'] print(result) # for i in result: # ingredients = [] # tags = i['tags'] # id = i['id'] # title = i['title'] # instructions = i['instructions'] # if 'image' in i: # image = i['image'] # test = i['extendedIngredients'] # for i in test: # ingredients.append(i['original']) # if 'image' in i: # resultData.append([id, title, ingredients, instructions, tags, image]) # else:
import spoonacular as sp import requests import json #fe3c1ea44a3f49f2ab8015238b8605a4 #265470c9b6f04a0d9535d385763d7f19 api = sp.API("265470c9b6f04a0d9535d385763d7f19") #Almost used f4a8409201dd4d3ca6d687796881bfe8 # url = "https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/findByIngredients" # headers = { # 'x-rapidapi-key': "04971e3383msh7cce6ecca39b48fp1b23bbjsnd0e81a4583f9", # 'x-rapidapi-host': "spoonacular-recipe-food-nutrition-v1.p.rapidapi.com" # } # response = requests.request("GET", url, headers=headers, params=querystring) class Recipe: def __init__(self, ingredients="", foodname="", recipe_amount=1): # Know we would call it multiple times, so we make a class attribute (because we'd pass it in response = '') self.ingredients = dict() self.ingredients[ "ingredients"] = ingredients #ingre should be a string. Example "apples,flour,sugar" self.ingredients[ "ignorePantry"] = "false" #this makes it so that the api call does NOT ignore flour/salt/water self.ingredients[ "number"] = recipe_amount #amount of recips to output is defauled to 2 self.food_name = foodname # can be anything, example "cheeseburger with mushrooms" def GetRequest_Ingredients( self): #takes ingredients as input and returns a potential recipe
import urllib.request as URL import spoonacular import json if __name__ == "__main__": device = spoonacular.API('738087f315ba454490f58e521168dcb7') res = device.search_recipes_complex('', number=10, fillIngredients=True, addRecipeNutrition=True, ignorePantry=True, instructionsRequired=True) data = res.json() js = json.dumps(data, indent=2) with open('result.txt', mode='w') as result: result.write(js)
import spoonacular as sp from flask import request from ast import literal_eval api = sp.API("356a7bee2cc2417b9b37ea217d35247b") def mealPlan(): diet_name = request.form['diet'] options = request.form['exclude'] calories_input = request.form['calories'] list = options.split(",") li = [] for i in list: li.append(str(i)) response = api.generate_meal_plan(diet=diet_name, exclude=li, targetCalories=calories_input, timeFrame=None) data = response.json() items_data = data['items'] x = [] for index in range(len(items_data)): # print(items_data[index]['day'], items_data[index]['slot'],literal_eval(items_data[index]['value'])['title']) x.append([ items_data[index]['day'], items_data[index]['slot'], literal_eval(items_data[index]['value'])['title']
from io import BytesIO # this file is missing because it is included in the gitignore. You have to # create your own and fill it with the following variables from secrets import SQL_PASSWORD, SQL_PUBLIC_IP, SQL_DATABASE_NAME, FOODREPO_KEY, SPOON_KEY, PROJECT_ID, MODEL_ID, BUCKET_NAME, SECRET_KEY import spoonacular as sp import torch import torchvision import torchvision.transforms as transforms from torchvision import models import torchvision from PIL import Image import torchvision.transforms as transforms import torchvision.utils as vutils from torch.utils.data import DataLoader import torch.nn.init as init api = sp.API(SPOON_KEY) os.environ[ "GOOGLE_APPLICATION_CREDENTIALS"] = "./gcp_credentials/astral-charter-294311-a6531ff12b3e.json" API_KEY = SPOON_KEY app = Flask(__name__) Custom_Model = True ############################################################################### # GOOGLE CLOUD SETTINGS ############################################################################### GC_BUCKET_NAME = BUCKET_NAME # Google Cloud SQL settings PASSWORD = SQL_PASSWORD
import spoonacular as sp api = sp.API("eaf1205e8c26404a8cda30c46c86f1cd") def find_from_ingredients(ingredient_list): #ranking = 2 means minimizing missing ingredients recipe_list = api.search_recipes_by_ingredients( ingredients=ingredient_list, number=1, ranking=2) return recipe_list def get_recipe_nutrition(ingredient_list, serving_num): recipe_list = api.visualize_recipe_nutrition( ingredientList=ingredient_list, servings=serving_num) return recipe_list ingredients = input("Enter ingredients you would like to cook with: ") nutrition = get_recipe_nutrition(ingredients, 1) for recipe in nutrition: print(recipe)
query = update.callback_query print(query.data) query.answer() print(query.data) print(recipes[int(query.data)-1]['title']) text = "Selected recipe: "+ recipes[int(query.data)-1]['title'] print(text) query.edit_message_text(text=text) message = 'Here is the link to the recipe :\n'+ recipes[int(query.data)-1]["sourceUrl"] print(message) context.bot.send_message(chat_id=update.effective_chat.id, text=message, disable_web_page_preview=False) def main(): updater = Updater(bot_token, use_context=True) dp = updater.dispatcher dp.add_handler(CommandHandler('start', start)) dp.add_handler(CommandHandler('randomRecipe', get_random_recipes)) #dp.add_handler(CommandHandler('searchByName')) #dp.add_handler(MessageHandler(Filters.text, get_news_with_keyword)) dp.add_handler(CallbackQueryHandler(buttonHandler)) updater.start_polling() updater.idle() if __name__ == '__main__': api = sp.API("1ad42e955fd3498aa44b7e9861cb717c") with open('tokens.txt','r') as tokens_file : tokens = json.load(tokens_file) bot_token = tokens["Bot Token"] apikey = tokens["Recipe API key"] main()