我的Discord机器人的pi命令不起作用。

huangapple go评论62阅读模式
英文:

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 = &quot;hidden for saftey lol&quot;

intents = discord.Intents.all()
bot = commands.Bot(command_prefix=&quot;?&quot;, intents=intents)
bot.add_cog(Pi(bot))

@bot.event
async def on_ready():
  await bot.change_presence(activity=discord.Game(name=f&quot;?help&quot;))
  await asyncio.sleep(1)
  print(&quot;\n Bot has successfully logged in as: {}&quot;.format(bot.user))
  print(&quot;Bot ID: {}\n&quot;.format(bot.user.id))


try:
  bot.run(token)
except discord.HTTPException as e:
  if e.status == 429:
    print(&quot;The Discord servers denied the connection for making too many requests&quot;)
  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=&quot;?&quot;, 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 &gt; 10000:
      await ctx.send(&quot;Sorry, I can only print up to 10000 decimal places.&quot;)
      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&quot;The value of pi to {num_decimals} decimal places is: {pi_str}&quot;)

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 &quot;main.py&quot;, line 9, in &lt;module&gt;
from pi.py import Pi
ModuleNotFoundError: No module named &#39;pi&#39;

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 = &quot;./cogs&quot;  # 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(&quot;.py&quot;)]

    # Add &quot;cogs.&quot; to the beginning of file_name
    cogs = [&quot;cogs.&quot; + filename for filename in file_names]

    print(f&quot;\n\nTHE FILES IN THE COG FOLDER ARE: {cogs}\n\n&quot;)
    return cogs


class Bot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix=commands.when_mentioned_or(&#39;.&#39;), 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(&#39;the game your bot is playing&#39;))

        # Replace the channel ID with the actual ID you want to send the message to
        channel = self.get_channel(1072747266747670541)
        await channel.send(&#39;7.5 million years have passed...\nThe answer is ready:\nThe Ultimate Answer to Life, The Universe, and Everything is...42!&#39;)
        
        print(&#39;We have logged in as {0.user}&#39;.format(self))
        try:
            synced = await self.tree.sync()
            print(f&#39;Synced {len(synced)} command(s)&#39;)
        except Exception as e:
            tb = e.__traceback__
            lineno = tb.tb_lineno
            traceback.print_exc()
            print(f&quot;An Error Occurred in loading the commands on line {lineno}:\n{e}&quot;)


bot = Bot()


bot.run(&#39;TOKEN&#39;)  

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 = &quot;hidden for safety lol&quot;

intents = discord.Intents.all()
bot = commands.Bot(command_prefix=&quot;?&quot;, intents=intents)
bot.add_cog(Pi(bot))

@bot.event
async def on_ready():
    await bot.change_presence(activity=discord.Game(name=&quot;?help&quot;))
    await asyncio.sleep(1)
    print(&quot;\nBot has successfully logged in as: {}&quot;.format(bot.user))
    print(&quot;Bot ID: {}\n&quot;.format(bot.user.id))


try:
    bot.run(token)
except discord.HTTPException as e:
    if e.status == 429:
        print(&quot;The Discord servers denied the connection for making too many requests&quot;)
    else:
        raise e

You had a couple of things wrong here.

  1. you shouldn't use bot.command() inside of a cog. For prefix commands you should be using @commands.command()

  2. 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 your bot.add_cog() function needs to have an await at the beginning as well as having the parameters (bot:commands.Bot)

  3. 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 &gt; 10000:
            await ctx.send(&quot;Sorry, I can only print up to 10000 decimal places.&quot;)
            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&quot;The value of pi to {num_decimals} decimal places is: {pi_str}&quot;)

async def setup(bot:commands.Bot) -&gt; None:
    await bot.add_cog(Pi(bot))

huangapple
  • 本文由 发表于 2023年5月28日 14:18:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76350197.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定