Я пытаюсь создать бот -разборовой, который позволит мне запустить команду из другого файла, используя 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
--------------------------------------------
Я пытаюсь создать бот -разборовой, который позволит мне запустить команду из другого файла, используя CoG, но, кажется, возникают проблемы, когда я пытаюсь добавить свой винтов в свой файл main.py.[code]import discord import os import asyncio from discord.ext import commands
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("--------------------------------------------")
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 -------------------------------------------- [/code] Сам бот работал, но команда не сработала.
@bot.command() асинхронная защита лол (ctx): для гильдии в bot.guilds: # все сервера бота role = discord.utils.find(lambda r: r.name == 'новая роль', guild.roles) для участника в guild.members: если роль вmember.roles: ожидайтеmember.send(слово)...
Я сейчас только изучаю discord.py и закончил тестового бота в discord.py. Теперь я хочу переписать его как селфбота, так как моей целью было начать с написания селфбота, но я решил сначала изучить discord.py.
Как мне взять существующий код...
Я создаю бота Discord, который отправляет запросы на переименование канала каждый раз, когда кто-то присоединяется или покидает сервер Minecraft. Как следует из названия, я был далек от того, чтобы нарушить фактический предел скорости. В какой-то...
Когда отдельный бот запускается через функцию пользователем моего бота, т.е. он создает своего бота через моего бота, то при обработке обработчиков событий если я указываю state='*' все работает, но если я указываю определенное состояние в качестве...
В настоящее время использую Discord 2.4.0 и Python 3.12.1
На моем портале разработки -> Rich Presence -> Rich Presence Assets я загрузил изображение jpg размером 1024x1024 и назвал его «asset_id». . Я обязательно сохранил изменения, и после...