Discord.py bot不会响应命令。。。除了它是一个水平系统

2024-06-16 10:30:56 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:我可能应该补充一下,我在repl.it上完成了以下所有代码,尽管我怀疑这会有什么不同

编辑2:我不知道我做了什么,但现在什么都不管用了。控制台中不会显示“就绪”消息。这可能与我添加的“keep_alive”文件有关

于是我开始了我的一天,试图找出这段代码的问题所在,直到我意识到“嘿,我可以尝试询问堆栈溢出”

在上下文中,每当我运行bot并键入命令(即“!rank”),bot似乎都无法识别该命令。控制台中没有红色单词,除非我使用不存在的命令This is the console after I used three commands: '!rank', '!leaderboard', and '!yeet', which purposefully doesn't exist.

如果您懒得打开映像,控制台将显示:

Ignoring exception in command None:

discord.ext.commands.errors.CommandNotFound: Command "yeet" is not found

代码如下:

from keep_alive import keep_alive

from discord.ext import commands
import discord
import os
import levelsys

cogs = [levelsys]

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

token = os.environ.get("DISCORD_BOT_SECRET")
client.run(token)

keep_alive()
token = os.environ.get("DISCORD_BOT_SECRET")
client.run(token)

for i in range(len(cogs)):
  cogs[i].setup(client)
import discord
from discord.ext import commands
from pymongo import MongoClient

general = [806613968684318720]

level = ["Sperm Whale", "Artillery General", "Commander", "Supreme General",]
levelnum = [1,5,10,15]

cluster = MongoClient("mongodb+srv://[Username]:[Password]@kingdom-kun.lffd9.mongodb.net/Kingdom-kun?retryWrites=true&w=majority")

client = discord.Client

leveling = cluster["discord"]["levelling"]

class levelsys(commands.Cog):
  def _init_(self, client):
    self.client = client

  @commands.Cog.listener()
  async def on_ready(self):
    print("Kingdom-kun is ready to come!")

  @commands.Cog.listener()
  async def on_message(self, message):
    if message.channel == general:
      stats = leveling.find_one({"id" : message.author.id})
      if not message.author.bot:
        if stats is None:
          newuser = {"id": message.author.id, "xp": 100}
          leveling.insert_one(newuser)
        else:
          xp = stats["xp"] +5
          leveling.update_one({"id": message.author.id}, {"$set": {"xp"}})
          lvl = 0
          while True:
            if xp < {(50*(lvl**2))+(50*(lvl-1))}:
              break
            lvl +=1
          xp -= {(50*(lvl-1)**2)+(50*(lvl-1))}
          if xp == 0:
            await message.channel.send(f"Well done {message.author.mention}! You were promoted to **Level: {lvl}**")
            for i in range(len(level)):
              if lvl == levelnum[i]:
                await message.author.add_roles(discord.utils.get(message.author.guild.roles, name=level[i]))
                embed = discord.Embed(description=f"{message.author.mention} you have gotten role **{level[i]}**!!!")
                embed.set_thumbnail(url=message.author.avatar_url)
                await message.channel.send(embed=embed)

#This is rank command
  @commands.command()
  async def rank(self, ctx):
    if ctx.channel.id == general:
      stats = leveling.find_one({"id": ctx.author.id})
      if stats is None:
        embed = discord.Embed(description = "You haven't sent any messages, no rank!!!")
        await ctx.channelsned(embed=embed)
      else:
        xp = stats["xp"]
        lvl = 0
        rank = 0
        while True:
          if xp < {(50*(lvl**2))+(50*(lvl-1))}:
              break
          lvl += 1
        xp -= {(50*(lvl-1)**2)+(50*(lvl-1))}
        boxes = [(xp/(200*((1/2) * lvl)))*20]
        rankings = leveling.find().sort("xp",-1)
        for x in rankings:
          rank += 1
          if stats("id") == x["id"]:
            break
        embed = discord.Embed(title="{}'s level stats".format(ctx.author.name))
        embed.add_field(name="Name", value = ctx.author.mention, inline=True)

        embed.add_field(name="XP", value = f"{(xp/(200*((1/2)* lvl)))*20}", inline=True)

        embed.add_field(name="Rank", value = f"{rank}/{ctx.guild.member_count}", inline=True)

        embed.add_field(name="Progress Bar[lvl]", value = boxes * ":blue_square:" * (20-boxes) * ":white_large_square:", inline=False)
        embed.set_thumbnail(url=ctx.author.avatar_url)
        await ctx.channel.send(embed=embed)

#This is leaderboard command
  @commands.command()
  async def leaderboard(self, ctx):
    if (ctx.channel.id == general):
      rankings = leveling.find().sort("xp",-1)
      i=1
      embed = discord.Embed(title = "Rankings:")
      for x in rankings:
        try:
          temp = ctx.guild.get_member(x["id"])
          tempxp = x["xp"]
          embed.add_field(name=f"(i): {temp.name}", value=f"Total XP: {tempxp}", inline=False)
          i == 1
        except:
          pass
        if i == 11:
          break
      await ctx.channel.send(embed=embed)

def setup(client):
  client.add_cog(levelsys(client))

(这是我添加的keep_alive文件,不知怎么搞砸了一切)

from flask import Flask
from threading import Thread

app = Flask('')

@app.route('/')
def home():
    return "OwO mode pog?"

def run():
  app.run(host='0.0.0.0',port=8080)

def keep_alive():
    t = Thread(target=run)
    t.start()

我试过很多方法-将括号改成括号,然后再改回来,重新键入整个内容。。。再一次,甚至更多,但一切都没有改变。如果有人能回答这个难题,我将非常感激

无论如何,祝你有一个愉快的一天


Tags: importclientidmessageifdefstatsembed