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

如何使用discord.py实现机器人获取私信并转发至服务器指定频道

实现Discord机器人私信转发到指定频道(discord.py)

完全可以用discord.py实现这个功能,核心是监听私信消息事件,并将内容转发到指定服务器的目标频道。以下是具体实现步骤和代码示例:

步骤说明

  • 确保已安装discord.py:执行pip install discord.py
  • 机器人需要具备读取私信、发送消息到目标频道的权限
  • 提前获取目标服务器的ID(Guild ID)和目标频道的ID(Channel ID)

代码示例

import discord
from discord.ext import commands

# 初始化机器人,设置命令前缀(可自定义)
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())

# 替换成你的目标服务器ID和频道ID
TARGET_GUILD_ID = 123456789012345678
TARGET_CHANNEL_ID = 987654321098765432

@bot.event
async def on_ready():
    print(f'已登录为 {bot.user}')

@bot.event
async def on_message(message):
    # 忽略机器人自身发送的消息,避免循环
    if message.author == bot.user:
        return
    
    # 判断是否为私信消息(guild为None代表是私信场景)
    if message.guild is None:
        # 获取目标服务器
        target_guild = bot.get_guild(TARGET_GUILD_ID)
        if not target_guild:
            print('未找到目标服务器')
            return
        
        # 获取目标频道
        target_channel = target_guild.get_channel(TARGET_CHANNEL_ID)
        if not target_channel:
            print('未找到目标频道')
            return
        
        # 转发消息内容,附带发送者信息便于溯源
        forward_content = f'来自用户 {message.author}(ID:{message.author.id})的私信:\n{message.content}'
        await target_channel.send(forward_content)
    
    # 必须保留该语句,否则机器人命令无法正常触发
    await bot.process_commands(message)

# 替换成你的机器人Token
bot.run('YOUR_BOT_TOKEN_HERE')

关键细节说明

  • discord.Intents.all():开启全部意图权限,同时需要在Discord开发者后台对应开启相关权限,确保机器人能接收私信消息
  • message.guild is None:通过该判断精准识别私信消息
  • 转发时附带用户ID和昵称,方便管理员明确消息来源
  • 务必替换代码中TARGET_GUILD_ID、TARGET_CHANNEL_ID和YOUR_BOT_TOKEN_HERE为实际值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:15:32