Discord Bot的!roblox命令中username变量无值问题求助
问题描述
我开发了一个Discord Bot,该Bot通过!roblox <username>命令触发,计划调用Roblox API查询目标用户的群组等级、好友数量、账号年龄。但目前username变量始终没有存储值,我添加了print语句排查也没有输出。以下是我的代码:
import discord import requests intents = discord.Intents.default() intents.members = True client = discord.Client(intents=intents) @client.event async def on_ready(): print('Logged in as {0.user}'.format(client)) @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('!roblox'): # Get the username from the user input username = message.content.split('!roblox ')[1] print(username) # Make a request to the Roblox API to get the user's data url = f"https://users.roblox.com/v1/users/search?keyword={username}&limit=10" response = requests.get(url) data = response.json() # Check if the user exists if "data" in data and data["data"]: user_id = data["data"][0]["id"] # Get the user's account age url = f"https://users.roblox.com/v1/users/{user_id}" response = requests.get(url) data = response.json() created_at = data["created"] # Get the user's friend count url = f"https://friends.roblox.com/v1/users/{user_id}/friends/count" response = requests.get(url) data = response.json() friend_count = data["count"] # Get the user's role name in the group "United States Army" url = f"https://groups.roblox.com/v2/users/{user_id}/groups/roles" response = requests.get(url) data = response.json() role_name = None for group in data["data"]: if group["group"]["id"] == 3108077: role_name = group["role"]["name"] break # Build the response message message = f"**Username:** {username}\n" message += f"**Account Age:** {created_at}\n" message += f"**Friend Count:** {friend_count}\n" message += f"**Role in United States Army:** {role_name}" if role_name else "" else: message = f"Could not find user {username}." # Send the response message await message.channel.send(message) client.run('TOKEN')
请问为何username变量没有值,请求帮助!
问题原因与解决方案
核心问题
你提取用户名的方式存在两个关键问题,导致username无法正常赋值甚至代码直接终止:
- 索引越界异常:用
message.content.split('!roblox ')[1]时,如果用户输入的命令格式错误(比如只打了!roblox没加用户名,或者空格位置不对),split后的列表长度会小于2,直接取索引1会触发IndexError,代码会中断,print(username)根本没机会执行。 - 命令匹配不严谨:
startswith('!roblox')会匹配所有以!roblox开头的消息,比如!robloxian这种错误指令,此时split('!roblox ')只能得到一个元素,同样会触发索引错误。
另外代码还有隐藏问题:你用字符串覆盖了原有的message对象,后续执行await message.channel.send(message)会报错,因为此时message已经不是Discord的Message实例了。
修复步骤
- 安全提取用户名:改用按空格拆分的方式,先判断参数数量:
parts = message.content.split() # 确保命令格式正确 if len(parts) < 2: await message.channel.send("请输入正确格式:!roblox <用户名>") return username = parts[1] print(username)
- 严谨匹配命令:直接判断拆分后的第一个元素是否为
!roblox,避免误匹配:
if parts[0] == '!roblox': # 后续逻辑
- 避免覆盖Message对象:把回复消息的变量名改成
response_msg:
# 构建回复消息 response_msg = f"**Username:** {username}\n" response_msg += f"**Account Age:** {created_at}\n" response_msg += f"**Friend Count:** {friend_count}\n" if role_name: response_msg += f"**Role in United States Army:** {role_name}" # 发送回复 await message.channel.send(response_msg)
- 添加异常防护:对API请求步骤添加异常捕获,避免Bot崩溃:
try: response = requests.get(url) response.raise_for_status() # 捕获HTTP错误 data = response.json() except requests.exceptions.RequestException as e: await message.channel.send(f"API请求失败:{str(e)}") return
内容的提问来源于stack exchange,提问作者FrostZer0
相关产品推荐
相关产品推荐

