iT邦幫忙

0

Discord Bot Cog功能Python載入問題

  • 分享至 

  • xImage

最近回去修以前寫的Discord Bot,不過在載入Cog功能上有點問題...

以下是我用Python 3.8 寫的Discord bot架構
cog功能放在 專案的 cmds 資料夾下

bot 執行檔案(main.py)

import discord
from discord.ext import commands, tasks
import json
import os
import asyncio

intent = discord.Intents.all()
intent.members = True

with open('setting.json', 'r', encoding='utf8') as jfile:
    jdata = json.load(jfile)
    
bot = commands.Bot(command_prefix='_', intents=intent)

@bot.event
async def on_ready():
    print(f"目前登入身份 --> {bot.user}")
    
async def cog_load_extensions():
   for Filename in os.listdir('./cmds'):
      if Filename.endswith('.py'):
         extension = Filename[:-3]
         try:
            print(f"Loaded extension cmds.{extension}")
            await bot.load_extension(f"cmds.{extension}")
         except Exception as e:
            exception = f"{type(e).__name__}: {e}"
            print(f"Failed to Loaded extension '{extension}' '{exception}'")  

async def main():
  await cog_load_extensions()
  await bot.start(jdata['Token'])

if __name__ == "__main__":
    asyncio.run(main())

重複函數繼承(core/classes.py)

import discord
from discord.ext import commands

class Cog_Extension(commands.Cog):
     def __init__(self,bot):
          self.bot = bot

cog指令功能(cmds/main.py)

import discord
import datetime
import pytz
from discord.ext import commands
from discord.ext.commands import MissingPermissions
from core.classes import Cog_Extension

class main(Cog_Extension):
  
    @commands.command()
    async def ping(self,ctx):
        await ctx.send(f'{round(self.bot.latency*1000)} (ms)')
        
async def setup(bot):
    await bot.add_cog(main(bot))

執行起來會跳錯誤訊息
.../python3.8/site-packages/discord/ext/commands/bot.py:618: RuntimeWarning: coroutine 'setup' was never awaited setup(self)

上面 cog_load_extensions 抓出的例外是顯示這個
'TypeError: object NoneType can't be used in 'await' expression'

看了一些網路上文章還是不太懂哪裡寫錯了...還請知道的大大能夠幫我解惑!

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
re.Zero
iT邦研究生 5 級 ‧ 2023-05-25 21:50:28
最佳解答

你先檢查 Python 與 discord.py 模組的版本。
例如, discord.pyBot.add_cog , 在文件內有提到, 從 v2.0 之後才改成 協程 (coroutine)

chitose iT邦新手 5 級 ‧ 2023-05-25 23:25:46 檢舉

哦哦!!我去查看後才發現沒更新版本上去哈哈XDD修正版本後就正常了...感謝~

我要發表回答

立即登入回答