environment
Python 3.6.6
Discord.py-1.2.5
Directory structure
├ cogs
│ └ mainCmd.py
└ main.py
main.py
import discord
from discord.ext import commands
import traceback
DiscordBot_Cogs = [
'cogs.mainCmd'
]
class MyBot(commands.Bot):
def __init__(self, command_prefix):
super().__init__(command_prefix)
for cog in DiscordBot_Cogs:
try:
self.load_extension(cog)
except Exception:
traceback.print_exc()
async def on_ready(self):
print('BOT start')
if __name__ == '__main__':
bot = MyBot(command_prefix='!?')
bot.run('TOKEN')
mainCmd.py
from discord.ext import commands
class MainCmdCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def cmd(self, ctx):
await ctx.send("Received a command.")
def setup(bot):
bot.add_cog(MainCmdCog(bot))
main.py
DiscordBot_Cogs = [
'cogs.mainCmd'
]
Put 'cogs.mainCmd'
in the list DiscordBot_Cogs
.
When adding a Python file (cog) for commands, follow the list writing method.
DiscordBot_Cogs = [
'cogs.mainCmd',
'cogs.exampleCmd'
]
And.
cogs
is the folder name and mainCmd
is the file name without the extension.
for cog in DiscordBot_Cogs:
try:
self.load_extension(cog)
except Exception:
traceback.print_exc()
Turn the previous list with a for statement and use try & except to register the cog. (An error will occur if the file does not exist because the file name is incorrect.)
if __name__ == '__main__':
bot = MyBot(command_prefix='!?')
bot.run('TOKEN')
Characters to be added to the head with BOT commands (!?
In MonsterBOT, /
in Minecraft style)
mainCmd.py
@commands.command()
async def cmd(self, ctx):
await ctx.send("Received a command.")
Just type !? cmd
and I received thecommand on that channel. A command to send to
and BOT.
When using an argument for this, do as follows.
@commands.command()
async def cmd(self, ctx, *args):
if len(args) == 0:
await ctx.send("There are no arguments.")
if len(args) == 1:
await ctx.send("With one argument**" + args[0] + "**Is.")
if len(args) == 2:
await ctx.send("With two arguments**" + args[0] + "**When**" + args[1] + "**Is.")
The rest should be increased.
Recommended Posts