【发布时间】:2018-11-13 15:52:25
【问题描述】:
如何从多个文件中加载命令 Python Bot 下面是我的 main.py 和其他带有命令的 python 文件。这是正确的方法还是我需要改变什么?我需要在所有文件中添加token、prefix、bot = commands.Bot、bot.run(token) 等。
main.py
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)
second.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))
third.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))
【问题讨论】:
-
discord.py具有“cogs”的概念,即您的机器人可以加载的命令、事件等组。见this example。你用的是什么版本的discord.py? -
@PatrickHaugh 我使用的是 0.16.12 版本。
-
那你应该看看this example。
-
您在 cog 中对
bot的所有剩余引用都应更改为self.bot。 -
不,这里的
__main__指的是the main script being run in the interpreter,而不是main.py文件。我会按原样使用该代码。
标签: python python-3.x discord discord.py