discord.py - 我正在使用 discord.py,我想发出一个命令,发件人要求在 youtube 中搜索特定视频,并在新选项卡中打开它
问题描述
我正在使用 discord.py,我想发出一个命令,发件人在 YouTube 中请求特定视频,并在新选项卡中为他们打开该视频,但我不知道如何。有人知道吗?
解决方案
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)
资源:
推荐阅读
- python - list[:] 的浅拷贝
- java - 在 EJB 中安排类似 Cron 的作业
- python - 无法导入 normalize_corpus python 3
- reactjs - 测试用 recompose 组成的多个 HOC
- php - 如何检测字符串是否包含 PHP 代码?PHP
- c# - 如何在 c# 中创建一个类,以便我可以单击一个表单上的按钮来更新第二个表单上的数据?
- xaml - 是否可以使 Canvas 字段的背景颜色取决于其值?
- jenkins - 如何在管道电子邮件分机内容中使用 ${TEST_COUNTS,var="TYPE"}
- swift - 如何在 swift 5 中使用“Data.withUnsafeMutableBytes”
- android - Acengage:推送通知不起作用