最近回去修以前寫的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'
看了一些網路上文章還是不太懂哪裡寫錯了...還請知道的大大能夠幫我解惑!
你先檢查 Python 與 discord.py 模組的版本。
例如, discord.py 的 Bot.add_cog , 在文件內有提到, 從 v2.0 之後才改成 協程 (coroutine) 。