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

discord.py:如何将命令结果发送至触发命令的频道?

解决discord.py中fban命令的发送问题

你的代码主要存在未定义message变量和Embed字符串未正确格式化的问题,同时可以通过ctx上下文对象直接实现消息发送到触发频道的需求,无需手动指定频道ID。以下是修正后的完整代码及说明:

修正后的代码

import asyncio
import discord

@bot.command(name="fban")
async def fban(ctx):
    # 仅接收触发命令的用户在同一频道发送的消息
    def check(msg):
        return msg.author == ctx.author and msg.channel == ctx.channel
    
    try:
        # 等待用户输入内容,设置60秒超时避免无限等待
        msg = await bot.wait_for("message", check=check, timeout=60.0)
        outmsg = msg.content.lower()
        lines = outmsg.splitlines()
        
        # 校验输入格式是否符合要求
        if len(lines) < 2:
            await ctx.reply("请输入两行内容:第一行是用户名,第二行是封禁原因。")
            return
        
        username = lines[0]
        reason = lines[1]

        # 使用f-string正确格式化Embed的标题和描述
        fake_ban_embed = discord.Embed(
            title=f"{username} was banned.",
            description=f"Reason : {reason}"
        )
        # 替换为Imgur的直接图片链接,确保缩略图能正常加载
        fake_ban_embed.set_thumbnail(url='https://i.imgur.com/FkqtqE8.png')

        # 直接通过ctx发送到触发命令的频道
        await ctx.reply(embed=fake_ban_embed)
        
    except asyncio.TimeoutError:
        await ctx.reply("输入超时,请重新触发命令。")

关键修正点说明

  • 替换未定义的message:使用ctx.reply()直接回复触发命令的消息,或用ctx.channel.send()在同一频道发送新消息,ctx对象已包含触发命令的频道信息,无需额外指定ID。
  • 正确格式化Embed内容:原代码中的"{username}"无法自动替换变量,改为f-string(f"{username}")实现变量插入。
  • 添加错误处理:增加超时处理和输入格式校验,避免因用户输入不规范或超时导致程序崩溃。
  • 修复图片链接:将原Imgur网页链接替换为直接图片链接,确保Embed能正常加载缩略图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 00:03:22