首页 > 解决方案 > 如何从不同文件导入函数并在 discord.py 中使用

问题描述

一个直截了当的问题 - 如何从不同的文件中导入函数并在 discord.py 中使用它,因为我尝试过但失败了,例如文件 a 和 b 看起来像 a.py:

async def joke(ctx):
   joke = 'Your mama so fat boy'
   await ctx.send(joke)

我想使用从文件 a 到文件 b 的笑话函数,我写的代码是:

from a import joke
from discord.ext import commands
#some discord code
TOKEN = 'My_Secret_Token'
GUILD = 'My_Guild'
client = commands.Bot(command_prefix='!')
@client.command(name='joke', help='This will return a joke')
joke()
client.run(TOKEN)

joke() 行返回错误

  File "main.py", line 31
    joke()
    ^
SyntaxError: invalid syntax

我在这里很困惑,为什么它会返回错误以及如何传递参数 ctx。所以请为我想出一个解决方案。

编辑:在调试和挠头几个小时后,我想出了一个同样不起作用的解决方案,我稍微修改了我的 b.py:

from a import joke
from discord.ext import commands
#some discord code
TOKEN = 'My_Secret_Token'
GUILD = 'My_Guild'
client = commands.Bot(command_prefix='!')
@client.command(name='joke', help='This will return a joke')
async def my_function(ctx):
    joke(ctx)
client.run(TOKEN)

标签: python-3.xdiscord.py

解决方案


您可以为此使用齿轮。文档:https
://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html 这是一个示例: Your main.py

import discord
from discord.ext import commands
import os

client = commands.Bot(command_prefix='!')

for file in os.listdir("cogs"):
    if file.endswith(".py"):
        name = file[:-3]
        client.load_extension(f"cogs.{name}")


client.run(TOKEN)

做一个/cogs/joke.py

import discord
from discord.ext import commands
import random

class joke(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def joke(self, ctx):
        jokes = [
        'Your mama so fat boy',
        'joke2',
        'joke3',
        'joke4',
        'joke5'
        ]
        answer = random.choice(jokes)
        await ctx.send(answer)

def setup(bot):
    bot.add_cog(joke(bot))

推荐阅读