python - 如何制作多个文件 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))
解决方案
你能做的是用 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
推荐阅读
- webpack - 如何摇树 Webpack 供应商块文件?
- firebase - 如何根据颤动中那些文档中的特定值从firebase firestore检索文档?
- google-workspace - 如何在 GSuite 域应用程序脚本中触发电子邮件密码更改
- snowflake-cloud-data-platform - 在雪花中,我可以列出所有数据库及其大小吗?
- c# - Web 应用程序中 WMI 获取 API 中的“访问被拒绝”错误
- mysql - MySQL - 几何
- javascript - 等待 axios 获取请求中的 setTimeout()
- latex - 当内容大小增加时,如何防止带有 \hline 的长表在新页面上开始?
- c++ - 在OpenGL中从上方移动相机
- python - 需要帮助在 python 上将底图转移到 cartopy