· 6 years ago · Nov 05, 2019, 10:22 AM
1#!/usr/bin/python3
2
3import os
4import telepot
5import logging
6import dwytsongs
7from time import sleep
8from shutil import rmtree
9from pprint import pprint
10from spotipy import Spotify
11from mutagen.mp3 import MP3
12from threading import Thread
13from mutagen.flac import FLAC
14from bs4 import BeautifulSoup
15from acrcloud import ACRcloud
16from requests import post, get
17import spotipy.oauth2 as oauth2
18from mutagen.easyid3 import EasyID3
19from configparser import ConfigParser
20from deezloader import Login, exceptions
21from sqlite3 import connect, OperationalError
22from mutagen.id3._util import ID3NoHeaderError
23
24from telepot.namedtuple import (
25 ReplyKeyboardMarkup, KeyboardButton,
26 ReplyKeyboardRemove, InlineKeyboardMarkup,
27 InlineKeyboardButton, InlineQueryResultArticle, InputTextMessageContent
28)
29
30config = ConfigParser()
31config.read("setting.ini")
32
33try:
34 deezer_token = config['login']['token']
35 bot_token = config['bot']['token']
36 acrcloud_key = config['acrcloud']['key']
37 acrcloud_hash = config['acrcloud']['secret']
38 acrcloud_host = config['acrcloud']['host']
39 ya_key = config['yandex']['key']
40 version = config['bot_info']['version']
41 creator = config['bot_info']['creator']
42 donation_link = config['bot_info']['donation']
43 group_link = config['bot_info']['group']
44except KeyError:
45 print("Something went wrong with configuration file")
46 exit()
47
48downloa = Login(deezer_token)
49bot = telepot.Bot(bot_token)
50bot_name = bot.getMe()['username']
51users = {}
52qualit = {}
53date = {}
54languag = {}
55del1 = 0
56del2 = 0
57free = 1
58default_time = 0
59is_audio = 0
60telegram_audio_api_limit = 50000000
61send_image_track_query = "Track: %s \nArtist: %s \nAlbum: %s \nDate: %s"
62send_image_album_query = "Album: %s \nArtist: %s \nDate: %s \nTracks amount: %d"
63send_image_playlist_query = "Creation: %s \nUser: %s \nTracks amount: %d"
64insert_query = "INSERT INTO DWSONGS (id, query, quality) values ('%s', '%s', '%s')"
65where_query = "SELECT query FROM DWSONGS WHERE id = '{}' and quality = '{}'"
66db_file = "dwsongs.db"
67loc_dir = "Songs/"
68
69config = {
70 "key": acrcloud_key,
71 "secret": acrcloud_hash,
72 "host": acrcloud_host
73}
74
75acrcloud = ACRcloud(config)
76
77logging.basicConfig(
78 filename = "dwsongs.log",
79 level = logging.WARNING,
80 format = "%(asctime)s %(levelname)s %(name)s %(message)s"
81)
82
83if not os.path.isdir(loc_dir):
84 os.makedirs(loc_dir)
85
86conn = connect(db_file)
87c = conn.cursor()
88
89try:
90 c.execute("CREATE TABLE DWSONGS (id text, query text, quality text)")
91 c.execute("CREATE TABLE BANNED (banned int)")
92 c.execute("CREATE TABLE CHAT_ID (chat_id int)")
93 conn.commit()
94except OperationalError:
95 pass
96
97def generate_token():
98 return oauth2.SpotifyClientCredentials(
99 client_id = "c6b23f1e91f84b6a9361de16aba0ae17",
100 client_secret = "237e355acaa24636abc79f1a089e6204"
101 ).get_access_token()
102
103spo = Spotify(
104 generate_token()
105)
106
107def request(url, chat_id = None, control = False):
108 try:
109 thing = get(url)
110 except:
111 thing = get(url)
112
113 if control:
114 try:
115 if thing.json()['error']['message'] == "Quota limit exceeded":
116 sendMessage(chat_id, "Please send the link again :(")
117 return
118 except KeyError:
119 pass
120
121 try:
122 if thing.json()['error']:
123 sendMessage(chat_id, "No result has been found :(")
124 return
125 except KeyError:
126 pass
127
128 return thing
129
130def check_image(image1, ids):
131 if not image1:
132 URL = "https://www.deezer.com/track/%s" % ids
133 image1 = request(URL).text
134
135 image1 = (
136 BeautifulSoup(image1, "html.parser")
137 .find("meta", property = "og:image")
138 .get("content")
139 .replace("500x500", "1000x1000")
140 )
141
142 ima = request(image1).content
143
144 if len(ima) == 13:
145 image1 = "https://e-cdns-images.dzcdn.net/images/cover/1000x1000-000000-80-0-0.jpg"
146
147 return image1
148
149def init_user(chat_id, msg):
150 try:
151 languag[chat_id]
152 except KeyError:
153 try:
154 languag[chat_id] = msg['from']['language_code']
155 except KeyError:
156 languag[chat_id] = "en"
157
158 try:
159 qualit[chat_id]
160 except KeyError:
161 qualit[chat_id] = "MP3_320"
162
163 try:
164 users[chat_id]
165 except KeyError:
166 users[chat_id] = 0
167
168def translate(language, sms):
169 try:
170 language = language.split("-")[0]
171
172 if not "en" in language:
173 api = (
174 "https://translate.yandex.net/api/v1.5/tr.json/translate?key=%s&text=%s&lang=en-%s"
175 % (
176 ya_key,
177 sms,
178 language
179 )
180 )
181
182 sms = request(api).json()['text'][0]
183 except:
184 pass
185
186 return sms
187
188def delete(chat_id):
189 global del2
190
191 del2 += 1
192
193 try:
194 users[chat_id] -= 1
195 except KeyError:
196 pass
197
198def write_db(execution):
199 conn = connect(db_file)
200 c = conn.cursor()
201
202 while True:
203 sleep(1)
204
205 try:
206 c.execute(execution)
207 conn.commit()
208 conn.close()
209 break
210 except OperationalError:
211 pass
212
213def sendall(msg):
214 conn = connect(db_file)
215 c = conn.cursor()
216 alls = c.execute("SELECT chat_id FROM CHAT_ID").fetchall()
217 conn.close()
218
219 for a in alls:
220 sendMessage(a[0], msg)
221
222def statisc(chat_id, do):
223 conn = connect(db_file)
224 c = conn.cursor()
225
226 if do == "USERS":
227 c.execute("SELECT chat_id FROM CHAT_ID where chat_id = '%d'" % chat_id)
228
229 if not c.fetchone():
230 write_db("INSERT INTO CHAT_ID (chat_id) values ('%d')" % chat_id)
231
232 c.execute("SELECT chat_id FROM CHAT_ID")
233
234 elif do == "TRACKS":
235 c.execute("SELECT id FROM DWSONGS")
236
237 infos = len(
238 c.fetchall()
239 )
240
241 conn.close()
242 return infos
243
244def check_flood(chat_id, time_now = 0):
245 conn = connect(db_file)
246 c = conn.cursor()
247 exist = c.execute("SELECT banned FROM BANNED where banned = '%d'" % chat_id).fetchone()
248 conn.close()
249
250 if exist:
251 return "BANNED"
252
253 if time_now == 0:
254 return
255
256 try:
257 time = time_now - date[chat_id]['time']
258
259 if time > 30:
260 date[chat_id]['msg'] = 0
261
262 date[chat_id]['time'] = time_now
263
264 if time <= 4:
265 date[chat_id]['msg'] += 1
266
267 if time <= 4 and date[chat_id]['msg'] > 4:
268 date[chat_id]['msg'] = 0
269 date[chat_id]['tries'] -= 1
270
271 sendMessage(
272 chat_id,
273 "It is appearing you are trying to flood, you have to wait more that four second to send another message.\n%d possibilites :)" % date[chat_id]['tries']
274 )
275
276 if date[chat_id]['tries'] == 0:
277 write_db("INSERT INTO BANNED (banned) values ('%d')" % chat_id)
278 del date[chat_id]
279 sendMessage(chat_id, "You are banned :)")
280 except KeyError:
281 date[chat_id] = {
282 "time": time_now,
283 "tries": 3,
284 "msg": 0
285 }
286
287def sendMessage(chat_id, text, reply_markup = None, reply_to_message_id = None):
288 sleep(default_time)
289
290 try:
291 bot.sendMessage(
292 chat_id,
293 translate(
294 languag[chat_id], text
295 ),
296 reply_markup = reply_markup,
297 reply_to_message_id = reply_to_message_id
298 )
299 except:
300 pass
301
302def sendPhoto(chat_id, photo, caption = None, reply_markup = None):
303 sleep(default_time)
304
305 try:
306 bot.sendChatAction(chat_id, "upload_photo")
307
308 bot.sendPhoto(
309 chat_id,
310 photo,
311 caption = caption,
312 reply_markup = reply_markup
313 )
314 except:
315 pass
316
317def sendAudio(chat_id, audio, link = None, image = None, youtube = False):
318 sleep(default_time)
319
320 try:
321 bot.sendChatAction(chat_id, "upload_audio")
322
323 if os.path.isfile(audio):
324 try:
325 tag = EasyID3(audio)
326 duration = MP3(audio).info.length
327 except ID3NoHeaderError:
328 tag = FLAC(audio)
329 duration = tag.info.length
330
331 if os.path.getsize(audio) < telegram_audio_api_limit:
332 data = {
333 "chat_id": chat_id,
334 "duration": int(duration),
335 "performer": tag['artist'][0],
336 "title": tag['title'][0]
337 }
338
339 file_param = {
340 "audio": open(audio, "rb"),
341 "thumb": image
342
343 }
344
345 url = "https://api.telegram.org/bot%s/sendAudio" % bot_token
346
347 try:
348 request = post(
349 url,
350 params = data,
351 files = file_param,
352 timeout = 20
353 )
354 except:
355 request = post(
356 url,
357 params = data,
358 files = file_param,
359 timeout = 20
360 )
361
362 file_id = request.json()['result']['audio']['file_id']
363
364 if not youtube:
365 quality = (
366 audio
367 .split("(")[-1]
368 .split(")")[0]
369 )
370
371 write_db(
372 insert_query
373 % (
374 link,
375 file_id,
376 quality
377 )
378 )
379 else:
380 sendMessage(chat_id, "The song is bigger than 50MB")
381 else:
382 bot.sendAudio(chat_id, audio)
383
384 except telepot.exception.TelegramError:
385 sendMessage(chat_id, "Sorry the track %s doesn't seem readable on Deezer :(" % link)
386
387
388def track(link, chat_id, quality):
389 global spo
390
391 conn = connect(db_file)
392 c = conn.cursor()
393
394 match = c.execute(
395 where_query.format(link, quality.split("MP3_")[-1])
396 ).fetchone()
397
398 conn.close()
399
400 if match:
401 sendAudio(chat_id, match[0])
402 else:
403 try:
404 youtube = False
405
406 if "spotify" in link:
407 try:
408 url = spo.track(link)
409 except:
410 spo = Spotify(
411 generate_token()
412 )
413
414 url = spo.track(link)
415
416 try:
417 image = url['album']['images'][2]['url']
418 except IndexError:
419 image = "https://e-cdns-images.dzcdn.net/images/cover/90x90-000000-80-0-0.jpg"
420
421 z = downloa.download_trackspo(
422 link,
423 quality = quality,
424 recursive_quality = True,
425 recursive_download = True,
426 not_interface = True
427 )
428
429 elif "deezer" in link:
430 ids = link.split("/")[-1]
431
432 try:
433 url = request(
434 "https://api.deezer.com/track/%s" % ids, chat_id, True
435 ).json()['album']['cover_xl']
436 except AttributeError:
437 return
438
439 image = check_image(url, ids).replace("1000x1000", "90x90")
440
441 z = downloa.download_trackdee(
442 link,
443 quality = quality,
444 recursive_quality = True,
445 recursive_download = True,
446 not_interface = True
447 )
448 except (exceptions.TrackNotFound, exceptions.NoDataApi):
449 sendMessage(chat_id, "Track doesn't %s exist on Deezer or maybe it isn't readable, it'll be downloaded from YouTube..." % link)
450
451 try:
452 if "spotify" in link:
453 z = dwytsongs.download_trackspo(
454 link, check = False
455 )
456
457 elif "deezer" in link:
458 z = dwytsongs.download_trackdee(
459 link, check = False
460 )
461
462 youtube = True
463 except dwytsongs.TrackNotFound:
464 sendMessage(chat_id, "Sorry I cannot download this song %s :(" % link)
465 return
466
467 sendAudio(chat_id, z, link, image, youtube)
468
469def Link(link, chat_id, quality, msg):
470 global spo
471 global del1
472
473 del1 += 1
474 done = 0
475 links1 = []
476 links2 = []
477 quali = quality.split("MP3_")[-1]
478
479 if "?" in link:
480 link = link.split("?")[0]
481
482 try:
483 if "spotify" in link:
484 if "track/" in link:
485 try:
486 url = spo.track(link)
487 except Exception as a:
488 if not "The access token expired" in str(a):
489 sendMessage(
490 chat_id, "Invalid link %s ;)" % link,
491 reply_to_message_id = msg['message_id']
492 )
493
494 delete(chat_id)
495 return
496
497 spo = Spotify(
498 generate_token()
499 )
500
501 url = spo.track(link)
502
503 try:
504 image1 = url['album']['images'][0]['url']
505 except IndexError:
506 image1 = "https://e-cdns-images.dzcdn.net/images/cover/1000x1000-000000-80-0-0.jpg"
507
508 sendPhoto(
509 chat_id, image1,
510 caption = (
511 send_image_track_query
512 % (
513 url['name'],
514 url['album']['artists'][0]['name'],
515 url['album']['name'],
516 url['album']['release_date']
517 )
518 )
519 )
520
521 track(link, chat_id, quality)
522
523 elif "album/" in link:
524 try:
525 tracks = spo.album(link)
526 except Exception as a:
527 if not "The access token expired" in str(a):
528 sendMessage(
529 chat_id, "Invalid link %s ;)" % link,
530 reply_to_message_id = msg['message_id']
531 )
532
533 delete(chat_id)
534 return
535
536 spo = Spotify(
537 generate_token()
538 )
539
540 tracks = spo.album(link)
541
542 try:
543 image3 = tracks['images'][2]['url']
544 image1 = tracks['images'][0]['url']
545 except IndexError:
546 image3 = "https://e-cdns-images.dzcdn.net/images/cover/90x90-000000-80-0-0.jpg"
547 image1 = "https://e-cdns-images.dzcdn.net/images/cover/1000x1000-000000-80-0-0.jpg"
548
549 tot = tracks['total_tracks']
550 conn = connect(db_file)
551 c = conn.cursor()
552 count = 0
553
554 for a in tracks['tracks']['items']:
555 count += a['duration_ms']
556
557 c.execute(
558 where_query.format(a['external_urls']['spotify'], quali)
559 )
560
561 links2.append(
562 a['external_urls']['spotify']
563 )
564
565 if c.fetchone():
566 links1.append(
567 a['external_urls']['spotify']
568 )
569
570 if (count / 1000) > 40000:
571 sendMessage(chat_id, "If you do this again I will come to your home and I will ddos your ass :)")
572 delete(chat_id)
573 return
574
575 sendPhoto(
576 chat_id, image1,
577 caption = (
578 send_image_album_query
579 % (
580 tracks['name'],
581 tracks['artists'][0]['name'],
582 tracks['release_date'],
583 tot
584 )
585 )
586 )
587
588 tracks = tracks['tracks']
589
590 if tot != 50:
591 for a in range(tot // 50):
592 try:
593 tracks2 = spo.next(tracks)
594 except:
595 spo = Spotify(
596 generate_token()
597 )
598
599 tracks2 = spo.next(tracks)
600
601 for a in tracks2['items']:
602 c.execute(
603 where_query.format(a['external_urls']['spotify'], quali)
604 )
605
606 links2.append(
607 a['external_urls']['spotify']
608 )
609
610 if c.fetchone():
611 links1.append(
612 a['external_urls']['spotify']
613 )
614
615 conn.close()
616
617 if len(links1) != tot:
618 z, zip_name = downloa.download_albumspo(
619 link,
620 quality = quality,
621 recursive_quality = True,
622 recursive_download = True,
623 not_interface = True,
624 zips = True
625 )
626 else:
627 for a in links2:
628 track(a, chat_id, quality)
629
630 done = 1
631
632 elif "playlist/" in link:
633 musi = link.split("/")
634
635 try:
636 tracks = spo.user_playlist(musi[-3], musi[-1])
637 except Exception as a:
638 if not "The access token expired" in str(a):
639 sendMessage(
640 chat_id, "Invalid link ;)",
641 reply_to_message_id = msg['message_id']
642 )
643
644 delete(chat_id)
645 return
646
647 spo = Spotify(
648 generate_token()
649 )
650
651 tracks = spo.user_playlist(musi[-3], musi[-1])
652
653 try:
654 image1 = tracks['images'][0]['url']
655 except IndexError:
656 image1 = "https://e-cdns-images.dzcdn.net/images/cover/1000x1000-000000-80-0-0.jpg"
657
658 tot = tracks['tracks']['total']
659
660 if tot > 400:
661 sendMessage(chat_id, "Fuck you")
662 delete(chat_id)
663 return
664
665 sendPhoto(
666 chat_id, image1,
667 caption = (
668 send_image_playlist_query
669 % (
670 tracks['tracks']['items'][0]['added_at'],
671 tracks['owner']['display_name'],
672 tot
673 )
674 )
675 )
676
677 for a in tracks['tracks']['items']:
678 try:
679 track(
680 a['track']['external_urls']['spotify'],
681 chat_id,
682 quality
683 )
684 except KeyError:
685 try:
686 sendMessage(chat_id, "%s Not found :(" % a['track']['name'])
687 except KeyError:
688 sendMessage(chat_id, "Error :(")
689
690 tot = tracks['tracks']['total']
691 tracks = tracks['tracks']
692
693 if tot != 100:
694 for a in range(tot // 100):
695 try:
696 tracks = spo.next(tracks)
697 except:
698 spo = Spotify(
699 generate_token()
700 )
701
702 tracks = spo.next(tracks)
703
704 for a in tracks['items']:
705 try:
706 track(
707 a['track']['external_urls']['spotify'],
708 chat_id,
709 quality
710 )
711 except KeyError:
712 try:
713 sendMessage(chat_id, "%s Not found :(" % a['track']['name'])
714 except KeyError:
715 sendMessage(chat_id, "Error :(")
716
717 done = 1
718
719 else:
720 sendMessage(chat_id, "Sorry :( The bot doesn't support this link")
721
722 elif "deezer" in link:
723 ids = link.split("/")[-1]
724
725 if "track/" in link:
726 try:
727 url = request(
728 "https://api.deezer.com/track/%s" % ids, chat_id, True
729 ).json()
730 except AttributeError:
731 delete(chat_id)
732 return
733
734 image1 = check_image(
735 url['album']['cover_xl'], ids
736 )
737
738 sendPhoto(
739 chat_id, image1,
740 caption = (
741 send_image_track_query
742 % (
743 url['title'],
744 url['artist']['name'],
745 url['album']['title'],
746 url['album']['release_date']
747 )
748 )
749 )
750
751 track(link, chat_id, quality)
752
753 elif "album/" in link:
754 try:
755 url = request(
756 "https://api.deezer.com/album/%s" % ids, chat_id, True
757 ).json()
758 except AttributeError:
759 delete(chat_id)
760 return
761
762 if url['duration'] > 40000:
763 sendMessage(chat_id, "If you do this again I will come to your home and I will ddos your ass :)")
764 delete(chat_id)
765 return
766
767 image1 = url['cover_xl']
768
769 if not image1:
770 URL = "https://www.deezer.com/album/%s" % ids
771 image1 = request(URL).text
772
773 image1 = (
774 BeautifulSoup(image1, "html.parser")
775 .find("img", class_ = "img_main")
776 .get("src")
777 .replace("200x200", "1000x1000")
778 )
779
780 ima = request(image1).content
781
782 if len(ima) == 13:
783 image1 = "https://e-cdns-images.dzcdn.net/images/cover/1000x1000-000000-80-0-0.jpg"
784
785 image3 = image1.replace("1000x1000", "90x90")
786
787 conn = connect(db_file)
788 c = conn.cursor()
789
790 for a in url['tracks']['data']:
791 c.execute(
792 where_query.format(a['link'], quali)
793 )
794
795 links2.append(a['link'])
796
797 if c.fetchone():
798 links1.append(a['link'])
799
800 conn.close()
801 tot = url['nb_tracks']
802
803 sendPhoto(
804 chat_id, image1,
805 caption = (
806 send_image_album_query
807 % (
808 url['title'],
809 url['artist']['name'],
810 url['release_date'],
811 tot
812 )
813 )
814 )
815
816 if len(links1) != tot:
817 z, zip_name = downloa.download_albumdee(
818 link,
819 quality = quality,
820 recursive_quality = True,
821 recursive_download = True,
822 not_interface = True,
823 zips = True
824 )
825 else:
826 for a in links2:
827 track(a, chat_id, quality)
828
829 done = 1
830
831 elif "playlist/" in link:
832 try:
833 url = request(
834 "https://api.deezer.com/playlist/%s" % ids, chat_id, True
835 ).json()
836 except AttributeError:
837 delete(chat_id)
838 return
839
840 tot = url['nb_tracks']
841
842 if tot > 400:
843 sendMessage(chat_id, "Fuck you")
844 delete(chat_id)
845 return
846
847 sendPhoto(
848 chat_id, url['picture_xl'],
849 caption = (
850 send_image_playlist_query
851 % (
852 url['creation_date'],
853 url['creator']['name'],
854 tot
855 )
856 )
857 )
858
859 for a in url['tracks']['data']:
860 try:
861 track(a['link'], chat_id, quality)
862 except:
863 song = "{} - {}".format(a['title'], a['artist']['name'])
864 sendMessage(chat_id, "Cannot download %s :(" % song)
865
866 done = 1
867
868 elif "artist/" in link:
869 link = "https://api.deezer.com/artist/%s" % ids
870
871 try:
872 url = request(link, chat_id, True).json()
873 except AttributeError:
874 delete(chat_id)
875 return
876
877 sendPhoto(
878 chat_id, url['picture_xl'],
879 caption = (
880 "Artist: %s \nAlbum numbers: %d \nFans on Deezer: %d"
881 % (
882 url['name'],
883 url['nb_album'],
884 url['nb_fan']
885 )
886 ),
887 reply_markup = InlineKeyboardMarkup(
888 inline_keyboard = [
889 [
890 InlineKeyboardButton(
891 text = "TOP 30",
892 callback_data = "%s/top?limit=30" % link
893 ),
894 InlineKeyboardButton(
895 text = "ALBUMS",
896 callback_data = "%s/albums" % link
897 )
898 ],
899 [
900 InlineKeyboardButton(
901 text = "RADIO",
902 callback_data = "%s/radio" % link
903 ),
904 InlineKeyboardButton(
905 text = "RELATED",
906 callback_data = "%s/related" % link
907 )
908 ]
909 ]
910 )
911 )
912
913 else:
914 sendMessage(chat_id, "Sorry :( The bot doesn't support this link %s :(" % link)
915
916 else:
917 sendMessage(chat_id, "Sorry :( The bot doesn't support this link %s :(" % link)
918
919 try:
920 for a in range(
921 len(z)
922 ):
923 sendAudio(chat_id, z[a], links2[a], image3)
924 except NameError:
925 pass
926
927 except exceptions.QuotaExceeded:
928 sendMessage(chat_id, "Please send the link %s again :(" % link)
929
930 except exceptions.AlbumNotFound:
931 sendMessage(chat_id, "Album %s didn't find on Deezer :(" % link)
932 sendMessage(chat_id, "Try to search it throught inline mode or search the link on Deezer")
933
934 except Exception as a:
935 logging.warning(a)
936 logging.warning(quality)
937 logging.warning(link)
938
939 sendMessage(
940 chat_id, "OPS :( Something went wrong please send to @An0nimia this link: {} {}, if this happens again".format(link, quality)
941 )
942
943 if done == 1:
944 sendMessage(
945 chat_id, "FINISHED :) Rate me here https://t.me/BotsArchive/298",
946 reply_to_message_id = msg['message_id'],
947 reply_markup = InlineKeyboardMarkup(
948 inline_keyboard = [
949 [
950 InlineKeyboardButton(
951 text = "SHARE",
952 url = "tg://msg?text=Start @%s for download all the songs which you want ;)" % bot_name
953 )
954 ]
955 ]
956 )
957 )
958
959 delete(chat_id)
960
961def Audio(audio, chat_id):
962 global spo
963 global is_audio
964
965 is_audio = 1
966 audi = "{}{}.ogg".format(loc_dir, audio)
967
968 try:
969 bot.download_file(audio, audi)
970 except telepot.exception.TelegramError:
971 sendMessage(chat_id, "File sent is too big, please send a file lower than 20 MB")
972 is_audio = 0
973 return
974
975 audio = acrcloud.recognizer(audi)
976 is_audio = 0
977
978 try:
979 os.remove(audi)
980 except FileNotFoundError:
981 pass
982
983 if audio['status']['msg'] != "Success":
984 sendMessage(chat_id, "Sorry cannot detect the song from audio :(, retry...")
985 return
986
987 artist = audio['metadata']['music'][0]['artists'][0]['name']
988 track = audio['metadata']['music'][0]['title']
989 album = audio['metadata']['music'][0]['album']['name']
990
991 try:
992 date = audio['metadata']['music'][0]['release_date']
993 album += "_%s" % date
994 except KeyError:
995 album += "_"
996
997 try:
998 label = audio['metadata']['music'][0]['label']
999 album += "_%s" % label
1000 except KeyError:
1001 album += "_"
1002
1003 try:
1004 genre = audio['metadata']['music'][0]['genres'][0]['name']
1005 album += "_%s" % genre
1006 except KeyError:
1007 album += "_"
1008
1009 if len(album) > 64:
1010 album = "Infos with too many bytes"
1011
1012 try:
1013 song = "{} - {}".format(track, artist)
1014
1015 url = request(
1016 "https://api.deezer.com/search/track/?q=%s" % song.replace("#", ""), chat_id, True
1017 ).json()
1018 except AttributeError:
1019 return
1020
1021 try:
1022 for a in range(url['total'] + 1):
1023 if url['data'][a]['title'] == track:
1024 ids = url['data'][a]['link']
1025 image = url['data'][a]['album']['cover_xl']
1026 break
1027 except IndexError:
1028 try:
1029 ids = "https://open.spotify.com/track/%s" % audio['metadata']['music'][0]['external_metadata']['spotify']['track']['id']
1030
1031 try:
1032 url = spo.track(ids)
1033 except:
1034 spo = Spotify(
1035 generate_token()
1036 )
1037
1038 url = spo.track(ids)
1039
1040 image = url['album']['images'][0]['url']
1041 except KeyError:
1042 pass
1043
1044 try:
1045 ids = "https://api.deezer.com/track/%s" % audio['metadata']['music'][0]['external_metadata']['deezer']['track']['id']
1046
1047 try:
1048 url = request(ids, chat_id, True).json()
1049 except AttributeError:
1050 return
1051
1052 image = url['album']['cover_xl']
1053 except KeyError:
1054 pass
1055
1056 try:
1057 sendPhoto(
1058 chat_id, image,
1059 caption = "{} - {}".format(track, artist),
1060 reply_markup = InlineKeyboardMarkup(
1061 inline_keyboard = [
1062 [
1063 InlineKeyboardButton(
1064 text = "Download",
1065 callback_data = ids
1066 ),
1067 InlineKeyboardButton(
1068 text = "Info",
1069 callback_data = album
1070 )
1071 ]
1072 ]
1073 )
1074 )
1075 except:
1076 sendMessage(chat_id, "Error :(")
1077
1078def inline(msg, from_id, query_data, query_id):
1079 if "artist" in query_data:
1080 message_id = msg['message']['message_id']
1081 keyboard = []
1082 link = "https://api.deezer.com/artist/%s" % query_data.split("/")[4]
1083
1084 try:
1085 url = request(
1086 query_data.replace("down", ""),
1087 from_id, True
1088 ).json()
1089 except AttributeError:
1090 return
1091
1092
1093 if "album" in query_data:
1094 keyboard += [
1095 [
1096 InlineKeyboardButton(
1097 text = "{} - {}".format(a['title'], a['release_date']),
1098 callback_data = a['link']
1099 )
1100 ] for a in url['data']
1101 ]
1102
1103 keyboard.append(
1104 [
1105 InlineKeyboardButton(
1106 text = "BACK ?",
1107 callback_data = link
1108 )
1109 ]
1110 )
1111
1112 elif "down" in query_data:
1113 if ans == "2":
1114 if users[from_id] == 3:
1115 bot.answerCallbackQuery(
1116 query_id,
1117 translate(
1118 languag[from_id],
1119 "Wait the end and repeat the step, did you think you could download how much songs you wanted? ;)"
1120 ),
1121 show_alert = True
1122 )
1123
1124 return
1125 else:
1126 users[from_id] += 1
1127
1128 bot.answerCallbackQuery(
1129 query_id,
1130 translate(
1131 languag[from_id], "Songs are downloading"
1132 )
1133 )
1134
1135 for a in url['data']:
1136 Link(
1137 "https://www.deezer.com/track/%d" % a['id'],
1138 from_id,
1139 qualit[from_id],
1140 msg['message']
1141 )
1142
1143 if ans == "2":
1144 users[from_id] += 1
1145
1146 if ans == "2":
1147 users[from_id] -= 1
1148
1149 elif "radio" in query_data or "top" in query_data:
1150 if "radio" in query_data:
1151 method = "radio"
1152 else:
1153 method = "top?limit=30"
1154
1155 keyboard += [
1156 [
1157 InlineKeyboardButton(
1158 text = "{} - {}".format(a['artist']['name'], a['title']),
1159 callback_data = "https://www.deezer.com/track/%d" % a['id']
1160 )
1161 ] for a in url['data']
1162 ]
1163
1164 keyboard.append(
1165 [
1166 InlineKeyboardButton(
1167 text = "GET ALL ⬇️",
1168 callback_data = "{}/{}/down".format(link, method)
1169 )
1170 ]
1171 )
1172
1173 keyboard.append(
1174 [
1175 InlineKeyboardButton(
1176 text = "BACK ?",
1177 callback_data = link
1178 )
1179 ]
1180 )
1181
1182 elif "related" in query_data:
1183 keyboard = [
1184 [
1185 InlineKeyboardButton(
1186 text = "{}- {}".format(a['name'], a['nb_fan']),
1187 callback_data = "https://api.deezer.com/artist/%d" % a['id']
1188 )
1189 ] for a in url['data']
1190 ]
1191
1192 keyboard.append(
1193 [
1194 InlineKeyboardButton(
1195 text = "BACK ?",
1196 callback_data = link
1197 )
1198 ]
1199 )
1200
1201 else:
1202 bot.deleteMessage(
1203 (
1204 from_id, message_id
1205
1206 )
1207 )
1208
1209 keyboard = [
1210 [
1211 InlineKeyboardButton(
1212 text = "TOP 30",
1213 callback_data = "%s/top?limit=30" % link
1214 ),
1215 InlineKeyboardButton(
1216 text = "ALBUMS",
1217 callback_data = "%s/albums" % link
1218 )
1219 ],
1220 [
1221 InlineKeyboardButton(
1222 text = "RADIO",
1223 callback_data = "%s/radio" % link
1224 ),
1225 InlineKeyboardButton(
1226 text = "RELATED",
1227 callback_data = "%s/related" % link
1228 )
1229 ]
1230 ]
1231
1232 sendPhoto(
1233 from_id, url['picture_xl'],
1234 caption = (
1235 "Artist: %s \nAlbum numbers: %d \nFans on Deezer: %d"
1236 % (
1237 url['name'],
1238 url['nb_album'],
1239 url['nb_fan']
1240 )
1241 ),
1242 reply_markup = InlineKeyboardMarkup(
1243 inline_keyboard = keyboard
1244 )
1245 )
1246
1247 try:
1248 bot.editMessageReplyMarkup(
1249 (
1250 (
1251 from_id, message_id
1252 )
1253 ),
1254 reply_markup = InlineKeyboardMarkup(
1255 inline_keyboard = keyboard
1256 )
1257 )
1258 except telepot.exception.TelegramError:
1259 pass
1260 else:
1261 tags = query_data.split("_")
1262
1263 if tags[0] == "Infos with too many bytes":
1264 bot.answerCallbackQuery(
1265 query_id,
1266 translate(
1267 languag[from_id], query_data
1268 )
1269 )
1270
1271 elif len(tags) == 4:
1272 bot.answerCallbackQuery(
1273 query_id,
1274 text = (
1275 "Album: %s\nDate: %s\nLabel: %s\nGenre: %s"
1276 % (
1277 tags[0],
1278 tags[1],
1279 tags[2],
1280 tags[3]
1281 )
1282 ),
1283 show_alert = True
1284 )
1285
1286 else:
1287 if ans == "2":
1288 if users[from_id] == 3:
1289 bot.answerCallbackQuery(
1290 query_id,
1291 translate(
1292 languag[from_id], "Wait the end and repeat the step, did you think you could download how much songs you wanted? ;)"
1293 ),
1294 show_alert = True
1295 )
1296
1297 return
1298 else:
1299 users[from_id] += 1
1300
1301 bot.answerCallbackQuery(
1302 query_id,
1303 translate(
1304 languag[from_id], "Song is downloading"
1305 )
1306 )
1307
1308 Link(
1309 query_data, from_id,
1310 qualit[from_id], msg['message']
1311 )
1312
1313def download(msg):
1314 query_id, from_id, query_data = telepot.glance(msg, flavor = "callback_query")
1315
1316 init_user(from_id, msg)
1317
1318 Thread(
1319 target = inline,
1320 args = (
1321 msg, from_id,
1322 query_data, query_id
1323 )
1324 ).start()
1325
1326def search(msg):
1327 query_id, from_id, query_string = telepot.glance(msg, flavor = "inline_query")
1328
1329 if check_flood(from_id) == "BANNED":
1330 return
1331
1332 init_user(from_id, msg)
1333
1334 if "" == query_string:
1335 search1 = request("https://api.deezer.com/chart").json()
1336
1337 result = [
1338 InlineQueryResultArticle(
1339 id = a['link'],
1340 title = a['title'],
1341 description = a['artist']['name'],
1342 thumb_url = a['album']['cover_big'],
1343 input_message_content = InputTextMessageContent(
1344 message_text = a['link']
1345 )
1346 ) for a in search1['tracks']['data']
1347 ]
1348
1349 result += [
1350 InlineQueryResultArticle(
1351 id = "https://www.deezer.com/album/%d" % a['id'],
1352 title = "%s (Album)" % a['title'],
1353 description = a['artist']['name'],
1354 thumb_url = a['cover_big'],
1355 input_message_content = InputTextMessageContent(
1356 message_text = "https://www.deezer.com/album/%d" % a['id']
1357 )
1358 ) for a in search1['albums']['data']
1359 ]
1360
1361 result += [
1362 InlineQueryResultArticle(
1363 id = a['link'],
1364 title = "%d" % a['position'],
1365 description = a['name'],
1366 thumb_url = a['picture_big'],
1367 input_message_content = InputTextMessageContent(
1368 message_text = a['link']
1369 )
1370 ) for a in search1['artists']['data']
1371 ]
1372
1373 result += [
1374 InlineQueryResultArticle(
1375 id = a['link'],
1376 title = a['title'],
1377 description = "N° tracks: %d" % a['nb_tracks'],
1378 thumb_url = a['picture_big'],
1379 input_message_content = InputTextMessageContent(
1380 message_text = a['link']
1381 )
1382 ) for a in search1['playlists']['data']
1383 ]
1384 else:
1385 query_string = query_string.replace("#", "")
1386 search = query_string
1387 method = ""
1388
1389 if "alb:" in query_string or "art:" in query_string or "pla:" in query_string:
1390 search = query_string.split(query_string[:4])[-1]
1391
1392 if "alb:" in query_string:
1393 method = "album"
1394 elif "art:" in query_string:
1395 method = "artist"
1396 elif "pla:" in query_string:
1397 method = "playlist"
1398
1399 search1 = request(
1400 "https://api.deezer.com/search/{}/?q={}".format(method, search)
1401 ).json()
1402
1403 try:
1404 if search1['error']:
1405 return
1406 except KeyError:
1407 pass
1408
1409 if "alb:" in query_string:
1410 result = [
1411 InlineQueryResultArticle(
1412 id = a['link'],
1413 title = a['title'],
1414 description = a['artist']['name'],
1415 thumb_url = a['cover_big'],
1416 input_message_content = InputTextMessageContent(
1417 message_text = a['link']
1418 )
1419 ) for a in search1['data']
1420 ]
1421
1422 elif "art:" in query_string:
1423 result = [
1424 InlineQueryResultArticle(
1425 id = a['link'],
1426 title = a['name'],
1427 thumb_url = a['picture_big'],
1428 input_message_content = InputTextMessageContent(
1429 message_text = a['link']
1430 )
1431 ) for a in search1['data']
1432 ]
1433
1434 elif "pla:" in query_string:
1435 result = [
1436 InlineQueryResultArticle(
1437 id = a['link'],
1438 title = a['title'],
1439 description = "N° tracks: %d" % a['nb_tracks'],
1440 thumb_url = a['picture_big'],
1441 input_message_content = InputTextMessageContent(
1442 message_text = a['link']
1443 )
1444 ) for a in search1['data']
1445 ]
1446 else:
1447 if "lbl:" in query_string or "trk:" in query_string:
1448 search = query_string.split(query_string[:4])[-1]
1449
1450 if "lbl:" in query_string:
1451 method = "label"
1452 else:
1453 method = "track"
1454
1455 search1 = request(
1456 "https://api.deezer.com/search/?q={}:'{}'".format(method, search)
1457 ).json()
1458
1459 try:
1460 if search1['error']:
1461 return
1462 except KeyError:
1463 pass
1464
1465 result = [
1466 InlineQueryResultArticle(
1467 id = a['link'],
1468 title = a['title'],
1469 description = a['artist']['name'],
1470 thumb_url = a['album']['cover_big'],
1471 input_message_content = InputTextMessageContent(
1472 message_text = a['link']
1473 )
1474 ) for a in search1['data']
1475 ]
1476
1477 for a in search1['data']:
1478 try:
1479 if "https://www.deezer.com/album/%d" % a['album']['id'] in str(result):
1480 continue
1481 except KeyError:
1482 continue
1483
1484 result += [
1485 InlineQueryResultArticle(
1486 id = "https://www.deezer.com/album/%d" % a['album']['id'],
1487 title = "%s (Album)" % a['album']['title'],
1488 description = a['artist']['name'],
1489 thumb_url = a['album']['cover_big'],
1490 input_message_content = InputTextMessageContent(
1491 message_text = "https://www.deezer.com/album/%d" % a['album']['id']
1492 )
1493 )
1494 ]
1495
1496 try:
1497 bot.answerInlineQuery(query_id, result)
1498 except telepot.exception.TelegramError:
1499 pass
1500
1501def nada(msg):
1502 pass
1503
1504def start(msg):
1505 global free
1506
1507 content_type, chat_type, chat_id = telepot.glance(msg)
1508
1509 if free == 0 and chat_id != 560950095:
1510 return
1511
1512 if check_flood(chat_id, msg['date']) == "BANNED":
1513 return
1514
1515 pprint(msg)
1516 statisc(chat_id, "USERS")
1517 init_user(chat_id, msg)
1518
1519 if content_type == "text" and msg['text'] == "/start":
1520 try:
1521 sendPhoto(
1522 chat_id, open("example.jpg", "rb"),
1523 caption = "Welcome to @%s \nPress '/' to get commands list" % bot_name
1524 )
1525 except FileNotFoundError:
1526 pass
1527
1528 sendMessage(
1529 chat_id,
1530 "Press for search what you prefer" +
1531 "\nP.S. Remember you can do this digiting @ in your keyboard and select %s" % bot_name +
1532 "\nSend a Deezer or Spotify link to download \nSend a song o vocal message to recognize the track",
1533 reply_markup = InlineKeyboardMarkup(
1534 inline_keyboard = [
1535 [
1536 InlineKeyboardButton(
1537 text = "Search by artist",
1538 switch_inline_query_current_chat = "art: "
1539 ),
1540 InlineKeyboardButton(
1541 text = "Search by album",
1542 switch_inline_query_current_chat = "alb: "
1543 )
1544 ],
1545 [
1546 InlineKeyboardButton(
1547 text = "Search playlist",
1548 switch_inline_query_current_chat = "pla: "
1549 ),
1550 InlineKeyboardButton(
1551 text = "Search label",
1552 switch_inline_query_current_chat = "lbl: "
1553 )
1554 ],
1555 [
1556 InlineKeyboardButton(
1557 text = "Search track",
1558 switch_inline_query_current_chat = "trk: "
1559 ),
1560 InlineKeyboardButton(
1561 text = "Global search",
1562 switch_inline_query_current_chat = ""
1563 )
1564 ]
1565 ]
1566 )
1567 )
1568
1569 elif content_type == "text" and msg['text'] == "/translator":
1570 if languag[chat_id] != "en":
1571 languag[chat_id] = "en"
1572 sendMessage(chat_id, "Now the language is english")
1573 else:
1574 languag[chat_id] = msg['from']['language_code']
1575 sendMessage(chat_id, "Now the bot will use the Telegram app language")
1576
1577 elif content_type == "text" and msg['text'] == "/quality":
1578 sendMessage(
1579 chat_id, "Select default download quality\nCURRENTLY: %s" % qualit[chat_id],
1580 reply_markup = ReplyKeyboardMarkup(
1581 keyboard = [
1582 [
1583 KeyboardButton(
1584 text = "FLAC"
1585 ),
1586 KeyboardButton(
1587 text = "MP3_320Kbps"
1588 )
1589 ],
1590 [
1591 KeyboardButton(
1592 text = "MP3_256Kbps"
1593 ),
1594 KeyboardButton(
1595 text = "MP3_128Kbps"
1596 )
1597 ]
1598 ]
1599 )
1600 )
1601
1602 elif content_type == "text" and (
1603 msg['text'] == "FLAC" or
1604 msg['text'] == "MP3_320Kbps" or
1605 msg['text'] == "MP3_256Kbps" or
1606 msg['text'] == "MP3_128Kbps"
1607 ):
1608 qualit[chat_id] = msg['text'].replace("Kbps", "")
1609
1610 sendMessage(
1611 chat_id, "Songs will be downloaded in %s quality" % msg['text'],
1612 reply_markup = ReplyKeyboardRemove()
1613 )
1614
1615 sendMessage(chat_id, "Songs which cannot be downloaded in quality you have chosen will be downloaded in the best quality possible")
1616
1617 elif content_type == "voice" or content_type == "audio":
1618 Thread(
1619 target = Audio,
1620 args = (msg[content_type]['file_id'], chat_id)
1621 ).start()
1622
1623 elif content_type == "text" and msg['text'] == "/info":
1624 sendMessage(
1625 chat_id,
1626 "Version: %s \nName: @%s \nCreator: @%s \nDonation: %s \nForum: %s \nUsers: %d \nTotal downloads: %d"
1627 % (
1628 version,
1629 bot_name,
1630 creator,
1631 donation_link,
1632 group_link,
1633 statisc(chat_id, "USERS"),
1634 statisc(chat_id, "TRACKS")
1635 )
1636 )
1637
1638 elif content_type == "text" and chat_id == 560950095 and "the cat is on the table" in msg['text']:
1639 what = msg['text'].split("the cat is on the table ")[-1]
1640
1641 if what == "1":
1642 free = 1
1643
1644 elif what == "0":
1645 free = 0
1646
1647 else:
1648 Thread(
1649 target = sendall,
1650 args = (what,)
1651 ).start()
1652
1653 elif content_type == "text":
1654 text = msg['text'].replace("'", "")
1655
1656 try:
1657 msg['entities']
1658
1659 if ans == "2" and users[chat_id] == 3:
1660 sendMessage(chat_id, "Wait the end and repeat the step, did you think you could download how much songs you wanted? ;)")
1661 else:
1662 if ans == "2":
1663 users[chat_id] += 1
1664
1665 Thread(
1666 target = Link,
1667 args = (
1668 text, chat_id,
1669 qualit[chat_id], msg
1670 )
1671 ).start()
1672 except KeyError:
1673 sendMessage(chat_id, "Press",
1674 reply_markup = InlineKeyboardMarkup(
1675 inline_keyboard = [
1676 [
1677 InlineKeyboardButton(
1678 text = "Search artist",
1679 switch_inline_query_current_chat = "art: %s" % text
1680 ),
1681 InlineKeyboardButton(
1682 text = "Search album",
1683 switch_inline_query_current_chat = "alb: %s" % text
1684 )
1685 ],
1686 [
1687 InlineKeyboardButton(
1688 text = "Search playlist",
1689 switch_inline_query_current_chat = "pla: %s" % text
1690 ),
1691 InlineKeyboardButton(
1692 text = "Search label",
1693 switch_inline_query_current_chat = "lbl: %s" % text
1694 )
1695 ],
1696 [
1697 InlineKeyboardButton(
1698 text = "Search track",
1699 switch_inline_query_current_chat = "trk: %s" % text
1700 ),
1701 InlineKeyboardButton(
1702 text = "Search global",
1703 switch_inline_query_current_chat = text
1704 )
1705 ]
1706 ]
1707 )
1708 )
1709
1710try:
1711 print(
1712 """
1713 1): Free
1714 2): Strict
1715 """
1716 )
1717
1718 ans = input("Choose: ")
1719
1720 if ans == "1" or ans == "2":
1721 bot.message_loop(
1722 {
1723 "chat": start,
1724 "callback_query": download,
1725 "inline_query": search,
1726 "chosen_inline_result": nada
1727 }
1728 )
1729 else:
1730 exit()
1731
1732 print("Bot started")
1733
1734 while True:
1735 sleep(1)
1736 path = os.statvfs("/")
1737 free_space = path.f_bavail * path.f_frsize
1738
1739 if (del1 == del2 and is_audio == 0) or free_space <= 4000000000:
1740 del1 = 0
1741 del2 = 0
1742
1743 for a in os.listdir(loc_dir):
1744 try:
1745 rmtree(loc_dir + a)
1746 except NotADirectoryError:
1747 os.remove(loc_dir + a)
1748except KeyboardInterrupt:
1749 os.rmdir(loc_dir)
1750 print("\nSTOPPED")