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

Discord机器人可正常运行但无法向服务器发送消息求助

问题修复:Discord机器人无法发送消息到指定频道

你的代码存在几个关键问题,导致无法正常发送消息,以下是逐一修复方案:

1. 缺少消息内容意图(Message Content Intent)

Discord.py v2.0+ 需要显式开启message_content意图才能读取用户消息内容,否则on_message事件无法触发。

  • 修改Intents初始化代码:
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
  • 同时需要在Discord开发者门户的机器人页面,开启"Message Content Intent"权限。

2. Channel ID参数类型错误

client.get_channel()需要传入整数类型的频道ID,而不是字符串。把代码中的字符串类型ID改为整数:

channel = client.get_channel(123456789012345678)  # 替换成你的频道ID(整数)

3. 缺少必要权限

确保机器人在目标服务器拥有以下权限:

  • 查看频道(View Channels)
  • 发送消息(Send Messages)
  • 嵌入链接(Embed Links,可选,用于更好展示链接)

4. 添加异常处理(可选但推荐)

为避免因抓取失败或频道不存在导致崩溃,添加异常处理逻辑:

@client.event
async def on_message(message):
    if message.content.startswith('!latest'):
        try:
            latest_article_link = get_latest_article_link()
            channel = client.get_channel(123456789012345678)
            if channel:
                await channel.send(latest_article_link)
            else:
                await message.channel.send("指定频道不存在!")
        except Exception as e:
            await message.channel.send(f"获取最新文章失败:{str(e)}")

完整修改后的代码

import discord
import requests
from bs4 import BeautifulSoup

# Discord API token
TOKEN = "你的机器人Token"

# 配置Intents
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)

# Website URL
url = 'https://www.rockstargames.com/newswire'

# Function to fetch latest article link
def get_latest_article_link():
    response = requests.get(url)
    response.raise_for_status()  # 检查请求是否成功
    soup = BeautifulSoup(response.content, 'html.parser')
    latest_article_link = soup.find('a', class_='FeaturedNews-header')['href']
    # 拼接完整URL,避免相对链接
    if not latest_article_link.startswith('http'):
        latest_article_link = f"https://www.rockstargames.com{latest_article_link}"
    return latest_article_link

# Event listener for when the bot is ready
@client.event
async def on_ready():
    print('Logged in as {0.user}'.format(client))

# Command to send the latest article link to the specified channel
@client.event
async def on_message(message):
    if message.content.startswith('!latest'):
        try:
            latest_article_link = get_latest_article_link()
            channel = client.get_channel(123456789012345678)  # 替换为你的频道ID(整数)
            if channel:
                await channel.send(latest_article_link)
                await message.channel.send("已发送最新文章链接到指定频道!")
            else:
                await message.channel.send("错误:指定的频道不存在!")
        except requests.exceptions.RequestException as e:
            await message.channel.send(f"请求新闻页面失败:{str(e)}")
        except TypeError:
            await message.channel.send("错误:未找到最新文章链接!")
        except Exception as e:
            await message.channel.send(f"发生未知错误:{str(e)}")

# Run the bot
client.run(TOKEN)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:25:06