首页 > 解决方案 > 我正在使用 discord.py,我想发出一个命令,发件人要求在 youtube 中搜索特定视频,并在新选项卡中打开它

问题描述

我正在使用 discord.py,我想发出一个命令,发件人在 YouTube 中请求特定视频,并在新选项卡中为他们打开该视频,但我不知道如何。有人知道吗?

标签: discord.py

解决方案


import discord
from discord.ext import commands
import urllib.request
import urllib.parse
import re

token = "" # Insert your token on the left side
prefix = "" # Insert your prefix on the left side
bot = commands.Bot(command_prefix=prefix) # Define bot as a discord bot

@bot.event
async def on_ready(): # This part is when the bot is connected, it will print a message in the console
  print(f"Logged in as {bot.user}")
  return

@bot.command(name="search",help="Search something on YouTube") # The “name” and “help” attributes are optional
async def search(ctx, *, query): # Defining a bot command
  encodedQuery = urllib.parse.quote_plus(query) # URL Encode your search query (using the plus symbol for spaces)
  html = urllib.request.urlopen(f"https://www.youtube.com/results?search_query={encodedQuery}") # Request the HTML
  video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode()) # Find video IDs
  yt_url = f"https://youtube.com/watch?v={video_ids[0]}" # Use a the video ID and f-strings to build the YT URL
  await ctx.message.reply(f"Here you are:\n{yt_url}") # Sends it :)

bot.run(token)

资源:


推荐阅读