在bot.py的所在的資料夾中,開一個資料夾Cog
打開main檔案,開始把指令搬家囉
先打出這個基本的Cog結構
import discord
from discord.ext import commands
class Main(commands.Cog):
def __init__(self, bot):
self.bot = bot
def setup(bot):
bot.add_cog(Main(bot))
將 ping 和 purge 兩個指令剪下貼上到class Main裡面
修改 ping 和 purge 指令
Note: 直接寫在 bot.py和寫成Cog主要有兩個不同,第一是修飾器,第二個則是 function的參數一定要有self,Cog因為是一個class,所以每個function的第一個參數都必須是self
command | event | |
---|---|---|
bot.py | @bot.command() | @bot.event |
Cog | @commands.command() | @commands.Cog.listener() |
import discord
from discord.ext import commands
class Main(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
await ctx.send(self.bot.latency)
@commands.command()
async def purge(self, ctx, num=1):
deleted = await ctx.channel.purge(limit=num+1)
await ctx.send(f'{len(deleted)} messages deleted!')
def load(bot):
bot.add_cog(Main(bot))
import discord
from discord.ext import commands
import random
import json
with open('setting.json', 'r', encoding='utf8') as jsonFile:
setting = json.load(jsonFile)
class Image(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def image(self, ctx):
dcFile = discord.File(random.choice(setting['image']))
await ctx.send(file=dcFile)
@commands.command()
async def webimage(self, ctx):
await ctx.send(random.choice(setting['webimage']))
def setup(bot):
bot.add_cog(Image(bot))
Note: 由於這個Cog全部都是event,修飾器是用@commands.Cog.listener(),而不是之前的@commands.command()
import discord
from discord.ext import commands
import json
with open('setting.json', 'r', encoding='utf8') as jsonFile:
setting = json.load(jsonFile)
class Event(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(self, member):
ch = self.bot.get_channel(int(setting['channel_id']))
await ch.send(f'{member} Ya hello')
@commands.Cog.listener()
async def on_member_remove(self, member):
ch = self.bot.get_channel(int(setting['channel_id']))
await ch.send(f'{member} Bye bye')
@commands.Cog.listener()
async def on_message(self, msg):
if 'Yo' in msg.content and msg.author != self.bot.user:
await msg.channel.send('Yo')
await self.bot.process_commands(msg)
def setup(bot):
bot.add_cog(Event(bot))
Note: 這裡的load功能其實就有點像是程式開頭的from … import …
for cog in [p.stem for p in Path(".").glob("./Cog/*.py")]:
bot.load_extension(f'Cog.{cog}')
print(f'Loaded {cog}.')
print('Done.')
@bot.command()
async def load(ctx, ext):
bot.load_extension(f'Cog.{ext}')
await ctx.send(f'{ext} loaded successfully.')
@bot.command()
async def unload(ctx, ext):
bot.unload_extension(f'Cog.{ext}')
await ctx.send(f'{ext} unloaded successfully.')
@bot.command()
async def reload(ctx, ext):
bot.reload_extension(f'Cog.{ext}')
await ctx.send(f'{ext} reloaded successfully.')
我們可以直接使用內建的 on_command_error 事件,幫助我們把這些錯誤訊息傳送至頻道
示意圖
@commands.Cog.listener()
async def on_command_error(self, ctx, err):
await ctx.send(err)