You need to enable JavaScript to run this app. Discord.py say命令未指定发送频道时的channel变量赋值问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py say命令未指定发送频道时的channel变量赋值问题求助

问题原因

  • 原代码中channel:discord.TextChannel没有设置默认值,属于必填参数,用户未输入时Discord.py会直接抛出参数缺失错误,不会执行后续的if not channel判断逻辑
  • 原代码中channel=()的赋值逻辑错误,空元组没有send方法,就算执行到这里也会触发运行报错

修正方案

直接替换为以下代码即可实现需求:

import discord
from typing import Optional

@bot.command()
async def say(ctx, channel: Optional[discord.TextChannel] = None, *, message):
    # 未传入频道时默认使用命令触发的当前频道
    if not channel:
        channel = ctx.channel
    embed=discord.Embed(
        description=message,
        color=discord.Color.blue()
    )
    await channel.send(embed=embed)
    await ctx.message.delete()

如果使用Python 3.10及以上版本,可以省略typing导入,将参数行写为:
async def say(ctx, channel: discord.TextChannel | None = None, *, message):

效果验证

  • 输入!say 测试内容:未指定频道时自动在命令触发的当前频道发送嵌入消息
  • 输入!say #目标频道 测试内容:指定频道时向对应频道发送嵌入消息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 11:27:07