Skip to content

Commit

Permalink
Modified some requirements in requirements.txt to install only the la…
Browse files Browse the repository at this point in the history
…test version of the dependencies.

Added some checks in the code that verifies if the value in the .env file are not empty if there is empty fields it will raise an error.

Added a link to generate the refresh token instead of searching.
Added a warning in the console if not refresh rate was specified.

Removed unused imports.
Renamed some variables for the Spotify API to match the rest of the env variables.

Renamed sendMusicNote to send_music_note

Corrected some typos in the code.
  • Loading branch information
nil-malh committed Jun 6, 2023
1 parent b7a3045 commit 7109601
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 21 deletions.
41 changes: 24 additions & 17 deletions notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@

# Instagrapi Imports
from instagrapi import Client
from instagrapi.mixins.challenge import ChallengeChoice
from instagrapi.types import NoteResponse
from dotenv import load_dotenv


Expand Down Expand Up @@ -42,6 +40,7 @@ def setup_env_file():
if not os.path.isfile(".env"):
client_id = input("Please enter your Spotify client ID: ")
client_secret = input("Please enter your Spotify client secret: ")
print(f'In order to get your refresh token , you can visit this link : https://spotify-refresh-token-generator.netlify.app/')
refresh_token = input("Please enter your Spotify refresh token: ")
bot_refresh_rate = input("Please enter the bot refresh rate (in seconds): ")
note_prefix = input("Please enter the desired prefix that will be displayed before the song name and artist")
Expand All @@ -50,6 +49,7 @@ def setup_env_file():
ig_password = input("Please enter your Instagram password: ")

if not bot_refresh_rate:
debug("No specified refresh rate was specified. Defaulting to 180s")
bot_refresh_rate = "180"

with open(".env", "w") as env_file:
Expand Down Expand Up @@ -79,10 +79,12 @@ def setup_env_file():
SLEEP_TIME = os.getenv("BOT_REFRESH_RATE") # in seconds

# Spotify credentials
client_id = os.getenv("SPOTIPY_CLIENT_ID")
client_secret = os.getenv("SPOTIPY_CLIENT_SECRET")
refresh_token = os.getenv("SPOTIPY_REFRESH_TOKEN")
SPOTIFY_CLIENT_ID = os.getenv("SPOTIPY_CLIENT_ID")
SPOTIFY_CLIENT_SECRET = os.getenv("SPOTIPY_CLIENT_SECRET")
SPOTIFY_REFRESH_TOKEN = os.getenv("SPOTIPY_REFRESH_TOKEN")

if not all([SPOTIFY_CLIENT_SECRET, SPOTIFY_CLIENT_ID, SPOTIFY_REFRESH_TOKEN]):
raise Exception("Can't find Spotify credentials in the .env file")

def get_access_token(client_id, client_secret, refresh_token):
debug("Getting an access token from Spotify API ...")
Expand All @@ -102,11 +104,11 @@ def get_access_token(client_id, client_secret, refresh_token):
raise Exception(f"Request failed with status code {response.status_code}: {response.text}")
response_data = response.json()
access_token = response_data["access_token"]
debug("Access token has been retrived from Spotify API !")
debug("Access token has been retrieved from Spotify API !")
return access_token


access_token = get_access_token(client_id, client_secret, refresh_token)
access_token = get_access_token(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, SPOTIFY_REFRESH_TOKEN)
sp = spotipy.Spotify(auth=access_token)


Expand All @@ -115,27 +117,32 @@ class Bot:

def __init__(self):
self._cl = Client()

if not all([IG_USERNAME, IG_PASSWORD, IG_NOTE_PREFIX,IG_CREDENTIAL_PATH]):
raise Exception("Can't find Instagram credentials in the .env file")
if os.path.exists(IG_CREDENTIAL_PATH):
self._cl.load_settings(IG_CREDENTIAL_PATH)
debug(f'Connecting to Instagram as {IG_USERNAME}')
self._cl.login(IG_USERNAME, IG_PASSWORD)
else:
TOTA = input("Please enter your 2FA code in order to connect to Instagram.")
debug(f'Connecting to Instagram as {IG_USERNAME} for the first time, with 2FA code : {TOTA}')
debug(f'Logging-in to Instagram as {IG_USERNAME} for the first time, with 2FA code : {TOTA}')
self._cl.login(IG_USERNAME, IG_PASSWORD, verification_code=TOTA)
debug('Instagram Credentials has been saved !')
debug(f'Logged-in to Instagram !')
self._cl.dump_settings(IG_CREDENTIAL_PATH)
debug('Instagram credentials has been saved !')

def sendMusicNote(self, song_name, artist):
def send_music_note(self, song_name, artist):
previous_note = None
note_content = f"{IG_NOTE_PREFIX} {song_name} - {artist}" if IG_NOTE_PREFIX else f"🎧 {song_name} - {artist}"
if note_content == previous_note and previous_note is not None:
debug("The content of the note is the same as before, no need to send a new one")
if len(note_content) < 60:
self._cl.send_note(f"{IG_NOTE_PREFIX} : {song_name} - {artist}" if IG_NOTE_PREFIX else f"🎧 : {song_name} - {artist}", 0)
previous_note = note_content

else:
print(f'The content of the note is too long. (note_content_len : {len(note_content)})')
previous_note = note_content

def update(self, spotify):

Expand All @@ -146,25 +153,25 @@ def update(self, spotify):
note_content = f"{song_name} - {artist}"
debug(note_content)
debug("Sending note to Instagram API.")
bot.sendMusicNote(song_name, artist)
bot.send_music_note(song_name, artist)
debug(f'Note should be set on {IG_USERNAME} account.')
else:
debug("Currently nothing is playing.")
debug("Nothing is playing currently.")
pass


if __name__ == '__main__':
bot = Bot()
trigged_fail = False
trigger_fail = False
while True:
try:
bot.update(sp)
sleep(int(SLEEP_TIME))
except spotipy.exceptions.SpotifyException as e:
if e.http_status == 401:
debug("Token has expired, refreshing it...")
access_token = get_access_token(client_id, client_secret, refresh_token)
debug("Spotify token has expired, refreshing it...")
access_token = get_access_token(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, SPOTIFY_REFRESH_TOKEN)
sp = spotipy.Spotify(auth=access_token)
debug("Token has been refresh, a new note has been created")
debug("Spotify token has been refreshed")
else:
raise e
9 changes: 5 additions & 4 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
instagrapi==1.16.41
requests==2.28.1
spotipy==2.22.1
python-dotenv==0.14.0
instagrapi
pillow
requests
spotipy
python-dotenv

0 comments on commit 7109601

Please sign in to comment.