我正在制作一个机器人来测试我的 Python 技能,我正在尝试让它搜索 youtube

时间:2021-01-28 12:43:43

标签: python youtube bots discord.py

我正在制作一个不和谐的机器人,到目前为止它可以工作,我让它搜索youtube并显示结果,但只有第一个,我希望它显示一个列表,您可以从中选择显示.

这是我有的代码

async def yt(ctx, self, *, search):
    
    query_string = urllib.parse.urlencode({'search_query': search})
    htm_content = urllib.request.urlopen(
        'http://www.youtube.com/results?' + query_string)
    search_results = re.findall(r'/watch\?v=(\S{11})',
                                htm_content.read().decode())
    await ctx.send('http://www.youtube.com/watch?v=' + search_results[0])

我是新手,我找不到一个很好的例子来说明如何做到这一点。

1 个答案:

答案 0 :(得分:0)

您可以使用 Embed() 显示带有选择选项的列表,并使用 add_reaction() 添加带有您可以单击的 emoji 的按钮。接下来您需要 wait_for('reaction_add',...) 等待点击按钮。接下来,您可以删除带有选项的消息并发送带有所选项目的消息。

import os
from discord import Embed
from discord.ext import commands
from discord.ext.commands import Bot

bot = commands.Bot(command_prefix='!')

@bot.command(aliases=['yt'])
async def youtube(ctx):
    
    # search results
    options = ['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF', 'GGG', 'HHH']
    
    # convert list to dictionary with emoji as key
    codepoint_start = 127462  # Emoji `A`
    options = {chr(i): f"{chr(i)} - {v}" for i, v in enumerate(options, start=codepoint_start)}

    # create list to display
    embed = Embed(title='Select', description="\n".join(options.values()))
    
    # display it as message
    message = await ctx.send(embed=embed)

    # add reactions to get selection    
    for reaction in options:
        await message.add_reaction(reaction)

    # function which check if selection is correct
    def check(reaction, user):
        return user != message.author and str(reaction.emoji) in list(options)

    # wait for selection
    reaction, user = await bot.wait_for('reaction_add', check=check)
        
    # remove message with options
    await message.delete()
    
    # send selection    
    selected = options[reaction.emoji]
    selected = selected.split(' - ', 1)[-1] # remove emoji 
    #print('selected:', selected)
    await ctx.send(selected)
    
# --- main ---

print('start bot')
TOKEN = os.getenv('DISCORD_TOKEN')
bot.run(TOKEN)  # `bot`, not `client`
print('stop bot')

enter image description here