You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Discord机器人密码破解报错:TypeError: object of type 'Message' has no len()

解决Discord机器人密码破解器中的TypeError: object of type 'Message' has no len()错误

错误原因

你的代码中,password = await bot.wait_for("message")获取到的是Discord的Message对象,而非用户输入的密码字符串。直接对Message对象调用len()会触发TypeError,因为该对象没有实现长度计算的方法。

修正方案

需要做以下几个关键改动:

  • 从Message对象中提取用户输入的文本内容:使用message.content属性
  • 添加过滤条件,确保只接收发起命令的用户的消息,避免无关消息干扰程序
  • 修正循环内的对比逻辑:random.choices返回的是字符列表,需转为字符串后再和密码对比

修正后的完整代码

import random

@bot.command(name="password_cracker")
async def passCrack(ctx):
    chars = "azertyuiopmlkjhgfdsqwxcvbn1234567890AZERTYUIOPMLKJHGFDSQWXCVBN"
    chars_list = list(chars)

    await ctx.channel.send("Mot de Passe : ")
    # 等待发起命令的用户输入消息,并提取内容
    def check(msg):
        return msg.author == ctx.author and msg.channel == ctx.channel
    password_msg = await bot.wait_for("message", check=check)
    password = password_msg.content  # 获取用户输入的密码字符串
    guess_password = ""
    number = 0

    while guess_password != password:
        # 根据密码长度生成随机字符列表,再转为字符串
        guess_password = ''.join(random.choices(chars_list, k=len(password)))
        number += 1

        if guess_password == password:
            await ctx.channel.send(f"Your Password Is: {guess_password}")
            await ctx.channel.send(f"We have tested {number} possibilities")
            break

关键改动说明

  1. 将命令函数的参数从message改为ctx(Discord.py中更规范的上下文对象)
  2. 添加check函数过滤消息,确保只有发起命令的用户输入才会被接收
  3. 通过password_msg.content获取用户输入的纯文本密码
  4. 把random.choices返回的列表直接转为字符串,简化后续对比逻辑
  5. 使用f-string优化消息格式,提升可读性

内容的提问来源于stack exchange,提问作者Rapha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 08:35:34