Python编写的Kahoot机器人脚本生成数量异常,求排查错误
问题根源
你代码的循环逻辑存在类型错误:
- 调用
input()获取的机器人数量bots是字符串类型,直接对字符串做for x in bots遍历操作时,实际是逐个遍历字符串的每一位字符。比如你输入10,字符串"10"会被拆成'1'、'0'两个字符循环,所以只会生成2个机器人。 - 额外存在隐性问题:你执行
int(code)时没有把转换后的结果赋值给变量,相当于转换操作直接被丢弃,后续如果有使用数字类型游戏码的场景会触发异常。
修复方案
- 先将输入的机器人数量转换为整数类型,再用
range()生成对应次数的循环序列 - 如果希望机器人ID后缀从1开始计数,可调整
range()的起始参数 - 补充游戏码转换的变量赋值,把类型转换放在格式判断逻辑之后避免提前抛异常
修复后可运行代码
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
相关产品推荐
相关产品推荐

