首页 > 解决方案 > 如何忽略 discord.py 中的 ctx 参数?

问题描述

这是完整的脚本:

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 之间添加了参数 *,这并没有解决它

标签: pythondiscord.py

解决方案


不可能“忽略”上下文参数,为什么要在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")

我猜你的命令不起作用,因为你没有在事件process_commands结束时添加on_message

@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)

从现在开始,每个命令都应该正常工作。

参考:


推荐阅读