浏览代码

added song search in youtube

tenessy0570 3 年之前
父节点
当前提交
fae0cf2671
共有 3 个文件被更改,包括 46 次插入2 次删除
  1. 18 1
      __init__.py
  2. 2 1
      commands_list_divided_with_newline
  3. 26 0
      utils.py

+ 18 - 1
__init__.py

@@ -3,7 +3,13 @@ from os import environ
 import environment_vars
 from decorators import author_is_not_bot, notify_if_wrong_command
 from img_urls import good_face_url
-from utils import on_ready_print, receive_message_then_send, get_commands_from_file
+from utils import (
+    on_ready_print,
+    receive_message_then_send,
+    get_commands_from_file,
+    message_is_song_name,
+    get_video_url_by_song_name
+)
 
 
 class MyClient(discord.Client):
@@ -34,6 +40,17 @@ class MyClient(discord.Client):
             await message.channel.send(embed=image_to_send)
             return
 
+        if message_is_song_name(message):
+
+            try:
+                url = get_video_url_by_song_name(message)
+            except NameError as error_info:
+                await message.channel.send(error_info)
+                return
+
+            await message.channel.send(url)
+            return
+
         return True
 
 

+ 2 - 1
commands_list_divided_with_newline

@@ -1,2 +1,3 @@
 face
-ping
+ping
+!song <your song name>

+ 26 - 0
utils.py

@@ -1,3 +1,6 @@
+from youtubesearchpython import VideosSearch
+
+
 def on_ready_print(self):
     print("---------")
     print("Logged as")
@@ -17,3 +20,26 @@ def get_commands_from_file(filename: str) -> tuple:
     with open(filename, 'r') as file:
         _help_commands = tuple((command.split('\n')[0] for command in file))
     return _help_commands
+
+
+def message_is_song_name(message):
+    return message.content.split(' ')[0] == '!song'
+
+
+def _get_song_name_from_message(message):
+    parsed_msg = message.content.split(' ')
+    if len(parsed_msg) == 1:
+        raise NameError("Song name can't be empty!")
+    return ''.join(message.content.split(' ')[1:])
+
+
+def _get_movie_id(videos_search):
+    return videos_search.result()['result'][0]['id']
+
+
+def get_video_url_by_song_name(message):
+    url = 'https://www.youtube.com/watch?v='
+    song_name = _get_song_name_from_message(message)
+    videos_search = VideosSearch(song_name, limit=1)
+    video_id = _get_movie_id(videos_search)
+    return url + video_id