前情提要
關於cog,當指令越寫越多的時候,可以運用Cog的架構。
Cog可以視為一個extension,也就是說可以取出來(可以取出來也代表可以拿出來),這就代表在開發的時候可以不用一值將bot開開關關
我們先使用!help
有load、unload、reload,讓你方便管理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| 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): self.bot.reload_extension(f'cogs.{extension}') await ctx.author.send(f'{extension} 已更新')
def setup(bot): bot.add_cog(reloadCogs(bot))
|
發送圖片
處理圖片和gif的方式一樣,這邊一樣直接上程式碼吧
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
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))
|
什麼是pass_context?
上述程式碼之中,有一個pass_context = True,這是什麼?
在discord1.0版,它的作用是不再傳遞上下文,而是將指定的文字作為參數傳遞給裝飾器
回到json檔
是時候該添加剛才的圖片(gif)了
1 2 3 4
| { "token":"your token", "自訂":"your gif or picture" }
|
如果以這種型式來看的話,上述程式碼的最後一行必須改成
1
| await ctx.send(file = discord.File(data["自訂"]))
|
添加元素
這裡提供快速的遷入訊息的作弊大法可供參考。
自己寫也可以,我們必須寫好title、description……等
1 2 3 4 5 6 7 8 9
|
@commands.command(pass_context = True) async def helping(ctx): sms = discord.Embed(title = "指令", description = "'忘記了嗎? 來看一下吧~~", color = 0x4599) await ctx.send(embed = sms)
|
示意圖
接下來自行使用add_field()函數,添加中心骨幹
1 2 3
| 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)
|
最後加張照片,這張照片會在右上角出現
1 2
| sms.set_thumbnail(url = "https://www.formula-ai.com/wp-content/uploads/2020/09/python_or_java_meme.jpg")
|
結果圖(忘記更新XD)
2.0部分更改
load_extension
變成協程
的架構囉!
這邊就簡單的示範一個
1 2 3 4 5 6 7
| @bot.command() async def load(ctx: commands.Context, extension): await bot.load_extension(f"cmds.{extension}") await ctx.send(f"Loaded {extension} done.")
|
還有這裡
1 2
| async def setup(bot: commands.Bot):: bot.add_cog(reloadCogs(bot))
|
然後快速遷入的部分可能也要瞄一下,具體來說那只是一個範例,如果是反覆嵌套的話沒注意一些細節會害死人的。
這裡可以看一下disnake.py-embed
反正除了disnake
要改回去discord
外,其他都大差不差。