python - 如何忽略 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 之间添加了参数 *,这并没有解决它
解决方案
不可能“忽略”上下文参数,为什么要在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)
从现在开始,每个命令都应该正常工作。
参考:
推荐阅读
- java - 带有 InputFilter 的 android 自定义正则表达式
- buffer - 如何在 gltf 2.0 中使用多个缓冲区?
- sails.js - Sails.js - 服务与助手
- java - 我想用 Java 代码插入 Oracle 表,但在 PreparedStatement 上出现错误
- ios - 当我展示另一个视图控制器时,NSTimer 不会停止
- android - 如何覆盖部分应用程序的主题?
- prometheus - 如何在普罗米修斯中搜索在标签上应用二元运算符?
- javascript - javascript:将实际的 html 代码发送到 url
- python - 如何创建保存日志文件的路径?每次都保存在单独的日志文件中?
- python - 加入列并在行中重塑