#python #error-handling #discord.py
Вопрос:
похоже, что файл cogs не работает, когда я пытаюсь запустить своего бота discord. Я даже пытаюсь использовать нагрузку в Диссонансе. я уже смотрю много видео о винтиках и читаю документацию, но не могу найти никакого решения. Кто-нибудь может заметить ошибку ? Вот мой файл cogs
import discord
from discord.ext import commands, tasks
from itertools import cycle
class UpdateCode(commands.Cog) :
def _init_(self, client) :
self.client = client
@ commands.Cogs.listener()
async def on_ready(self):
print("We have logged in as {0.user}".format(self.client))
self.status_swap.start()
self.status = cycle([
" Unanswered Question of Life",
" Self - Referential Paradox",
" Near-infinite density?",
" Dark matter ?",
" Measurement of the speed of light in one straight line",
" Schrodinger's cat ???"
"436c69636b2074686973206c696e6b20666f72206672656520766275636b7320212121212121203a200a68747470733a2f2f7777772e796f75747562652e636f6d2f77617463683f763d6451773477395767586351 (try to decrypt this)",
"The light side of Discord is the path of many unnatural abilities"
])
@ tasks.loop(minutes = 5)
async def status_swap(self):
await self.client.change_presence(activity = discord.Game(next(self.status)))
def setup(client) :
client.add_cog(UpdateCode(client))
Вот мой основной файл
import discord
import os
from discord.ext import commands, tasks
from online import keep_alive
client = commands.Bot(command_prefix = "!")
@ client.command()
async def load(ctx,extension) :
client.load_extension(f"cogs.{extension}")
@ client.command()
async def unload(ctx,extension) :
client.unload_extension(f"cogs.{extension}")
for filename in os.listdir('./cogs') :
if filename.endswith('.py') :
client.load_extension(f'cogs.{filename[:-3]}')
keep_alive()
client.run(os.getenv('MATH_VAR'))
В этом и заключается ошибка
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 848, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/runner/Math-Bot/cogs/update.py", line 6, in <module>
class UpdateCode(commands.Cog) :
File "/home/runner/Math-Bot/cogs/update.py", line 11, in UpdateCode
@ commands.Cogs.listener()
AttributeError: module 'discord.ext.commands' has no attribute 'Cogs'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 18, in <module>
client.load_extension(f'cogs.{filename[:-3]}')
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.update' raised an error: AttributeError: module 'discord.ext.commands' has no attribute 'Cogs'
Если вы знаете, как устранить эту ошибку, пожалуйста, прокомментируйте мой код. Спасибо.
Ответ №1:
Анализ ошибки
Устранение первой части ошибки:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 848, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/runner/Math-Bot/cogs/update.py", line 6, in <module>
class UpdateCode(commands.Cog) :
File "/home/runner/Math-Bot/cogs/update.py", line 11, in UpdateCode
# First hint which points to your code.
@ commands.Cogs.listener()
# Second hint which points the problem in your code.
AttributeError: module 'discord.ext.commands' has no attribute 'Cogs'
Ссылка на существующий код
Во-вторых, вы можете сослаться на то UpdateCode
, как определяется винтик, на чем он основан command.Cog
, а не command.Cogs
на чем . class UpdateCode(commands.Cog)
обратите внимание на пропущенную букву «s».
Вывод
Основываясь на первых двух замечаниях, которые я сделал, мы можем сделать вывод, что была небольшая ошибка, когда вы определили @ commands.Cogs.listener()
декоратора, включив » s «в слово «Винтик».