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

Discord.py 修改公告发送频道后对应命令不生效问题排查

问题核心原因
  • 你定义的announcement命令第一个参数不是必填的上下文对象ctx,函数内的announcement_channel_set是局部输入参数,完全覆盖了全局的同名变量,所以你修改的全局变量根本没有被这个命令读取到。
  • changeannouncementchannel命令中,参数change已经经过类型注解转换为discord.TextChannel对象,不需要再调用bot.get_channel()传入该对象,get_channel()仅接收数字类型的频道ID,你的错误调用会导致全局变量实际被赋值为None。
  • 废弃语法问题:bot.send()方法已经在discord.py v1.0之后被移除,无法直接调用机器人对象发消息。
修复后的完整代码
import discord
from discord.ext import commands

TOKEN = 'My Token'
command_prefix = '='
# 注意需要在Discord开发者后台开启对应意图权限
bot = commands.Bot(command_prefix = command_prefix, intents=discord.Intents.all())
announcement_channel_set = None

@bot.event
async def on_ready():
  print('We have logged in as {0.user}'.format(bot))

@bot.command()
async def announcement(ctx, announcement_text):
  global announcement_channel_set
  if announcement_channel_set is None:
    # 未设置频道时默认在命令触发频道发送
    await ctx.send(f"@everyone {announcement_text}")
  else:
    await announcement_channel_set.send(f"@everyone {announcement_text}")

@bot.command()
async def changeannouncementchannel(ctx, change: discord.TextChannel):
  global announcement_channel_set
  # 直接赋值已经转换完成的频道对象即可
  announcement_channel_set = change
  await ctx.send(f"Announcement Channel Changed To #{change.name}")

bot.run(TOKEN)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 13:54:04