Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python (discord.py)在cog中起作用_Python_Discord.py - Fatal编程技术网

Python (discord.py)在cog中起作用

Python (discord.py)在cog中起作用,python,discord.py,Python,Discord.py,我一直在尝试用python开发一个discord bot,我想生成一组“隐藏”命令,这些命令不会出现在帮助中。我想让它,每当有人激活一个隐藏的命令,机器人发送给他们一个下午。我试着做一个函数来实现它,但到目前为止还没有成功。以下是cog文件中的代码: import discord from discord.ext import commands class Hidden(commands.Cog): def __init__(self, client): self.client =

我一直在尝试用python开发一个discord bot,我想生成一组“隐藏”命令,这些命令不会出现在帮助中。我想让它,每当有人激活一个隐藏的命令,机器人发送给他们一个下午。我试着做一个函数来实现它,但到目前为止还没有成功。以下是cog文件中的代码:

import discord
from discord.ext import commands

class Hidden(commands.Cog):
  def __init__(self, client):
    self.client = client
  
  def hidden_message(ctx):
    ctx.author.send('You have found one of several hidden commands! :shushing_face:\nCan you find them all? :thinking:')

  @commands.command()
  async def example(self, ctx):
        
    await ctx.send('yes')

    hidden_message(ctx)

def setup(client):
  client.add_cog(Hidden(client))

运行示例命令时,bot会正常响应,但不会调用该函数。控制台中没有错误消息。我对python还是相当陌生,所以有人能告诉我我做错了什么吗?

在调用异步函数(如
ctx.author.send
)时,您需要使用
wait
,因此您包装的函数也需要是异步的

async def hidden_message(self, ctx):
    await ctx.author.send('You have found one of several hidden commands! :shushing_face:\nCan you find them all? :thinking:')
然后

@commands.command()
async def example(self, ctx):
    await ctx.send('yes')
    await self.hidden_message(ctx)
最后,要使命令在默认帮助命令中隐藏,可以执行以下操作

@commands.command(hidden=True)

为了发送消息,
hidden_message
必须是courotine,即它使用
async def
而不仅仅是
def

但是,由于如何调用
hidden_message
,出现了第二个问题。调用
hidden_message
作为
hidden_message(ctx)
需要在全局范围内定义函数。由于它是
类隐藏的方法
,因此需要这样调用它

突出显示编辑内容:

类隐藏(commands.Cog):
...
异步def隐藏_消息(self,ctx):
...
@commands.command()
异步定义示例(self、ctx):
等待ctx发送(“是”)
等待自我隐藏信息(ctx)

哦,我明白了。谢谢我修复了代码,但现在当我尝试调用函数时,它说hidden_message是一个“未定义的名称”…这是因为如果函数位于全局范围内,则调用
hidden_message
的方式是。由于
hidden_message
应该是类的一个方法,因此必须对其进行定义,以便它将
self
属性作为参数。在
示例中
,然后通过调用
self.hidden\u message(ctx)
调用
hidden\u message
。哦,我的错误,应该是
self.hidden\u message
。我将修复我的post,因此在cogs中声明函数时需要使用self作为参数。谢谢,这很有帮助!