關於cog,當指令越寫越多的時候,可以運用Cog的架構。
Cog可以視為一個extension,也就是說可以取出來(可以取出來也代表可以拿出來),這就代表在開發的時候可以不用一值將bot開開關關
我們先使用!help
有load、unload、reload,讓你方便管理
# cogs/loadReload.py
import discord
from discord.ext import commands
from core.any import Cog_Extension
import json, os
with open('items.json', 'r', encoding='utf8') as file:
data = json.load(file)
class reloadCogs(Cog_Extension):
@commands.command()
@commands.is_owner() # 管理者才能使用
async def load(self, ctx, extension):
self.bot.load_extension(f'cogs.{extension}')
await ctx.author.send(f"{extension} 已上傳")
@commands.command()
@commands.is_owner()
async def unload(self, ctx, extension):
self.bot.unload_extension(f'cogs.{extension}')
await ctx.author.send(f'{extension} 已卸載')
@commands.command()
@commands.is_owner()
async def reload(self, ctx, extension):
# 如果直接更改程式碼的話就直接reload
self.bot.reload_extension(f'cogs.{extension}')
await ctx.author.send(f'{extension} 已更新')
def setup(bot):
bot.add_cog(reloadCogs(bot))
# cogs/ahoy.py
from discord.ext import commands
import discord
from discord.ext.commands import bot
from core.any import Cog_Extension
import json
with open('./items.json', "r", encoding = "utf8") as file:
data = json.load(file)
class Ahoy(Cog_Extension):
@commands.command(pass_context = True)
async def ahoy(self, ctx):
await ctx.send(file = discord.File('your gif or picture'))
def setup(bot):
bot.add_cog(Ahoy(bot))
{
"token":"your token",
"自訂":"your gif or picture"
}
await ctx.send(file = discord.File(data["自訂"]))
自己寫也可以,我們必須寫好title、description......等
# cogs/embeds.py
# 略
@commands.command(pass_context = True)
async def helping(ctx):
sms = discord.Embed(title = "指令",
description = "'忘記了嗎? 來看一下吧~~", color = 0x4599)
await ctx.send(embed = sms)
# 略
示意圖
接下來自行使用add_field()函數,添加中心骨幹
sms.add_field(name = "!ahoy", value = "Ahoy.gif", inline = True)
sms.add_field(name = "!clear", value = "用 !clear + 數字刪訊息", inline = True)
sms.add_field(name = "!sms", value = "等於 == !help", inline = True)
# url可以放在json檔
sms.set_thumbnail(url = "https://www.formula-ai.com/wp-content/uploads/2020/09/python_or_java_meme.jpg")