我该如何解决这个问题 [discord.py]

时间:2021-03-23 15:54:02

标签: discord.py

你今天过得怎么样我当然希望你做得很好我很抱歉其他帐户的垃圾邮件我道歉。好的,所以我的问题是我从客户端切换到 bot 基本上是 bot = commands.Bot 我尝试将所有命令重命名为 bot.event 或 bot.command 有人请帮助我请我会很感激谢谢这里是代码:)

@bot.command()
async def ping(ctx):
    await ctx.send(f'Pong!\n`{round(client.latency*1000)}ms`')

@bot.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
    responses = [   "It is certain.",
                    "As I see it, yes",
                    "Ask again later.",
                    "Better not tell you now.",
                    "Cannot predict now.",
                    "Concentrate and ask again.",
                    "Don't count it",
                    "It is certain.",
                    "It is decidedly so.", 
                    "Most likely.",
                    "My reply is no."
                    "My sources say no.",
                    "Outlook not so good.",
                    "Outlook good.",
                    "Reply hazy, try again.",
                    "Signs point to yes.",
                    "Very doubtful.",
                    "Without a doubt.",
                    "Yes.",
                    "Yes – definitely.",
                    "You may rely on it." ]
    await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')


@commands.has_permissions(ban_members=True)
@bot.command()
async def kick(ctx, user: discord.Member, *, reason="No reason provided"):
        await user.ban(reason=reason)
        kick = discord.Embed(title=f":boom: Kicked {user.name}!", description=f"Reason: {reason}\nBy: {ctx.author.mention}")
        await ctx.message.delete()
        await ctx.channel.send(embed=kick)
        await user.send(embed=kick)

@commands.has_permissions(ban_members=True)
@bot.command()
async def ban(ctx, user: discord.Member, *, reason="No reason provided"):
        await user.ban(reason=reason)
        ban = discord.Embed(title=f":boom: Banned {user.name}!", description=f"Reason: {reason}\nBy: {ctx.author.mention}")
        await ctx.message.delete()
        await ctx.channel.send(embed=ban)
        await user.send(embed=ban)

@bot.command()
async def unban(ctx, *, member):
    banned_users = await ctx.guild.bans()
    
    member_name, member_discriminator = member.split('#')
    for ban_entry in banned_users:
        user = ban_entry.user
        
        if (user.name, user.discriminator) == (member_name, member_discriminator):
            await ctx.guild.unban(user)
            await ctx.channel.send(f"Unbanned: {user.mention}")

@bot.command(pass_context = True)
async def mute(ctx, user_id, userName: discord.User):
    if ctx.message.author.server_permissions.administrator:
        user = ctx.message.author
        role = discord.utils.get(user.server.roles, name="Muted")

@bot.command()
async def serverinfo(ctx):
  name = str(ctx.guild.name)
  description = str(ctx.guild.description)

  owner = str(ctx.guild.owner)
  id = str(ctx.guild.id)
  region = str(ctx.guild.region)
  memberCount = str(ctx.guild.member_count)

  icon = str(ctx.guild.icon_url)
   
  embed = discord.Embed(
      title=name + " Server Information",
      description=description,
      color=discord.Color.blue()
    )
  embed.set_thumbnail(url=icon)
  embed.add_field(name="Owner", value=owner, inline=True)
  embed.add_field(name="Server ID", value=id, inline=True)
  embed.add_field(name="Region", value=region, inline=True)
  embed.add_field(name="Member Count", value=memberCount, inline=True)

  await ctx.send(embed=embed)
  await client.add_roles(user, role)

@bot.command()
async def setdelay(ctx, seconds: int):
    await ctx.channel.edit(slowmode_delay=seconds)
    await ctx.send(f"Set the slowmode delay in this channel to {seconds} seconds!")

@bot.command()
async def afk(ctx, mins):
    current_nick = ctx.author.nick
    await ctx.send(f"{ctx.author.mention} has gone afk for {mins} minutes.")
    await ctx.author.edit(nick=f"{ctx.author.name} [AFK]")

    counter = 0
    while counter <= int(mins):
        counter += 1
        await asyncio.sleep(60)

        if counter == int(mins):
            await ctx.author.edit(nick=current_nick)
            await ctx.send(f"{ctx.author.mention} is no longer AFK")
            break

def setup(bot):
    bot.add_cog(Afk(bot))

def user_is_me(ctx):
    return ctx.message.author.id == "Your ID" 



def convert(time):
  pos = ["s","m","h","d"]

  time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d": 3600*24}

  unit = time[-1]

  if unit not in pos:
    return -1
  try:
    val = int(time[:-1])
  except:
    return -2

  return val * time_dict[unit]

@bot.command()
@commands.has_permissions(kick_members=True)
async def giveaway(ctx):
  await ctx.send("Let's start with this giveaway! Answer these questions within 15 seconds!")

  questions = ["Which channel should it be hosted in?", "What should be the duration of the giveaway? (s|m|h|d)", "What is the prize of the giveaway?"]

  answers = []

  def check(m):
    return m.author == ctx.author and m.channel == ctx.channel

  for i in questions:
    await ctx.send(i)

    try:
      msg = await bot.wait_for('messsage', timeout=15.0, check=check)
    except asyncio.TimeoutError:
      await ctx.send('You didn\'t answer in time, please be quicker next time!')
      return
    else: 
      answers.append(msg.content)

  try:
    c_id = int(answers[0][2:-1])
  except:
    await ctx.send(f"You didn't mention a channel properly. Do it like this {ctx.channel.mention} next time.")
    return

  channel = bot.get_channel(c_id)

  time = convert(answers[1])
  if time == -1:
    await ctx.send(f"You didn't answer with a proper unit. Use (s|m|h|d) next time!")
    return
  elif time == -2:
    await ctx.send(f"The time just be an integer. Please enter an integer next time.")
    return
  
  prize = answers[2]

  await ctx.send(f"The giveaway will be in {channel.mention} and will last {answers[1]} seconds!")

  embed = discord.embed(title = "Giveaway!", description = f"{prize}", color = ctx.author.color)

  embed.add_field(name = "Hosted by:", value = ctx.author.mention)

  embed.set_footer(text = f"Ends {answers[1]} from now!")

  my_msg = await channel.send(embed = embed)

  await my_msg.add_reaction("?")

  await asyncio.sleep(time)

  new_msg = await channel.fetch_message(my_msg.id)

  users = await new_msg.reactions[0].users().flatten()
  users.pop(users.index(bot.user))

  winner = random.choice(users)

  await channel.send(f"Congratulations! {winner.mention} won the prize: {prize}!")


@bot.command()
@commands.has_permissions(kick_members=True)
async def reroll(ctx, channel : discord.TextChannel, id_ : int):
  try:
    new_msg = await channel.fetch_message(id_)
  except:
    await ctx.send("The ID that was entered was incorrect, make sure you have entered the correct giveaway message ID.")
  users = await new_msg.reactions[0].users().flatten()
  users.pop(users.index(bot.user))

  winner = random.choice(users)

  await channel.send(f"Congratulations the new winner is: {winner.mention} for the giveaway rerolled!")

如果您想让我回答任何问题以帮助您解决问题,请随时发表评论,非常感谢,祝您有美好的一天!

2 个答案:

答案 0 :(得分:2)

您似乎从互联网上复制了大部分代码并将其拼凑在一起以创建机器人或齿轮(根据您的问题,我猜是机器人)。

假设这是您的主要 bot 文件的片段而不是齿轮,那么有几件事可能会有所不同:

  1. 将您的实用函数放在一个地方(最好在您的导入语句之后)。总体而言,这是一种很好的做法,可以使代码更具可读性。
  2. 除非您在与机器人实例相同的文件中有一个 cog 类(这是不好的做法),否则您不需要这个:
def setup(bot):
        bot.add_cog(Afk(bot))

如果有一个名为 Afk 的 cog 类,您应该将其移动到一个单独的文件中(将 cog 类放入主 bot 文件会破坏 cog 的目的)

  1. 在您的静音命令中,您有 pass_context = True。这是旧版本的 discord.py,不再需要。

我不能告诉你更多,因为尝试调试你的代码没有意义,因为你没有给我们任何错误或堆栈跟踪。

答案 1 :(得分:0)

这很累人,所以你可以在每个命令中留下 client,只需写这个 client = commands.Bot(command_prefix = 'your prefix') 它是同一个机器人,只是名称不同。 如果你是那个意思,因为我真的不明白你需要什么