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

Discord Bot on_ready事件报错求助:无法推送R星新闻至指定频道

修复Discord机器人「ERROR discord.client Ignoring exception in on_ready」错误

我开发Discord机器人时遇到了「ERROR discord.client Ignoring exception in on_ready」错误,机器人的功能是抓取Rockstar Games新闻页内容并发送到指定Discord频道,当前代码如下:

import discord
import requests
from bs4 import BeautifulSoup
client = discord.Client(intents=discord.Intents.default())
def get_latest_article():
    url = 'https://www.rockstargames.com/newswire'
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    article = soup.find('div', {'class': 'featured-post'}).find('a')
    title = article.text.strip()
    url = article['href']
    return title, url
@client.event
async def on_ready():
    channel = client.get_channel(channel_id)
    title, url = get_latest_article()
    await channel.send(f'**{title}**\n{url}')
client.run('bot_token_here')

错误原因及修复方案

1. 未定义频道ID

代码中直接使用channel_id变量但未赋值,需替换为目标频道的整数ID:

# 替换成你的实际频道ID
CHANNEL_ID = 123456789012345678

然后在on_ready中修改为:

channel = client.get_channel(CHANNEL_ID)

2. Intents权限不足

Discord默认intents不包含消息内容权限,需手动启用并在开发者后台配置:

  • 在Discord开发者门户的机器人页面,开启「Message Content Intent」
  • 修改代码中的intents初始化:
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)

3. 网页解析无异常处理

若网页结构变化或抓取失败,soup.find会返回None,调用.find('a')会触发AttributeError,需添加异常处理并模拟浏览器请求避免反爬:

def get_latest_article():
    url = 'https://www.rockstargames.com/newswire'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
    }
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()  # 检查请求是否成功
        soup = BeautifulSoup(response.text, 'html.parser')
        featured_post = soup.find('div', {'class': 'featured-post'})
        if not featured_post:
            return "未找到最新文章", ""
        article = featured_post.find('a')
        if not article:
            return "未找到文章链接", ""
        title = article.text.strip()
        article_url = article['href']
        # 拼接完整URL
        if not article_url.startswith('http'):
            article_url = f'https://www.rockstargames.com{article_url}'
        return title, article_url
    except Exception as e:
        return f"抓取失败: {str(e)}", ""

4. 未替换机器人令牌

将client.run('bot_token_here')中的bot_token_here替换为你的机器人实际令牌。

5. 发送消息前检查频道是否存在

避免因频道不存在导致错误:

@client.event
async def on_ready():
    print(f'已登录为 {client.user}')
    channel = client.get_channel(CHANNEL_ID)
    if not channel:
        print("未找到指定频道")
        return
    title, url = get_latest_article()
    if title and url:
        await channel.send(f'**{title}**\n{url}')
    else:
        await channel.send(title)

修复后的完整代码

import discord
import requests
from bs4 import BeautifulSoup

# 替换成你的实际频道ID
CHANNEL_ID = 123456789012345678
# 替换成你的机器人令牌
BOT_TOKEN = 'your_actual_bot_token'

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

def get_latest_article():
    url = 'https://www.rockstargames.com/newswire'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
    }
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, 'html.parser')
        featured_post = soup.find('div', {'class': 'featured-post'})
        if not featured_post:
            return "未找到最新文章", ""
        article = featured_post.find('a')
        if not article:
            return "未找到文章链接", ""
        title = article.text.strip()
        article_url = article['href']
        if not article_url.startswith('http'):
            article_url = f'https://www.rockstargames.com{article_url}'
        return title, article_url
    except Exception as e:
        return f"抓取失败: {str(e)}", ""

@client.event
async def on_ready():
    print(f'已登录为 {client.user}')
    channel = client.get_channel(CHANNEL_ID)
    if not channel:
        print("未找到指定频道")
        return
    title, url = get_latest_article()
    if title and url:
        await channel.send(f'**{title}**\n{url}')
    else:
        await channel.send(title)

client.run(BOT_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.27 19:15:00