Discord.py音乐Bot音量存储报错:ValueError无效整数字面量
Hey there, let's figure out why you're hitting that ValueError and fix your volume persistence logic step by step.
Why the Error Happens
The ValueError: invalid literal for int() with base 10: '' occurs because your code ends up reading an empty string from the file. Let's break down the problematic parts:
with open(r'E:\PythonProjects\WeebBot\textfiles\volumefile.txt', 'r+') as volumefile: open(r'E:\PythonProjects\WeebBot\textfiles\volumefile.txt', 'w')
- Opening the file with
'w'mode immediately clears all its content, wiping out any existing volume value. - Even if you didn't clear the file, after writing a new value, the file pointer sits at the end of the file—so a direct
read()call would return an empty string unless you move the pointer back to the start. - Also, you don't need to manually call
volumefile.close(): thewithstatement handles file closing automatically.
Fixed Volume Command Code
Here's a cleaned-up, working version of your command with input validation and proper file handling:
@commands.command(pass_context=True, no_pm=True) async def volume(self, ctx, value: int): """Sets the volume of the currently playing song (1-200%).""" # Validate input to avoid invalid volume values if not 1 <= value <= 200: await self.bot.say("Oops! Volume needs to be between 1 and 200.") return state = self.get_voice_state(ctx.message.server) volume_file_path = r'E:\PythonProjects\WeebBot\textfiles\volumefile.txt' # Save the new volume to the file (overwrites old value) with open(volume_file_path, 'w') as f: f.write(str(value)) # Apply the volume to the current player if it's active if state.is_playing(): player = state.player player.volume = value / 100 # Convert to 0.01-2.0 range await self.bot.say(f'Set volume to {value}%')
Persist Volume Across New Songs
To make sure the saved volume applies every time a new track starts, add this logic to your play command/function:
# When initializing a new player for a song: volume_file_path = r'E:\PythonProjects\WeebBot\textfiles\volumefile.txt' try: with open(volume_file_path, 'r') as f: # Strip whitespace/newlines to avoid parsing issues saved_volume = int(f.read().strip()) player.volume = saved_volume / 100 except (FileNotFoundError, ValueError): # Fallback to 50% if file is missing or has invalid content player.volume = 0.5 # Optional: Create the file with default value for future use with open(volume_file_path, 'w') as f: f.write('50')
Key Improvements
- Removed the redundant
open()call that was clearing the file - Added input validation to prevent invalid volume values outside the 1-200% range
- Simplified file saving with
'w'mode, which overwrites the old value cleanly - Added error handling for playback logic to gracefully handle missing or empty files
- Eliminated unnecessary post-write file read—we can use the input
valuedirectly
Quick Note for Newer Discord.py Versions
If you're using Discord.py v1.0+, ctx.message.server is deprecated. Replace it with ctx.guild to align with the latest API.
内容的提问来源于stack exchange,提问作者Bernas
相关产品推荐
相关产品推荐

