如何忽略discord.py中的ctx参数?

2024-05-21 20:45:10 发布

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

以下是完整的脚本:

from discord.ext.commands import Bot
import tracemalloc

tracemalloc.start()
client = Bot(command_prefix='$')
TOKEN = ''

@client.event
async def on_ready():
    print(f'Bot connected as {client.user}')
    
@client.command(pass_context=True)
async def yt(ctx, url):
    author = ctx.message.author
    voice_channel = author.voice_channel
    vc = await client.join_voice_channel(voice_channel)
    player = await vc.create_ytdl_player(url)
    player.start()

@client.event
async def on_message(message):
    if message.content == 'play':
        await yt("youtubeurl")
client.run(TOKEN)

当我运行这个脚本时,它工作得很好。当我在聊天中键入play时,出现以下错误:

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\user\bot.py", line 26, in on_message
    await yt("youtubeurl")
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 374, in __call__
    return await self.callback(*args, **kwargs)
TypeError: yt() missing 1 required positional argument: 'url'

我该如何解决这个问题?到目前为止,我所尝试的只是在ctx和url之间添加了参数*,但并没有解决这个问题


Tags: clienteventurlmessageasyncondefbot
1条回答
网友
1楼 · 发布于 2024-05-21 20:45:10

无法“忽略”上下文参数,为什么要在on_message事件中调用该命令

您可以使用Bot.get_context获取上下文

@client.event
async def on_message(message):
    ctx = await client.get_context(message)
    if message.content == 'play':
        yt(ctx, "url")

我猜您的命令不起作用,因为您没有在on_message事件末尾添加process_commands

@client.event
async def on_message(message):
    # ... PS: Don't add the if statements for the commands, it's useless
    await client.process_commands(message)

从现在起,每个命令都应该起作用

参考资料:

相关问题 更多 >