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

2022-09-28 21:52:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为discord制作一个机器人,到目前为止它工作正常,我让它搜索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])

我是新来的,我找不到一个好的例子来说明如何去做


Tags: comhttpsearchstringyoutubewww机器人contenturllibqueryresultswatchctxdiscordhtm
1条回答
网友
1楼 ·

您可以使用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

热门问题