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

如何让discord.py机器人仅响应指定频道?

如何让Discord ChatGPT机器人仅在指定频道响应

当然可以通过指定频道ID来限制机器人的响应范围,只需要在代码中添加允许响应的频道ID列表,并在消息处理逻辑前做判断即可。

修改步骤

  1. 定义允许的频道ID列表:创建一个包含目标频道ID的整数列表(注意频道ID是纯数字的整数类型)
  2. 添加频道判断逻辑:在on_message方法中,先检查当前消息所在频道是否在允许列表内,不在则直接终止后续处理

修改后的完整代码

import discord
import openai
import os

intents = discord.Intents.all()
openai.api_key = os.getenv("KEY")

# 替换为你需要机器人响应的频道ID,支持添加多个
ALLOWED_CHANNELS = [123456789012345678, 987654321098765432]

class Chatbot(discord.Client):
    async def on_ready(self):
        print("Logged on as {0}!".format(self.user))
    
    async def on_message(self, message):
        # 忽略机器人自身发送的消息
        if message.author == self.user:
            return
        
        # 仅在指定频道内处理消息
        if message.channel.id not in ALLOWED_CHANNELS:
            return
        
        input_content = message.content

        response = openai.ChatCompletion.create(
            model = "gpt-3.5-turbo",
            messages = [{"role": "user", "content": input_content}]
        )
        assistant_response = response["choices"][0]['message']["content"]
        await message.channel.send(assistant_response)

bot = Chatbot(intents=intents)
bot.run(os.getenv("TOKEN"))

额外说明

  • 如果需要更灵活的配置(比如从环境变量读取频道ID),可以将频道ID通过逗号分隔存入环境变量,再用以下方式读取:
    ALLOWED_CHANNELS = list(map(int, os.getenv("ALLOWED_CHANNELS").split(",")))
    
    对应的环境变量值示例:123456789,987654321

内容的提问来源于stack exchange,提问作者DOHAR BD JR

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:07:18