【问题标题】:(discord.py) functions in a cog(discord.py) 齿轮中的函数
【发布时间】:2021-01-20 13:10:05
【问题描述】:

我一直在尝试在 python 中开发一个不和谐的机器人,我想制作一堆在帮助中不显示的“隐藏”命令。我想这样做,以便每当有人激活隐藏命令时,机器人都会向他们发送 pm。我试图制作一个功能来做到这一点,但到目前为止它不起作用。这是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))

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

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    在调用 ctx.author.send 之类的异步函数时,您需要使用 await,因此您包装它的函数也需要是异步的

    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 是一个“未定义的名称”......
    • 那是因为您调用hidden_message 的方式是该函数位于全局范围内。由于hidden_message 应该是该类的方法,因此您必须对其进行定义,以便将self 属性作为参数。在example 中,您可以通过调用self.hidden_message(ctx) 来调用hidden_message
    • 哦,我的错,应该是self.hidden_message。我会修复我的帖子
    【解决方案2】:

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

    但是,由于hidden_message 的调用方式,会出现第二个问题。将hidden_message 称为hidden_message(ctx) 将需要在全局范围内定义函数。由于是class Hidden的方法,所以需要这样调用。

    突出显示编辑:

    class Hidden(commands.Cog):
        ...
        async def hidden_message(self, ctx):
            ...
    
        @commands.command()
        async def example(self, ctx):
            await ctx.send("yes")
            await self.hidden_message(ctx)
    
    

    【讨论】:

    • 所以在 cogs 中声明函数时需要使用 self 作为参数。谢谢,这有帮助!
    猜你喜欢
    • 2021-04-12
    • 2020-10-10
    • 2022-01-05
    • 2023-03-14
    • 1970-01-01
    • 2023-01-26
    • 2020-04-14
    • 2013-07-10
    • 1970-01-01
    相关资源
    最近更新 更多