如何使用discord.py在斜杠命令中发送文件?
如何在discord.py的斜杠命令中发送本地音频文件?
我已经基于discord.py写了一个带掷骰子斜杠命令的Discord机器人,代码如下:
import discord from discord import app_commands from discord.ext import commands import random TOKEN = "" # 我的机器人令牌 bot = commands.Bot(command_prefix = "/", intents = discord.Intents.all()) @bot.event async def on_ready(): print("Bot is Up and Ready!") try: synced = await bot.tree.sync() print(f"Synced {len(synced)} command(s)!") except Exception as e: print(e) @bot.tree.command(name = "roll", description = "roll a dice!") async def roll(interaction: discord.Interaction): await interaction.response.send_message(f"`{random.randint(1, 6)}`")
现在我想在名为song的斜杠命令中发送根目录下的song.mp3文件,实现类似手动拖拽文件到Discord聊天框的效果,预期代码结构如下:
@bot.tree.command(name = "song", description = "send the song") async def song(interaction: discord.Interaction): await interaction.response.send_message(f"{the_song_file}")
请问该如何实现这一功能?
解决方案
要实现发送本地音频文件的效果,你需要使用discord.File类包装本地文件,再通过send_message方法的file参数传递这个文件对象,无需用字符串格式化的方式。
修改后的完整代码如下:
import discord from discord import app_commands from discord.ext import commands import random TOKEN = "" # 我的机器人令牌 bot = commands.Bot(command_prefix = "/", intents = discord.Intents.all()) @bot.event async def on_ready(): print("Bot is Up and Ready!") try: synced = await bot.tree.sync() print(f"Synced {len(synced)} command(s)!") except Exception as e: print(e) @bot.tree.command(name = "roll", description = "roll a dice!") async def roll(interaction: discord.Interaction): await interaction.response.send_message(f"`{random.randint(1, 6)}`") @bot.tree.command(name = "song", description = "send the song") async def song(interaction: discord.Interaction): # 创建discord.File对象,传入本地文件路径 song_file = discord.File("song.mp3") # 发送消息时附带文件 await interaction.response.send_message(file=song_file)
关键说明:
discord.File("song.mp3")会读取根目录下的song.mp3文件,生成Discord可识别的文件对象。- 在
send_message中通过file参数传递该对象,即可实现和手动拖拽上传相同的效果。 - 如果需要同时发送文字内容,可添加
content参数,示例:await interaction.response.send_message(content="这是你要的音频!", file=song_file)
内容的提问来源于stack exchange,提问作者Coding_Guy
相关产品推荐
相关产品推荐

