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

使用interactions.py开发Discord机器人时,如何调用外部文件函数?

使用interactions.py 4.4.0实现“join VC”斜杠命令

实现步骤与代码示例

1. 正确导入依赖与外部函数

在main.py中导入interactions.py核心组件,以及Commands/music.py里的join_voice_channel函数:

from interactions import Client, slash_command, SlashContext
from Commands.music import join_voice_channel

2. 创建斜杠命令并绑定外部函数

Discord斜杠命令名称不支持空格,因此用join_vc作为命令标识,通过描述说明功能。在命令函数中直接调用外部的join_voice_channel函数:

# 初始化机器人客户端
bot = Client(token="你的机器人令牌")

# 定义斜杠命令
@slash_command(name="join_vc", description="让机器人加入你当前所在的语音频道")
async def join_vc_command(ctx: SlashContext):
    # 调用外部函数,传递上下文参数
    await join_voice_channel(ctx)

# 启动机器人
bot.start()

3. 适配外部函数的逻辑

确保Commands/music.py中的join_voice_channel是异步函数,且能接收SlashContext参数处理语音频道逻辑:

from interactions import SlashContext

async def join_voice_channel(ctx: SlashContext):
    # 校验用户是否在语音频道内
    if not ctx.author.voice:
        await ctx.send("你需要先加入一个语音频道才能让机器人进来!")
        return
    
    # 获取用户所在频道并让机器人加入
    target_channel = ctx.author.voice.channel
    await target_channel.connect()
    await ctx.send(f"已成功加入语音频道:{target_channel.name}")

注意事项

  • 若要让命令显示为“join VC”,可通过name_localizations参数设置自定义显示名称(比如针对英文用户显示“join VC”)
  • 确保机器人拥有连接语音频道和查看频道的权限,否则执行会失败
  • 所有涉及Discord API的操作必须使用异步函数,因此join_voice_channel必须定义为async函数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:42:41