这是一个**Linux软件机器人助手**的 skill.md:
```yaml
---
name: ubuntu-software-bot
description: 在Ubuntu上运行的软件机器人,支持语音交互、定时任务、天气查询和新闻阅读
metadata:
author: linux-automation
version: 1.0.0
tags: [ubuntu, automation, voice, api, cron]
requirements: [curl, jq, cron, pulseaudio]
---
```
## Ubuntu软件机器人开发指南
### 核心功能架构
```bash
软件机器人 = 语音输入 → 指令解析 → 任务执行 → 语音/文字输出
```
## 1. 语音交互模块
### 语音转文字(STT)
```bash
# 使用 OpenAI Whisper 本地版
pip install openai-whisper
# 录音并识别
arecord -d 5 -f cd -t wav /tmp/input.wav
whisper /tmp/input.wav --model base --language Chinese
```
### 文字转语音(TTS)
```bash
# 方案1:espeak(离线,机械音)
sudo apt install espeak
espeak -v zh "你好,我是机器人助手"
# 方案2:edge-tts(在线,更自然)
pip install edge-tts
edge-tts --text "你好,我是机器人助手" --write-media /tmp/output.mp3
play /tmp/output.mp3
```
### Python封装
```python
#!/usr/bin/env python3
import speech_recognition as sr
import subprocess
import os
class VoiceInterface:
def __init__(self):
self.recognizer = sr.Recognizer()
def listen(self, duration=5):
"""录制并识别语音"""
with sr.Microphone() as source:
print("🎤 正在聆听...")
audio = self.recognizer.record(source, duration=duration)
try:
text = self.recognizer.recognize_whisper(audio, language="zh")
return text
except Exception as e:
return None
def speak(self, text):
"""语音输出"""
# 使用 edge-tts
cmd = f'edge-tts --text "{text}" --write-media /tmp/bot_speak.mp3'
subprocess.run(cmd, shell=True)
subprocess.run(['play', '/tmp/bot_speak.mp3'])
```
## 2. 指令解析系统
### 命令映射表
```python
COMMANDS = {
"天气": "get_weather",
"新闻": "get_news",
"定时": "set_reminder",
"提醒": "set_reminder",
"播放音乐": "play_music",
"查询": "web_search",
"打开": "open_application",
"关闭": "close_application"
}
def parse_command(text):
"""解析自然语言指令"""
for keyword, action in COMMANDS.items():
if keyword in text:
return action, text
return "unknown", text
```
### 自然语言处理(可选)
```bash
# 使用本地LLM(如ollama)
pip install ollama
# 解析用户意图
curl -X POST
http://localhost:11434/api/generate \
-d '{"model": "qwen2.5", "prompt": "提取指令:用户说'明天早上8点叫我起床'"}'
```
## 3. 定时任务系统
### 使用Cron
```bash
# 编辑crontab
crontab -e
# 每天8点播报天气
0 8 * * * /home/user/bot/weather_report.sh
# 每小时检查一次邮件
0 * * * * /home/user/bot/check_email.sh
```
### Python定时任务(APScheduler)
```python
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime
class TaskScheduler:
def __init__(self):
self.scheduler = BackgroundScheduler()
self.scheduler.start()
def add_reminder(self, time_str, message, callback):
"""添加提醒"""
hour, minute = map(int, time_str.split(':'))
self.scheduler.add_job(
callback,
'cron',
hour=hour,
minute=minute,
args=[message]
)
def daily_task(self, hour, minute, task_func):
"""每日任务"""
self.scheduler.add_job(
task_func,
'cron',
hour=hour,
minute=minute
)
```
### Systemd Timer(系统级)
```ini
# ~/.config/systemd/user/bot-daily.timer
[Unit]
Description=Daily bot task
[Timer]
OnCalendar=*-*-* 08:00:00
Persistent=true
[Install]
WantedBy=timers.target
```
## 4. 天气查询模块
### 使用OpenWeatherMap API
```python
import requests
import os
class WeatherService:
def __init__(self):
self.api_key = os.getenv('OPENWEATHER_API_KEY')
self.base_url = "
http://api.openweathermap.org/data/2.5"
def get_current(self, city="Beijing"):
"""获取当前天气"""
url = f"{self.base_url}/weather?q={city}&appid={self.api_key}&lang=zh_cn&units=metric"
response = requests.get(url)
data = response.json()
if response.status_code == 200:
weather = data['weather'][0]['description']
temp = data['main']['temp']
humidity = data['main']['humidity']
return f"今天{city}天气{weather},温度{temp}度,湿度{humidity}%"
return "获取天气失败"
def get_forecast(self, city="Beijing", days=3):
"""获取未来天气预报"""
url = f"{self.base_url}/forecast?q={city}&appid={self.api_key}&lang=zh_cn&units=metric"
response = requests.get(url)
# 解析并返回格式化预报...
```
### 免费替代方案( wttr.in )
```bash
# 命令行获取天气(无需API key)
curl -s "wttr.in/Beijing?format=3"
# 详细天气
curl -s "wttr.in/Beijing" | head -17
```
## 5. 新闻阅读模块
### RSS订阅抓取
```python
import feedparser
class NewsReader:
def __init__(self):
self.sources = {
"tech": "
https://www.techcrunch.com/feed/",
"china": "
https://news.sina.com.cn/rss/china.xml",
"world": "
https://feeds.bbci.co.uk/news/world/rss.xml"
}
def get_headlines(self, category="china", count=5):
"""获取新闻标题"""
feed = feedparser.parse(self.sources[category])
headlines = []
for entry in feed.entries[:count]:
headlines.append(f"• {entry.title}")
return "\n".join(headlines)
def read_news(self, category="china"):
"""语音播报新闻"""
news = self.get_headlines(category)
summary = f"以下是{category}类新闻:{news}"
self.speak(summary)
return summary
```
### 网页抓取(BeautifulSoup)
```python
from bs4 import BeautifulSoup
import requests
def scrape_news(url, selector):
"""抓取特定网站新闻"""
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
articles = soup.select(selector)
return [a.get_text().strip() for a in articles[:5]]
```
## 6. 系统监控与控制
### 系统信息获取
```python
import psutil
import subprocess
class SystemMonitor:
def get_status(self):
"""获取系统状态"""
cpu = psutil.cpu_percent()
memory = psutil.virtual_memory().percent
disk = psutil.disk_usage('/').percent
return f"CPU使用率{cpu}%,内存使用率{memory}%,磁盘使用率{disk}%"
def control_volume(self, level):
"""控制音量 0-100"""
subprocess.run(['amixer', 'set', 'Master', f'{level}%'])
def control_brightness(self, level):
"""控制屏幕亮度(需安装brightnessctl)"""
subprocess.run(['brightnessctl', 'set', f'{level}%'])
```
### 应用控制
```python
import subprocess
class AppController:
def open(self, app_name):
"""打开应用"""
apps = {
"浏览器": "firefox",
"文件管理器": "nautilus",
"终端": "gnome-terminal",
"音乐": "spotify"
}
if app_name in apps:
subprocess.Popen([apps[app_name]])
def close(self, app_name):
"""关闭应用"""
subprocess.run(['pkill', '-f', app_name])
```
## 7. 完整机器人示例
```python
#!/usr/bin/env python3
"""
Ubuntu Software Bot - 主程序
"""
import os
import sys
from datetime import datetime
class UbuntuBot:
def __init__(self):
self.voice = VoiceInterface()
self.weather = WeatherService()
self.news = NewsReader()
self.scheduler = TaskScheduler()
self.system = SystemMonitor()
self.apps = AppController()
print("🤖 Ubuntu Bot 已启动")
def process(self, text):
"""处理用户输入"""
action, full_text = parse_command(text)
if action == "get_weather":
response = self.weather.get_current()
elif action == "get_news":
response = self.news.get_headlines()
elif action == "set_reminder":
response = self.set_timer(full_text)
elif action == "system_status":
response = self.system.get_status()
else:
response = "我不太明白,你可以说:天气、新闻、定时提醒等"
print(f"🤖: {response}")
self.voice.speak(response)
return response
def set_timer(self, text):
"""解析并设置定时任务"""
# 简单实现:提取时间(如"8点"、"30分钟后")
import re
# 匹配"X点"或"X:X"
time_match = re.search(r'(\d+)[点时]', text)
if time_match:
hour = time_match.group(1)
return f"已设置每天{hour}点的提醒"
return "请指定具体时间,比如'明天8点'"
def run(self):
"""主循环"""
while True:
text = self.voice.listen()
if text:
print(f"👤: {text}")
self.process(text)
if __name__ == "__main__":
bot = UbuntuBot()
bot.run()
```
## 8. 安装与配置
### 依赖安装脚本
```bash
#!/bin/bash
# install.sh
sudo apt update
sudo apt install -y \
python3-pip \
python3-venv \
portaudio19-dev \
espeak \
ffmpeg \
sox \
libsox-fmt-mp3 \
curl \
jq
# Python依赖
pip3 install \
SpeechRecognition \
pyaudio \
requests \
beautifulsoup4 \
feedparser \
apscheduler \
psutil \
openai-whisper \
edge-tts
echo "✅ 安装完成!"
echo "请设置环境变量:export OPENWEATHER_API_KEY='your_key'"
```
### 开机自启(Systemd)
```ini
# ~/.config/systemd/user/bot.service
[Unit]
Description=Ubuntu Software Bot
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/python3 /home/user/bot/main.py
Restart=always
RestartSec=10
[Install]
WantedBy=default.target
```
启用:
```bash
systemctl --user enable bot.service
systemctl --user start bot.service
```
## 9. 使用示例
```bash
# 语音命令示例:
"今天天气怎么样" → 播报天气
"读一下新闻" → 播报头条新闻
"明天8点叫我起床" → 设置定时提醒
"打开浏览器" → 启动Firefox
"系统状态" → 报告CPU/内存使用率
"播放音乐" → 打开音乐播放器
```
## 10. 扩展功能建议
- [ ] **智能家居控制** - 接入Home Assistant
- [ ] **邮件提醒** - 检查新邮件并语音播报
- [ ] **日历集成** - 读取Google/Outlook日历事件
- [ ] **文件管理** - 语音搜索和操作文件
- [ ] **翻译功能** - 实时语音翻译
- [ ] **聊天对话** - 接入本地LLM进行闲聊
这是一个完整的Ubuntu软件机器人框架,你可以根据需求裁剪功能!需要我详细解释某个模块吗?