首页 > 解决方案 > 如何制作多个文件 Python Bot

问题描述

如何从多个文件中加载命令 Python Bot 下面是我的 main.py 和其他带有命令的 python 文件。这是正确的方法还是我需要改变什么?我需要在所有文件中添加token, prefix,bot = commands.Bot等吗?bot.run(token)

主文件

token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
prefix = "?"

import discord
from discord.ext import commands
startup_extensions = ["second", "third"]

bot = commands.Bot(command_prefix=prefix)
bot.remove_command("help")

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')

@bot.command(pass_context=True)
async def hello1(ctx):
    msg = 'Hello {0.author.mention}'.format(ctx.message)
    await bot.say(msg)

bot.run(token)

第二个.py

import discord
from discord.ext import commands

class Second():
def __init__(self, bot):
    self.bot = bot

@commands.command(pass_context=True)
async def hello2(ctx):
    msg = 'Hello{0.author.mention}'.format(ctx.message)
    await bot.say(msg)

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

第三个.py

import discord
from discord.ext import commands

class Third():
def __init__(self, bot):
    self.bot = bot

@commands.command(pass_context=True)
async def hello3(ctx):
    msg = 'Hello{0.author.mention}'.format(ctx.message)
    await bot.say(msg)

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

标签: pythonpython-3.xdiscorddiscord.py

解决方案


你能做的是用 cogs 设置你的文件,例如你的主文件:

import discord
from discord.ext import commands

client = commands.Bot(command_prefix="!") # <- Choose your prefix


# Put all of your cog files in here like 'moderation_commands'
# If you have a folder called 'commands' for example you could do #'commands.moderation_commands'
cog_files = ['commands.moderation_commands']

for cog_file in cog_files: # Cycle through the files in array
    client.load_extension(cog_file) # Load the file
    print("%s has loaded." % cog_file) # Print a success message.

client.run(token) # Run the bot.

在你的 moderation_commands 文件中说它看起来像:

import discord
from discord.ext import commands

class ModerationCommands(commands.Cog):
    def __init__(self, client):
        self.client = client
    @commands.command(name="kick") # Your command decorator.
    async def my_kick_command(self, ctx) # ctx is a representation of the 
        # command. Like await ctx.send("") Sends a message in the channel
        # Or like ctx.author.id <- The authors ID
        pass # <- Your command code here

def setup(client) # Must have a setup function
    client.add_cog(ModerationCommands(client)) # Add the class to the cog.

您可以在此处找到有关 cogs 的更多信息:https ://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html


推荐阅读