-
Notifications
You must be signed in to change notification settings - Fork 986
/
Copy pathlyrics.py
58 lines (52 loc) · 2.14 KB
/
lyrics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import requests
import config
import os
from templates.button import *
from error_msg import QUERY_ERROR, EXAMPLE_LYRICS
MUSIXMATCH_API_KEY = os.environ.get('MUSIXMATCH_API_KEY', config.MUSIXMATCH_API_KEY)
def process(input, entities):
output = {}
try:
query = entities['lyrics'][0]['value']
# Search in title
r = requests.get('http://api.musixmatch.com/ws/1.1/track.search', params={
'apikey': MUSIXMATCH_API_KEY,
'q_track': query,
's_track_rating': 'desc',
'f_has_lyrics': '1'
})
data = r.json()
# Search inside lyrics if no results found in title search
if int(data['message']['header']['available']) == 0:
r = requests.get('http://api.musixmatch.com/ws/1.1/track.search', params={
'apikey': MUSIXMATCH_API_KEY,
'q_lyrics': query,
's_track_rating': 'desc',
'f_has_lyrics': '1'
})
data = r.json()
track = data['message']['body']['track_list'][0]['track']
track_id = track['track_id']
track_name = track['track_name']
artist_name = track['artist_name']
lyrics_url = track['track_share_url']
r = requests.get('http://api.musixmatch.com/ws/1.1/track.lyrics.get', params={
'apikey': MUSIXMATCH_API_KEY,
'track_id': track_id
})
data = r.json()
lyrics = data['message']['body']['lyrics']['lyrics_body']
template = TextTemplate()
template.set_text('Here are the lyrics of ' + track_name + ' by ' + artist_name + ':\n' + lyrics)
template.set_post_text('\n- Powered by MusiXmatch')
template.set_limit(TEXT_CHARACTER_LIMIT)
template = ButtonTemplate(template.get_text())
template.add_web_url('Full Lyrics', lyrics_url)
output['input'] = input
output['output'] = template.get_message()
output['success'] = True
except:
error_message = QUERY_ERROR.format('lyrics') + EXAMPLE_LYRICS
output['error_msg'] = TextTemplate(error_message).get_message()
output['success'] = False
return output