Я не знаю, как импортировать функцию Cog в мой Main.py для моего бота DiscordPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Я не знаю, как импортировать функцию Cog в мой Main.py для моего бота Discord

Сообщение Anonymous »

Я пытаюсь создать бот -разборовой, который позволит мне запустить команду из другого файла, используя CoG, но, кажется, возникают проблемы, когда я пытаюсь добавить свой винтов в свой файл main.py.

Код: Выделить всё

import discord
import os
import asyncio
from discord.ext import commands

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

async def load():
for filename in os.listdir('./cogs'):
if filename.endswith(".py"):
cog_name = filename[:-3]  # Remove the '.py' extension
cog_path = f'cogs.{cog_name}'  # Construct the full path to the cog
try:
bot.load_extension(cog_path)
print(f"Loaded extension: {cog_name}")
except commands.ExtensionAlreadyLoaded:
print(f"Extension {cog_name} is already loaded.")
except commands.ExtensionNotFound:
print(f"Extension {cog_name} not found.")

@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.dnd, activity=discord.Game('Playing Call of Duty: Modern Warfare 3'))
print("--------------------------------------------")
print("Bot is ready")
print("--------------------------------------------")

@bot.command()
async def hello(ctx):
await ctx.send(f"Hello there, {ctx.author.mention}!")

my_files = ["ban"]

for file in my_files:
bot.load_extension(f"cogs.ban")

with open("token.txt") as file:
token = file.read()

bot.run(token)
< /code>
А вот код для моей команды, я хочу, чтобы он мог запустить (это команда запрета): < /p>
import discord
from discord.ext import commands

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

@commands.command()
@commands.has_permissions(ban_members=True)
async def ban(self, ctx, member: discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.send(f"{member} has been banned!")

def setup(bot):
bot.add_cog(Ban(bot))
< /code>
Каждый раз, когда я запускаю его, всегда дает мне следующее сообщение об ошибке: < /p>
2024-05-08 10:53:31 ERROR    discord.ext.commands.bot Ignoring exception in command ban
Traceback (most recent call last):
File "/home/runner/DEATH-TO-THE-MPLA/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/DEATH-TO-THE-MPLA/main.py", line 35, in ban
await ctx.invoke(bot.get_command('ban'), ctx, member, reason=reason)  # Invoke the ban command defined in the Ban cog
File "/home/runner/DEATH-TO-THE-MPLA/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/context.py", line 336, in invoke
return await command(self, *args, **kwargs)
File "/home/runner/DEATH-TO-THE-MPLA/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 590, in __call__
return await self.callback(context, *args, **kwargs)  # type: ignore
TypeError: ban() takes 2 positional arguments but 3 positional arguments (and 1 keyword-only argument) were given

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/runner/DEATH-TO-THE-MPLA/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/DEATH-TO-THE-MPLA/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs)  # type: ignore
File "/home/runner/DEATH-TO-THE-MPLA/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: ban() takes 2 positional arguments but 3 positional arguments (and 1 keyword-only argument) were given
< /code>
Если кто -то мог бы помочь мне, я буду оценить его < /p>
Я попытался использовать другой пост здесь: Как я могу импортировать винтов в мой файл main.py? Чтобы решить этот вопрос, но когда я использовал его, все, что это делало, было вызвано ошибкой: < /p>
/home/runner/DEATH-TO-THE-MPLA/main.py:38: RuntimeWarning:  coroutine 'BotBase.load_extension' was never awaited
bot.load_extension(f"cogs.ban")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-05-08 11:00:53 INFO     discord.client logging in using static token
2024-05-08 11:00:54 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: 46f7aa5cd5816a4b67bec47342e1e375).
--------------------------------------------
Bot is ready
--------------------------------------------
Сам бот работал, но команда не сработала.

Подробнее здесь: https://stackoverflow.com/questions/784 ... iscord-bot
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»