Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting 403 error on vps #220

Open
ashwinstr opened this issue Sep 11, 2021 · 11 comments
Open

Getting 403 error on vps #220

ashwinstr opened this issue Sep 11, 2021 · 11 comments

Comments

@ashwinstr
Copy link

Showing 403 error when trying to search for lyrics while test running on github workflow

Expected behavior
was expecting lyrics from the api

To Reproduce
the code is as follows:

import lyricsgenius
if GENIUS is not None:
    genius = lyricsgenius.Genius(GENIUS)
song = "hawayein"
artist = "arijit singh"
songs = genius.search_songs(f"{artist} {song}")
song_id =  songs["hits"][0]["result"]["id"]
await message.reply(genius.lyrics(song_id))```

the error is

```Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/lyricsgenius/api/base.py", line 80, in _make_request
    response.raise_for_status()
  File "/usr/local/lib/python3.9/site-packages/requests/models.py", line 953, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://genius.com/Arijit-singh-hawayein-lyrics```

**Version info**
 - Version: 3.0.1
 - OS: windows

**Additional context**
same error comes after directly trying to get the lyrics with:

```import GENIUS
import lyricsgenius
if GENIUS is not None:
    genius = lyricsgenius.Genius(GENIUS)
song = "hawayein"
artist = "arijit singh"
songs = genius.search_songs(f"{artist} {song}")
lyrics = songs.lyrics```
@TabulateJarl8
Copy link

I get the same error on an Azure Virtual Machine running Ubuntu 20.04. I also get the error when I write the scraping code myself, but with an added user agent header. Can't seem to find away around this one

@ju
Copy link

ju commented Feb 13, 2022

having this same isuse on Ubuntu 20.04

@TabulateJarl8
Copy link

TabulateJarl8 commented Feb 13, 2022

I was looking at the issues yesterday and saw that the same thing was reported in #190. There doesn't seem to be a solution unfortunately, so I switched to using some other API which actually let me retrieve lyrics instead of having to scrape a website, which was https://lyrics.ovh/

@owocado
Copy link

owocado commented Sep 13, 2022

I am now getting the same error on oracle VPS, was working on same VPS for months until today.

@Mohammad9760
Copy link

I am getting the same error now ... frustrating

@AkiArasaki
Copy link

I'm getting the same error on oracle VPS ubuntu 22.04

@nsde
Copy link

nsde commented Mar 4, 2023

Same here :(

@sofijakrivokapic
Copy link

Hey! I am actually getting 403 error when I try to run .search_artist() . The token is correct, and the code works on .search_songs(), but not when I try to search artist. Is anyone having a similar problem or has already found the solution?

@allerter
Copy link
Contributor

This issue has gotten worse over the past year or so because Genius has tightened its captcha rules. As a result, many VPS users keep getting 403 errors more often. Currently, the only solution is to run lyricsgenius on your own machine so your requests don't get 403 errors.
As for a possible resolution, maybe fiddling with the request headers or using different IPs to make the requests could help us avoid this issue.

@sofijakrivokapic
Copy link

Yes, indeed, it only works locally. Thank you.

streambinder added a commit to streambinder/spotitube that referenced this issue Jul 10, 2023
Apparently Genius blocks CI runners (cfr. johnwmillr/LyricsGenius#220) API requests.
@Lionheartxx
Copy link

I have the same error!!!
If i deploy my telegram bot project to server i get 403 forbidden error but when i run local in PyCharm everything works
This my Code:

import numpy as np
from requests.exceptions import HTTPError, Timeout
import lyricsgenius

from aiogram import types
from data.config import GENIUS_ACCESS_TOKEN,GENIUS_CLIENT_ID,GENIUS_CLIENT_SECRET,GENIUS_REDIRECT_URI
from keyboards.inline.SelectButton import SelectSong
from aiogram.types import CallbackQuery
from aiogram.dispatcher.filters import Command
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.dispatcher import FSMContext

from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session

from loader import dp

class OAuth2Genius(StatesGroup):
    waiting_for_code = State()


GENIUS_API_BASE_URL = 'https://api.genius.com'

def create_genius_session(token=None, state=None):
    client = BackendApplicationClient(client_id=GENIUS_CLIENT_ID)
    genius3 = OAuth2Session(client=client, token=token, redirect_uri=GENIUS_REDIRECT_URI, state=state)
    return genius3

@dp.message_handler(Command("start"))
async def start_auth(message: types.Message):
    # Start the Genius OAuth2 flow
    genius3 = create_genius_session()
    authorization_url, state = genius3.authorization_url('https://api.genius.com/oauth/authorize')

    await message.answer("To authorize, click on this [link]({})".format(authorization_url), parse_mode='Markdown')
    await OAuth2Genius.waiting_for_code.set()

@dp.message_handler(state=OAuth2Genius.waiting_for_code)
async def receive_auth_code(message: types.Message, state: FSMContext):
    # Receive the Genius OAuth2 code and exchange it for a token
    genius3 = create_genius_session(state=state)
    token = genius3.fetch_token('https://api.genius.com/oauth/token', authorization_response=message.text,
                               client_secret=GENIUS_CLIENT_SECRET)

    # Save the token to use later in your requests
    await state.finish()
    await message.answer("Authorization successful! You can now use Genius API.")
    # Store the token somewhere secure for future use (e.g., a database)

    global genius2
    genius2 = create_genius_session(token=token)

genius = lyricsgenius.Genius(GENIUS_ACCESS_TOKEN)
numbered_songs = []

@dp.message_handler()
async def Send_List(message: types.Message):
    def ListOfSongs(search_songs):
        try:
            song = genius.search_songs(f"{search_songs}")

            list_of_artist = []
            list_of_song = []

            for hit in song['hits']:
                list_of_artist.append(hit['result']['primary_artist']['name'])
                list_of_song.append(hit['result']['title'])

            arr = np.dstack((list_of_artist, list_of_song))
            len_arr = len(arr[0])

            for res in arr[0][range(0, len_arr)]:
                numbered_songs.append(f"{res[0]} - {res[1]}")

        except HTTPError as e:
            print(e.errno)
            print(e.args[0])
            print(e.args[1])
        except Timeout:
            pass

    if len(numbered_songs) == 0:
        ListOfSongs(search_songs=message.text)
    else:
        numbered_songs.clear()
        ListOfSongs(search_songs=message.text)

    result_count = min(len(numbered_songs), 10)

    if result_count >= 1:
        await message.answer(
            f"<b>Результаты 1-{result_count}</b>\n\n"
            + "\n".join(f"{i + 1}.  {numbered_songs[i]}" for i in range(result_count)),
            reply_markup=SelectSong
        )
    else:
        await message.answer("Такой песен не найдено 🤔")

@dp.callback_query_handler(lambda call: call.data.isdigit())
async def Send_Lyric(call: CallbackQuery):
    index = int(call.data)

    if 1 <= index <= len(numbered_songs):
        await call.message.delete()
        await call.message.answer("🔎 Ищу тексты песен...")

        full_text = await GetText(numbered_songs[index - 1])

        if full_text:
            # Telegramning maksimal belgilar soni 4040 ta
            if len(full_text) <= 4020:
                await call.message.answer(full_text)
            else:
                short_text = full_text[:4020]
                await call.message.answer(short_text + f"...\n\n<i>через @MusixMBot</i>")
        else:
            await call.message.answer("Извините, такого текста не найдено 🫥")

async def GetText(song_name):
    artist_name, song_get_name = map(str.strip, song_name.split("-"))

    try:
        artist = genius.search_artist(artist_name, max_songs=1)
        song_text = artist.song(song_get_name)
        text = song_text.lyrics

        return f"<code>{artist_name} - {song_get_name}</code>\n\n{text[:-5]}\n\n<i>через @MusixMBot</i>"

    except HTTPError as e:
        print(e.errno)
        print(e.args[0])
        print(e.args[1])

    except Timeout:
        pass

    return None

image

I used the liyricsgenius package. But I don't know how to integrate Genius authentication method into Code. If anyone knows, please help!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

10 participants