【问题标题】:Discord music bot fiding yt videoDiscord 音乐机器人查找 yt 视频
【发布时间】:2021-07-06 22:45:28
【问题描述】:

您好,我想知道如何让我的机器人根据 YouTube 搜索播放音乐,因为复制和粘贴 url 让我很生气。机器人有 youtube_dl 和 ffmpg。这是更新的代码,它仍然无法正常工作。对不起我的英语不好。

    @client.command(pass_context=True, aliases=['p', 'pla'])
async def play(ctx, url: str):

    song_there = os.path.isfile("song.mp3")
    try:
        if song_there:
            os.remove("song.mp3")
            print("Usunięto starą piosenke.")
    except PermissionError:
        print("Próbuję usunąć plik utworu, ale jest on odtwarzany ")
        await ctx.send(":no_entry_sign:  Muzyka już gra!")
        return

    await ctx.send(":mag_right: Szukanie i Pobieranie")

    voice = get(client.voice_clients, guild=ctx.guild)

    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }

    yt = yt_search.build(url)
    search_result = yt.search("keyword", sMax=10, sType=["video"])
    print(search_result)

    with youtube_dl.YoutubeDL(options) as ytdl:
        if url[:4] == 'http':
            ytdl.download([url])
        else: # "yts" is youtube-search imported as
            link = json.loads(yts(url, max_results=1).to_json())['videos'][0]['url_suffix']
            link = 'https://www.youtube.com' + link
            ytdl.download([link])

    for file in os.listdir("./"):
        if file.endswith(".mp3"):
            name = file
            print(f"Zmnieniono nazwe: {file}\n")
            os.rename(file, "song.mp3")

    voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: print("Koniec!"))
    voice.source = discord.PCMVolumeTransformer(voice.source)
    voice.source.volume = 0.17

    nname = name.rsplit("-", 2)
    await ctx.send(f" :notes: Teraz Leci: `{nname[0]} - {nname[1]}`")
    print("Puszczanie\n")

【问题讨论】:

    标签: python python-3.x discord discord.py


    【解决方案1】:

    在 youtube-search 上查找文档。这是一个例子:

      with youtube_dl.YoutubeDL(options) as ytdl:
        if url[:4] == 'http':
          ytdl.download([url])
        else: # "yts" is youtube-search imported as
          link = json.loads(yts(url, max_results=1).to_json())['videos'][0]['url_suffix']
          link = 'https://www.youtube.com' + link
          ytdl.download([link])
    

    基本上是说“如果它以 http 开头,则仅用作链接。否则,使用 youtube-search 获取 YouTube 上第一个搜索结果的链接。”这可能不是一个好方法,也许使用 try/except 来查看搜索是否首先作为链接工作,除了重试传递获取的链接。

    【讨论】:

    • 你导入了 json 和 youtube_search
    • 是的,我导入了它仍然无法正常工作
    • 当你输入一个命令,一个歌名机器人写他正在寻找这首歌,然后在终端或不和谐中什么都没有发生,没有错误
    • 我编辑的问题太长,无法评论
    • 确保匹配变量名。例如,您的 youtube-dl 选项称为“ydl_​​options”,而 with 语句传入“选项”。
    猜你喜欢
    • 2021-05-27
    • 1970-01-01
    • 2019-04-30
    • 2021-05-24
    • 2018-07-24
    • 2022-12-20
    • 2020-05-15
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多