Discord.py 如何从另一个文件运行代码?

问题描述 投票:0回答:3

我想清理一下我的 Discord 机器人的代码,将命令分成不同的文件,而不是只有一个巨大的主文件。我知道我可以简单地使用

import [file]
直接从其他文件“导入”代码,但我无法使其与 Discord 代码一起使用。 如果我尝试类似的事情:

测试1.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 discord discord.py python-asyncio
3个回答
3
投票

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

async 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


1
投票

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

测试1.py

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

main.py

import test1

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

(我认为我得到了

await
async
是正确的。)

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


1
投票

你最好清理一下你的代码:)时不时地你必须这样做。为了解决您的

SyntaxError problem: 'await' outside function
,由于您自己所说的原因,您必须使用“导入”语句,然后您必须将完整的函数而不是函数片段放入文件中。

test1.py
中,您需要在函数内编写
await ctx.send ("successful")
,然后需要编写
async def example (ctx):
,然后在下面输入 async def 示例 (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)
© www.soinside.com 2019 - 2024. All rights reserved.