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

Python编写的Kahoot机器人脚本生成数量异常,求排查错误

问题根源

你代码的循环逻辑存在类型错误:

  • 调用input()获取的机器人数量bots是字符串类型,直接对字符串做for x in bots遍历操作时,实际是逐个遍历字符串的每一位字符。比如你输入10,字符串"10"会被拆成'1'、'0'两个字符循环,所以只会生成2个机器人。
  • 额外存在隐性问题:你执行int(code)时没有把转换后的结果赋值给变量,相当于转换操作直接被丢弃,后续如果有使用数字类型游戏码的场景会触发异常。

修复方案

  1. 先将输入的机器人数量转换为整数类型,再用range()生成对应次数的循环序列
  2. 如果希望机器人ID后缀从1开始计数,可调整range()的起始参数
  3. 补充游戏码转换的变量赋值,把类型转换放在格式判断逻辑之后避免提前抛异常

修复后可运行代码

from colorama import Fore
from kahoot import client
import pyfiglet
import sys


def joinHandle():
    pass


print(Fore.BLUE + pyfiglet.figlet_format("Kahoot Bot"))
print(Fore.BLUE + "Coded by AsyncCode <3")
username = input(Fore.BLUE + "Tell me the Bots name. > ")
code = input(Fore.BLUE + "Tell me the Kahoot's Game Code. > ")
# 先判断格式再转换,同时保留转换后的数字类型
if code.isdigit() is False:
  print(Fore.BLUE + "Error, the Code must be an Integer.")
  sys.exit(1)
code = int(code)
logging = input(Fore.BLUE + "Tell me if you want to enable logging. y / n > ")

# 转换机器人数量为整数,再生成循环序列
bots_count = int(input(Fore.BLUE + "How many bots do you want? "))
# range(1, bots_count+1) 保证ID从1到输入的数量
for x in range(1, bots_count + 1):
    bot = client()
    bot_id = str(x)
    bot.join(str(code), username + " - " + bot_id)
    bot.on("joined", joinHandle)
    if logging == "y":
      print(Fore.BLUE + f"Log: Joining the Game ({code}) with Name: {username} - {bot_id}.")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:15:02