英文:
My discord bot's pi command isn't working
问题
I made a discord bot with a lot of commands. The whole thing was in main.py, which made it very difficult to find one of the entire list of commands when I wanted to make some changes. So, I decided to make each command into a new file, and then import the file back into main.py. (So for example, before the code was @bot.command() async def pi(ctx, digits):
, but now the @bot.command() async def pi(ctx, digits):
has been put into a file called pi.py
) I just use the pi command as an example.
Here is my code in main.py:
import discord
from discord.ext import commands
import asyncio
from cogs.pi import Pi
token = "hidden for safety lol"
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="?", intents=intents)
bot.add_cog(Pi(bot))
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Game(name="?help"))
await asyncio.sleep(1)
print("\n Bot has successfully logged in as: {}".format(bot.user))
print("Bot ID: {}\n".format(bot.user.id))
try:
bot.run(token)
except discord.HTTPException as e:
if e.status == 429:
print("The Discord servers denied the connection for making too many requests")
else:
raise e
and here is my code in pi.py:
import discord
from discord.ext import commands
import decimal
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="?", intents=intents)
class Pi(commands.Cog):
def __init__(self, bot):
self.bot = bot
@bot.command()
async def pi(ctx, num_decimals: int):
if num_decimals > 10000:
await ctx.send("Sorry, I can only print up to 10000 decimal places.")
return
decimal.getcontext().prec = num_decimals + 1
pi_value = decimal.Decimal(0)
for i in range(num_decimals + 1):
pi_value += (decimal.Decimal(1) / 16 ** i) * ((decimal.Decimal(4) / (8 * i + 1)) - (decimal.Decimal(2) / (8 * i + 4)) - (decimal.Decimal(1) / (8 * i + 5)) - (decimal.Decimal(1) / (8 * i + 6)))
pi_str = str(pi_value)[:num_decimals + 1]
await ctx.send(f"The value of pi to {num_decimals} decimal places is: {pi_str}")
def setup(bot):
bot.add_cog(Pi(bot))
Just a reminder since I forgot to say at the beginning, the pi.py is inside a folder called "cogs". I've shown a photo of how it looks.
The problem I have is importing the file. When I run the code, it gives me this error: Traceback (most recent call last): File "main.py", line 9, in <module> from cogs.pi import Pi ModuleNotFoundError: No module named 'cogs.pi'
Please help. I would be very thankful for the answer.
英文:
I made a discord bot with a lot of commands. The whole thing was in main.py, which made it very difficult to find one of the entire list of commands when I wanted to make some changes. So, I decided to make each command into a new file, and then import the file back into main.py. (So for example, before the code was @bot.command() async def pi(ctx, digits):
, but now the @bot.command() async def pi(ctx, digits):
has been put into a file called pi.py
) I just use the pi command as an example.
Here is my code in main.py:
import discord
from discord.ext import commands
import asyncio
from pi.py import Pi
token = "hidden for saftey lol"
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="?", intents=intents)
bot.add_cog(Pi(bot))
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Game(name=f"?help"))
await asyncio.sleep(1)
print("\n Bot has successfully logged in as: {}".format(bot.user))
print("Bot ID: {}\n".format(bot.user.id))
try:
bot.run(token)
except discord.HTTPException as e:
if e.status == 429:
print("The Discord servers denied the connection for making too many requests")
else:
raise e
and here is my code in pi.py:
import discord
from discord.ext import commands
import decimal
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="?", intents=intents)
class Pi(commands.Cog):
def __init__(self, bot):
self.bot = bot
@bot.command()
async def pi(ctx, num_decimals: int):
if num_decimals > 10000:
await ctx.send("Sorry, I can only print up to 10000 decimal places.")
return
decimal.getcontext().prec = num_decimals + 1
pi_value = decimal.Decimal(0)
for i in range(num_decimals + 1):
pi_value += (decimal.Decimal(1) / 16 ** i) * ((decimal.Decimal(4) / (8 * i + 1)) - (decimal.Decimal(2) / (8 * i + 4)) - (decimal.Decimal(1) / (8 * i + 5)) - (decimal.Decimal(1) / (8 * i + 6)))
pi_str = str(pi_value)[:num_decimals + 1]
await ctx.send(f"The value of pi to {num_decimals} decimal places is: {pi_str}")
def setup(bot):
bot.add_cog(Pi(bot))
Just a reminder since I forgot to say at the beginning, the pi.py is inside a folder called "cogs". I've shown a photo of how it looks.
The problem I have is importing the file. When I run the code, it gives me this error: Traceback (most recent call last):
File "main.py", line 9, in <module>
from pi.py import Pi
ModuleNotFoundError: No module named 'pi'
Please help. I would be very thankful for the answer.
答案1
得分: 0
My way:
这样,齿轮将被自动加载到您的主函数中,并且应该可以立即运行,而无需再次更改主文件。
Main #2:
(您的代码已重写)
不要从pi.py导入,应该从实际的文件名(不带扩展名)导入。应该是 from pi import Pi
你这里有几个问题。
1)你不应该在一个cog内使用 bot.command()
。对于前缀命令,你应该使用 @commands.command()
2)在你的cog最后参考到主文件时有几个错误。你的def需要是async
,而且bot.add_cog()
函数需要在开头有await
,并且参数应该是(bot:commands.Bot)
3)在Pi cog内的pi命令中,ctx参数缺少self参数。因为这是一个类,所以需要引用它。
如果您有任何其他问题,请随时提出。
英文:
Your main is a little messy so I'll show you 2 ways you can make your main. Doing it my way and your way.
My way:
This way, the cogs will be auto-loaded into your main function and should work right off the bat without ever needing to change the main file again.
import discord
from discord.ext import commands
import os
import traceback
def get_cogs():
cogs_dir = "./cogs" # Directory path
# Get all file names in directory and filter out non-Python files
file_names = [f[:-3] for f in os.listdir(cogs_dir) if f.endswith(".py")]
# Add "cogs." to the beginning of file_name
cogs = ["cogs." + filename for filename in file_names]
print(f"\n\nTHE FILES IN THE COG FOLDER ARE: {cogs}\n\n")
return cogs
class Bot(commands.Bot):
def __init__(self):
super().__init__(command_prefix=commands.when_mentioned_or('.'), intents=discord.Intents().all())
self.cogsList = get_cogs()
async def setup_hook(self):
for ext in self.cogsList:
await self.load_extension(ext)
async def on_ready(self):
await self.change_presence(activity=discord.Game('the game your bot is playing'))
# Replace the channel ID with the actual ID you want to send the message to
channel = self.get_channel(1072747266747670541)
await channel.send('7.5 million years have passed...\nThe answer is ready:\nThe Ultimate Answer to Life, The Universe, and Everything is...42!')
print('We have logged in as {0.user}'.format(self))
try:
synced = await self.tree.sync()
print(f'Synced {len(synced)} command(s)')
except Exception as e:
tb = e.__traceback__
lineno = tb.tb_lineno
traceback.print_exc()
print(f"An Error Occurred in loading the commands on line {lineno}:\n{e}")
bot = Bot()
bot.run('TOKEN')
Main #2:
(your code rewritten)
Instead of importing from pi.py, you should import from the actual file name without the extension. it should be from pi import Pi
import discord
from discord.ext import commands
import asyncio
from pi import Pi
token = "hidden for safety lol"
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="?", intents=intents)
bot.add_cog(Pi(bot))
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Game(name="?help"))
await asyncio.sleep(1)
print("\nBot has successfully logged in as: {}".format(bot.user))
print("Bot ID: {}\n".format(bot.user.id))
try:
bot.run(token)
except discord.HTTPException as e:
if e.status == 429:
print("The Discord servers denied the connection for making too many requests")
else:
raise e
You had a couple of things wrong here.
-
you shouldn't use
bot.command()
inside of a cog. For prefix commands you should be using@commands.command()
-
you had a couple of mistakes in the reference back to the main at the very end of your cog. your def needs to be
async
and yourbot.add_cog()
function needs to have anawait
at the beginning as well as having the parameters(bot:commands.Bot)
-
In the pi command within the Pi cog, the ctx parameter is missing the self argument. because this is a class you need to have it referenced.
import discord
from discord.ext import commands
import decimal
class Pi(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def pi(self, ctx, num_decimals: int):
if num_decimals > 10000:
await ctx.send("Sorry, I can only print up to 10000 decimal places.")
return
decimal.getcontext().prec = num_decimals + 1
pi_value = decimal.Decimal(0)
for i in range(num_decimals + 1):
pi_value += (decimal.Decimal(1) / 16 ** i) * ((decimal.Decimal(4) / (8 * i + 1)) - (decimal.Decimal(2) / (8 * i + 4)) - (decimal.Decimal(1) / (8 * i + 5)) - (decimal.Decimal(1) / (8 * i + 6)))
pi_str = str(pi_value)[:num_decimals + 1]
await ctx.send(f"The value of pi to {num_decimals} decimal places is: {pi_str}")
async def setup(bot:commands.Bot) -> None:
await bot.add_cog(Pi(bot))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论