【发布时间】:2021-10-04 08:57:22
【问题描述】:
简单。我正在使用 python 为不和谐创建一个 youtube 搜索命令 这是代码:
async def youtube(ctx, *, 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('href=\"\\/watch\\?v=(.{11})', htm_content.read().decode())
await ctx.send('http://www.youtube.com/watch?v=' + search_results[0])
我遇到的错误是这样的:
Ignoring exception in command youtube:
Traceback (most recent call last):
File "C:\Users\Ryzen\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Ryzen\Desktop\ae\bot\bot 2.0\bot.py", line 738, in youtube
await ctx.send('http://www.youtube.com/watch?v=' + search_results[0])
IndexError: list index out of range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Ryzen\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Ryzen\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Ryzen\AppData\Roaming\Python\Python37\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
谢谢
【问题讨论】:
-
...m/watch?v=' + search_results[0]可能列表为空且没有 0 索引。? -
尼梅什卡是正确的。最重要的是,您正在使用 asyncio,因此您应该使用 aiohttp。
标签: python discord discord.py