OpenClaw 实战:用 Agent 打造你的专属新闻助手

# OpenClaw 实战:用 Agent 打造你的专属新闻助手

想每天早上起来就能看到精选的新闻摘要?想让 AI 帮你筛选感兴趣的资讯?这篇文章将带你用 OpenClaw Agent 打造一个专属新闻助手!

## 一、项目概述

### 我们要做什么?

创建一个专门的 News Agent,它能:
– 📰 自动收集科技新闻
– 🎯 根据你的兴趣筛选内容
– 📝 生成新闻摘要
– 💾 保存到本地文件
– 📧(可选)发送到你的邮箱

### 技术栈

– **OpenClaw Agent** – 核心框架
– **新闻 API** – 新闻数据源
– **Python** – 主要编程语言
– **Markdown** – 输出格式

## 二、准备工作

### 1. 创建新的 Agent

首先,让我们创建一个专门的 News Agent:

“`bash
# 创建 News Agent
openclaw agents add news-agent

# 切换到 News Agent
openclaw agents use news-agent
“`

### 2. 准备工作目录

“`bash
# 进入 News Agent 的工作区
cd ~/.openclaw/workspace-news-agent

# 创建必要的目录
mkdir data
mkdir logs
mkdir templates
“`

### 3. 选择新闻 API

推荐以下免费新闻 API:

1. **NewsAPI** – https://newsapi.org
2. **GNews** – https://gnews.io
3. **Currents** – https://currentsapi.services

我们选择 NewsAPI,因为它简单易用。

## 三、获取新闻 API 密钥

### 注册 NewsAPI

1. 访问 https://newsapi.org/register
2. 注册一个免费账号
3. 获取你的 API 密钥

免费额度:
– 每天 100 次请求
– 足够个人使用

### 测试 API

让我们用 curl 测试一下:

“`bash
# 测试 API(替换 YOUR_API_KEY)
curl “https://newsapi.org/v2/top-headlines?country=us&apiKey=YOUR_API_KEY”
“`

如果返回 JSON 数据,说明成功!

## 四、编写新闻收集脚本

### 创建配置文件

创建 `config.json`:

“`json
{
“api_key”: “YOUR_NEWSAPI_KEY”,
“categories”: [“technology”, “business”, “science”],
“countries”: [“us”, “cn”],
“max_articles”: 15,
“output_dir”: “./data”,
“keywords”: [“AI”, “OpenAI”, “Claude”, “OpenClaw”, “Python”]
}
“`

### 创建新闻收集脚本

创建 `news_collector.py`:

“`python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
import json
import datetime
import os
from typing import List, Dict

class NewsCollector:
def __init__(self, config_file: str = “config.json”):
with open(config_file, ‘r’, encoding=’utf-8′) as f:
self.config = json.load(f)

self.api_key = self.config[‘api_key’]
self.base_url = “https://newsapi.org/v2”

# 确保输出目录存在
os.makedirs(self.config[‘output_dir’], exist_ok=True)

def fetch_news(self, category: str = “technology”, country: str = “us”) -> List[Dict]:
“””获取新闻”””
url = f”{self.base_url}/top-headlines”
params = {
‘apiKey’: self.api_key,
‘category’: category,
‘country’: country,
‘pageSize’: self.config[‘max_articles’]
}

try:
response = requests.get(url, params=params, timeout=30)
if response.status_code == 200:
data = response.json()
return data.get(‘articles’, [])
else:
print(f”请求失败: {response.status_code}”)
return []
except Exception as e:
print(f”错误: {e}”)
return []

def filter_articles(self, articles: List[Dict]) -> List[Dict]:
“””根据关键词筛选文章”””
keywords = self.config.get(‘keywords’, [])
if not keywords:
return articles

filtered = []
for article in articles:
title = article.get(‘title’, ”).lower()
description = article.get(‘description’, ”).lower()

for keyword in keywords:
if keyword.lower() in title or keyword.lower() in description:
filtered.append(article)
break

return filtered

def save_to_markdown(self, articles: List[Dict], filename: str = None):
“””保存为 Markdown 文件”””
if not filename:
today = datetime.datetime.now().strftime(“%Y-%m-%d”)
filename = f”{self.config[‘output_dir’]}/news-{today}.md”

with open(filename, ‘w’, encoding=’utf-8′) as f:
f.write(f”# 新闻摘要 – {datetime.datetime.now().strftime(‘%Y年%m月%d日’)}\n\n”)

for i, article in enumerate(articles, 1):
f.write(f”## {i}. {article.get(‘title’, ‘无标题’)}\n\n”)
f.write(f”**来源**: {article.get(‘source’, {}).get(‘name’, ‘未知’)}\n\n”)
f.write(f”**时间**: {article.get(‘publishedAt’, ‘未知’)}\n\n”)
f.write(f”**链接**: {article.get(‘url’, ‘#’)}\n\n”)

description = article.get(‘description’, ”)
if description:
f.write(f”{description}\n\n”)

f.write(“—\n\n”)

print(f”已保存到: {filename}”)
return filename

def run(self):
“””运行新闻收集”””
all_articles = []

# 从多个分类和国家获取新闻
for country in self.config[‘countries’]:
for category in self.config[‘categories’]:
print(f”获取 {country} {category} 新闻…”)
articles = self.fetch_news(category, country)
all_articles.extend(articles)

# 筛选文章
filtered = self.filter_articles(all_articles)
print(f”共获取 {len(all_articles)} 篇,筛选后 {len(filtered)} 篇”)

# 保存
if filtered:
self.save_to_markdown(filtered)

if __name__ == “__main__”:
collector = NewsCollector()
collector.run()
“`

## 五、测试新闻收集器

### 运行脚本

“`bash
# 先安装依赖
pip install requests

# 运行新闻收集器
python news_collector.py
“`

### 查看结果

“`bash
# 查看生成的新闻文件
ls data/

# 查看新闻内容
cat data/news-2026-04-18.md
“`

## 六、创建 Agent 技能

现在让我们把这个变成 OpenClaw 技能!

### 创建 SKILL.md

创建 `~/.openclaw/skills/news-agent/SKILL.md`:

“`markdown
# News Agent – 新闻助手

专门的新闻收集和摘要生成 Agent。

## 功能

– 📰 收集科技新闻
– 🎯 关键词筛选
– 📝 生成新闻摘要
– 💾 保存为 Markdown

## 使用方法

当用户说”收集新闻”、”今日新闻”等时触发。

## 示例

用户:今天有什么新闻?
助手:好的,我来帮你收集今天的新闻…
[收集完成后] 已为你收集了 12 篇新闻,保存到 news-2026-04-18.md

## 触发词

– “新闻”
– “今日新闻”
– “收集新闻”
– “科技新闻”
“`

### 集成到 Agent

在 News Agent 的工作区创建 `collect_news.py`,让 OpenClaw 可以调用它。

## 七、设置定时任务

### 创建定时任务配置

让 OpenClaw 每天早上 9 点自动收集新闻:

“`bash
# 编辑定时任务
openclaw cron edit
“`

添加以下配置:

“`json
{
“tasks”: [
{
“id”: “daily-news”,
“schedule”: “0 9 * * *”,
“agent”: “news-agent”,
“task”: “运行新闻收集器,生成今日新闻摘要”,
“enabled”: true
}
]
}
“`

### 手动测试定时任务

“`bash
# 立即运行一次
openclaw cron run daily-news
“`

## 八、进阶功能

### 1. 添加摘要生成

使用 AI 为每篇新闻生成更简洁的摘要:

“`python
def generate_summary(text: str, max_length: int = 100) -> str:
“””使用 AI 生成摘要”””
# 这里可以调用 OpenClaw 的 AI 能力
# 或者使用其他摘要库
return text[:max_length] + “…” if len(text) > max_length else text
“`

### 2. 添加邮件发送

“`python
import smtplib
from email.mime.text import MIMEText

def send_email(filename: str, to_email: str):
“””发送新闻邮件”””
with open(filename, ‘r’, encoding=’utf-8′) as f:
content = f.read()

msg = MIMEText(content, ‘plain’, ‘utf-8’)
msg[‘Subject’] = f”新闻摘要 – {datetime.datetime.now().strftime(‘%Y-%m-%d’)}”
msg[‘From’] = “your-email@example.com”
msg[‘To’] = to_email

# 发送邮件…
“`

### 3. 添加更多数据源

除了 NewsAPI,还可以添加:
– RSS 源
– 社交媒体
– 特定网站爬虫

## 九、故障排除

### 问题 1:API 请求失败

**解决方案:**
– 检查 API 密钥是否正确
– 确认网络连接
– 查看是否超过每日限额

### 问题 2:没有获取到新闻

**解决方案:**
– 尝试不同的分类和国家
– 减少关键词筛选
– 增加 max_articles 数量

### 问题 3:定时任务不运行

**解决方案:**
– 检查 cron 表达式是否正确
– 确认 OpenClaw gateway 正在运行
– 查看日志文件

## 十、总结

恭喜你!现在你已经有了一个专属的新闻助手!

### 我们完成了:

1. ✅ 创建了专门的 News Agent
2. ✅ 集成了新闻 API
3. ✅ 编写了新闻收集脚本
4. ✅ 创建了 OpenClaw 技能
5. ✅ 设置了定时任务

### 下一步可以:

– 添加更多新闻源
– 实现 AI 摘要生成
– 添加邮件通知
– 创建新闻分类和标签
– 开发新闻统计和分析

记住,最好的改进来自实际使用!根据你的需求不断调整和优化。

*祝你用 News Agent 读遍天下新闻!📰🚀*

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容