【问题标题】:Discord.py how do I run code from another file?Discord.py 如何从另一个文件运行代码?
【发布时间】:2022-01-18 03:36:03
【问题描述】:

我想稍微清理一下我的 Discord 机器人的代码,将命令拆分为不同的文件,而不是只有一个巨大的主文件。我知道我可以使用import [file] 直接从其他文件“导入”代码,但我无法使其与 Discord 代码一起使用。 如果我尝试类似:

test1.py

await ctx.send("successful")

main.py

@client.command()
asnyc def test(ctx):
   import test1

我总是收到错误 SyntaxError: 'await' outside function。我知道这是因为await 在任何异步函数之外,但我不知道如何修复它。如果我将test1.py 替换为print("successful") 之类的东西,它会向控制台打印正确的响应。我已经尝试过寻找解决方案,但越来越被它弄糊涂了。

【问题讨论】:

  • Python 导入不是包含。您可以从模块(.py 文件)导入对象,但它本身必须在语法上有效。

标签: python discord discord.py python-asyncio


【解决方案1】:

您应该导入函数并调用它们:

test1.py

async def run(ctx):
    await ctx.send("successful")

main.py

import test1

@client.command()
async def test(ctx):
   await test1.run(ctx)

(我想我的 awaits 和 asyncs 是正确的。)

import 语句的功能与 C++ 或 PHP 的 include 不同,后者有效地复制并粘贴包含的代码。 Python 的 import 有效地运行您正在导入的文件,并(以最简单的形式)将创建的任何项目添加到您当前的范围内。

【讨论】:

    【解决方案2】:

    Discord 有一个称为“扩展”的系统,专门用于将命令拆分为不同的文件。确保将整个函数放在文件中,而不仅仅是函数的一部分,否则 Python 会出错。这是一个直接取自文档的示例:

    主文件:

    ...create bot etc...
    bot.load_extension("test")  # use name of python file here
    ...run bot etc...
    

    其他文件(在本例中称为 test.py):

    from discord.ext import commands
    
    @commands.command()
    async def hello(ctx):
        await ctx.send('Hello {0.display_name}.'.format(ctx.author))
    
    def setup(bot):
        bot.add_command(hello)
    

    关键点是:(1)用setup函数创建python文件(2)加载扩展。

    有关详细信息,请参阅: https://discordpy.readthedocs.io/en/stable/ext/commands/extensions.html https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html

    【讨论】:

      【解决方案3】:

      你最好清理一下你的代码 :) 你必须时不时地这样做。要解决你的SyntaxError problem: 'await' outside function,由于你自己说的原因,你必须使用“import”语句,然后你必须把完整的函数放在文件中,而不是函数的片段。

      test1.py中,你需要在一个函数中写你的await ctx.send ("successful"),然后你需要写async def example (ctx):,然后在下面输入async def example(ctx):

      #test1.py
      
      async def example(ctx):
          await ctx.send("successful")
      

      在 main.py 中,您必须更改一些内容。您在函数内部导入了 test1,而必须在函数外部导入它。然后在你的async function def test (ctx): 中,你必须写await test1.example (ctx),其中test1 是文件,example 是 test1 函数的名称。

          #main.py
          
          #import your file here, and not inside the function
          import test1
          
          @client.command()
          async def test(ctx):
             await test1.example(ctx)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-18
        • 2012-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多