iT邦幫忙

2021 iThome 鐵人賽

DAY 15
0
AI & Data

建立FF14資訊Discord chatbot系列 第 15

[DAY 15]cog架構用法(2/2)

  • 分享至 

  • twitterImage
  •  

cog架構還有一個很好用的功能是可以在不關bot的情況下將你寫的bot的功能進行讀取或卸載

主程式寫法

import discord
from discord.ext import commands
from dotenv import load_dotenv
import os


if __name__ == '__main__':

    intents = discord.Intents.default()
    intents.members = True
    bot = commands.Bot(command_prefix='?',intents =intents)

    #讀取Token
    load_dotenv()
    TOKEN = os.getenv('DISCORD_TOKEN')
    GUILDID_TOKEN = os.getenv('GUILDID_TOKEN')
    
    @bot.command()
    async def load(ctx,extension):
        bot.load_extension(f"cmds.{extension}")

    @bot.command()
    async def unload(ctx,extension):
        bot.unload_extension(f"cmds.{extension}")
    
    # bot.get_cog(Greetings(bot))
    for filename in os.listdir("./cmds"):
        if filename.endswith('.py'):
            bot.load_extension(f"cmds.{filename[:-3]}")
    
        
    bot.run(TOKEN)

其中load跟unload裡的extension是你的class名稱

cmds是你放你寫bot功能的資料夾

這邊放一個簡單的bot功能

class main(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        load_dotenv()
        self.TOKEN = os.getenv('DISCORD_TOKEN')
        self.GUILDID_TOKEN = os.getenv('GUILDID_TOKEN')
        #讀取字典
    
    @commands.command()
    async def ping(self,ctx):
        await ctx.send('Pong!')

因為我們在主程式:

bot = commands.Bot(command_prefix='?',intents =intents)

有規定前綴要用"?",記得在呼叫功能時加前綴

在頻道上打ping有出現反應

卸載掉main後打ping沒出現反應代表卸載成功,讀取main後打ping有反應代表讀取成功


上一篇
[DAY 14]cog架構用法(1/2)
下一篇
[DAY 16]用bot打出色色柴犬counter牌
系列文
建立FF14資訊Discord chatbot30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言