python-3.x - 如何从不同文件导入函数并在 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)
解决方案
您可以为此使用齿轮。文档: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))
推荐阅读
- sql - 如何在 SQL 中计算学年?
- python - discord.py BS4 无法从 href 元素中获取信息
- python-3.x - Scrapy 在分页中提供了模棱两可的结果
- node.js - nodejs fs.WriteStream.write(chunk) “原子” wrt 异步事件是什么?
- react-native - React Native Expo:使用任务管理器在后台获取地理位置
- java - 如何并行调用多个Flowable语句?
- html - 当文件从另一个文件扩展时,不显示 .html 文件的内容
- c++ - 无法在 Ubuntu Conda 环境中编译 R 包:x86_64-conda-linux-gnu-c++:未找到
- python - 如何正确安装最新版本的 pygame?
- gekko - 使用 GEKKO 作为运动自行车模型不同控制算法的模拟器