Skip to content

Commit 23be248

Browse files
committed
refactored auth to minimize Spotify API calls
1 parent c5d0fc7 commit 23be248

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

spotify_bot.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,8 @@
11
from uuid import uuid4
22

3-
import os
3+
import os, urllib.request, logging, json, sys, base64
44
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, InlineQueryHandler
55
from telegram import InputTextMessageContent, InlineQueryResultArticle
6-
import urllib.request
7-
import logging
8-
import json
9-
import sys
10-
import base64
116

127
# Enable logging
138
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
@@ -45,11 +40,16 @@ def get_auth_token():
4540
auth_request = urllib.request.Request("https://accounts.spotify.com/api/token", data=request_body)
4641
auth_request.add_header("Authorization", "Basic " + auth_token_encoded.decode())
4742

48-
auth_response = json.loads(urllib.request.urlopen(auth_request).read())
43+
try:
44+
auth_response = json.loads(urllib.request.urlopen(auth_request).read())
45+
except urllib.error.HTTPError as err:
46+
print(err.read())
47+
4948
access_token = auth_response["access_token"]
49+
5050
return access_token
5151

52-
def search(query, query_type):
52+
def search(query, query_type, auth_token):
5353
# replace all spaces with %20 as per Spotify Web API
5454
search_query = query.lower().strip().replace(" ", "%20")
5555
api_base_url = "https://api.spotify.com/v1/search?q="
@@ -63,7 +63,6 @@ def search(query, query_type):
6363
search_url = search_types[query_type]
6464

6565
request = urllib.request.Request(search_url)
66-
auth_token = get_auth_token()
6766
request.add_header("Authorization", "Bearer " + auth_token)
6867

6968
try:
@@ -85,17 +84,21 @@ def search(query, query_type):
8584

8685
# main function to handle all inline queries
8786
def inlinequery(bot, update):
87+
88+
print("New query started")
8889
query = update.inline_query.query
8990
results = list()
9091
types = ['Track', 'Artist', 'Album', 'Playlist']
9192

93+
auth_token = get_auth_token()
94+
9295
# if empty query, return blank results to prevent unnecessary Spotify API calls
9396
if query == '':
9497
return results
9598
else:
9699
# each new value will show up in the response to the user
97100
for _type in types:
98-
response = search(query, _type.lower())
101+
response = search(query, _type.lower(), auth_token)
99102
if response is not None:
100103
results.append(InlineQueryResultArticle(id=uuid4(),
101104
title=_type,

0 commit comments

Comments
 (0)