以下是我个人在使用Python创建Discord BOT时经常使用的模板(备忘录):

前提 – Only need one option.

Python 3.6.6
Discord.py-1.2.5
├ cogs
│   └ mainCmd.py
└ main.py

代码 (Mandarin Chinese)

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') 
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))

说明和警告

主要的.py

DiscordBot_Cogs = [
    'cogs.mainCmd'
]

将’cogs.mainCmd’添加到名为DiscordBot_Cogs的列表中。
在添加命令用的Python文件(cog)时,请按照列表的格式进行。

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语句来注册COG。(如果文件名错误或文件不存在,将会抛出错误。)

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

在BOT的指令中,頭部需要加上一個字元(像是MonsterBOT的話,可以形容成類似於Minecraft中的/)

主命令.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] + "** である。")

只需要增加就可以了。

广告
将在 10 秒后关闭
bannerAds