3
7

More than 3 years have passed since last update.

DiscordBOTをPythonで作るときの個人的によく使うテンプレート(備忘録)

Last updated at Posted at 2020-03-07

前提

環境
Python 3.6.6
Discord.py-1.2.5
ディレクトリ構造
├ 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起動')

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("コマンドを受信しました。")

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

説明と注意書き

main.py

DiscordBot_Cogs = [
    'cogs.mainCmd'
]

DiscordBot_Cogsというリストの中に'cogs.mainCmd'を入れる。
コマンド用Pythonファイル(コグ)を追加するときはリストの書き方に従って

DiscordBot_Cogs = [
    'cogs.mainCmd',
    'cogs.exampleCmd'
]

とする。
cogsはフォルダ名でmainCmdは拡張子なしのファイル名。

for cog in DiscordBot_Cogs:
    try:
        self.load_extension(cog)
    except Exception:
        traceback.print_exc()

先ほどのリストをfor文で回してtry&exceptを使ってコグを登録する。(ファイル名が間違っていたりしてファイルが存在しなかった場合にエラーが出る。)

if __name__ == '__main__':
    bot = MyBot(command_prefix='!?')
    bot.run('TOKEN') 

BOTのコマンドで頭に付ける文字(MonsterBOTだと!?、Minecraft風に言えば/

mainCmd.py

@commands.command()
async def cmd(self, ctx):
    await ctx.send("コマンドを受信しました。")

!?cmdと打つだけでそのチャンネルでコマンドを受信しました。とBOTに送らせるコマンド。

これに引数を使うときは以下のようにすればよい。

@commands.command()
async def cmd(self, ctx, *args):
    if len(args) == 0:
        await ctx.send("引数が存在しない。")
    if len(args) == 1:
        await ctx.send("引数が1つで **" + args[0] + "** である。")
    if len(args) == 2:
        await ctx.send("引数が2つで **" + args[0] + "** と **" + args[1] + "** である。")

あとは増やしていけばよい。

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7