-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
388 lines (307 loc) · 12.9 KB
/
bot.py
File metadata and controls
388 lines (307 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
#!/usr/bin/env python3
"""
A股行情监控 - Telegram Bot 持仓管理
通过 Telegram 命令交互式管理持仓,无需手动编辑配置文件。
命令列表:
/start - 显示帮助
/add <code> <price> <shares> [stop_loss] [take_profit]
- 添加持仓
/remove <code> - 删除持仓
/list - 查看所有持仓
/watch <code> <name> - 添加关注股票
/unwatch <code> - 删除关注股票
/status - 查看监控状态
"""
import logging
import os
import sys
from typing import Optional
import yaml
from telegram import Update, BotCommand
from telegram.ext import (
ApplicationBuilder,
CommandHandler,
ContextTypes,
)
# 导入新闻模块
from news import get_morning_news, get_evening_news, get_instant_news
# 导入用户配置模块
from user_config import load_user_config, save_user_config, get_all_users
# ── 日志 ──────────────────────────────────────────────────────
logging.basicConfig(
format="%(asctime)s [%(levelname)s] %(name)s - %(message)s",
level=logging.INFO,
)
logger = logging.getLogger(__name__)
# ── 权限控制 ──────────────────────────────────────────────────
# 允许使用 Bot 的 Telegram User ID 白名单
# 获取你的 User ID: 向 @userinfobot 发送消息,它会告诉你
ALLOWED_USERS = [
# 465948141, # 示例:替换为你的 Telegram User ID
]
def check_permission(user_id: int) -> bool:
"""检查用户是否有权限"""
# 如果白名单为空,允许所有人(方便调试)
if not ALLOWED_USERS:
logger.warning("⚠️ 白名单为空,任何人都可以使用 Bot!请在 bot.py 中配置 ALLOWED_USERS")
return True
return user_id in ALLOWED_USERS
CONFIG_FILE = "config.yaml"
# ── 辅助函数 ──────────────────────────────────────────────────
def load_config() -> dict:
"""加载配置文件"""
if not os.path.exists(CONFIG_FILE):
logger.error(f"配置文件不存在: {CONFIG_FILE}")
sys.exit(1)
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
return yaml.safe_load(f)
def save_config(config: dict):
"""保存配置文件"""
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
yaml.dump(config, f, allow_unicode=True, default_flow_style=False)
logger.info("配置已保存")
def get_stock_name(code: str) -> str:
"""从 AKShare 获取股票名称(简化版,可选)"""
try:
import akshare as ak
df = ak.stock_zh_a_spot_em()
df["代码"] = df["代码"].astype(str).str.zfill(6)
match = df[df["代码"] == code]
if not match.empty:
return match.iloc[0]["名称"]
except Exception as e:
logger.warning(f"获取股票名称失败: {e}")
return code
# ── Bot 命令处理 ──────────────────────────────────────────────
async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""显示帮助信息"""
help_text = (
"📊 *A股行情监控 Bot*\n\n"
"*持仓管理:*\n"
"/add `<代码>` `<买入价>` `<股数>` `[止损%]` `[止盈%]`\n"
" 例: `/add 600519 1500 100 -5 10`\n\n"
"/remove `<代码>` - 删除持仓\n"
"/list - 查看所有持仓\n\n"
"*关注池:*\n"
"/watch `<代码>` `<名称>` - 添加关注\n"
" 例: `/watch 300750 宁德时代`\n\n"
"/unwatch `<代码>` - 删除关注\n\n"
"*新闻资讯:*\n"
"/news - 即时财经快讯\n"
"/morning - 早间新闻(外盘+快讯)\n"
"/evening - 晚间总结(收盘+资金)\n\n"
"*监控:*\n"
"/status - 查看监控运行状态\n"
)
await update.message.reply_text(help_text, parse_mode="Markdown")
async def cmd_add(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""添加持仓"""
# 权限检查
user_id = update.effective_user.id
if not check_permission(user_id):
await update.message.reply_text("⛔ 无权限使用此 Bot")
return
args = context.args
if len(args) < 3:
await update.message.reply_text(
"❌ 用法: /add <代码> <买入价> <股数> [止损%] [止盈%]\n"
"例: /add 600519 1500 100 -5 10"
)
return
code = args[0].zfill(6)
try:
buy_price = float(args[1])
shares = int(args[2])
stop_loss = float(args[3]) if len(args) > 3 else -5.0
take_profit = float(args[4]) if len(args) > 4 else 10.0
except ValueError:
await update.message.reply_text("❌ 价格和股数必须是数字")
return
# 获取股票名称
name = get_stock_name(code)
# 加载用户配置
config = load_user_config(user_id)
# 添加持仓
config["portfolio"][code] = {
"name": name,
"buy_price": buy_price,
"shares": shares,
"stop_loss": stop_loss,
"take_profit": take_profit,
}
save_user_config(user_id, config)
msg = (
f"✅ 已添加持仓: *{name}({code})*\n"
f"买入价 ¥{buy_price:.2f} × {shares}股\n"
f"止损 {stop_loss:+.1f}% / 止盈 {take_profit:+.1f}%"
)
await update.message.reply_text(msg, parse_mode="Markdown")
async def cmd_remove(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""删除持仓"""
# 权限检查
user_id = update.effective_user.id
if not check_permission(user_id):
await update.message.reply_text("⛔ 无权限使用此 Bot")
return
if not context.args:
await update.message.reply_text("❌ 用法: /remove <代码>")
return
code = context.args[0].zfill(6)
config = load_user_config(user_id)
if code not in config["portfolio"]:
await update.message.reply_text(f"❌ 未找到持仓: {code}")
return
name = config["portfolio"][code].get("name", code)
del config["portfolio"][code]
save_user_config(user_id, config)
await update.message.reply_text(f"✅ 已删除持仓: *{name}({code})*", parse_mode="Markdown")
async def cmd_list(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""列出所有持仓"""
user_id = update.effective_user.id
if not check_permission(user_id):
await update.message.reply_text("⛔ 无权限使用此 Bot")
return
config = load_user_config(user_id)
portfolio = config.get("portfolio", {})
if not portfolio:
await update.message.reply_text("📭 当前没有持仓")
return
lines = ["💼 *我的持仓*\n"]
for code, info in portfolio.items():
name = info.get("name", code)
buy_price = info.get("buy_price", 0)
shares = info.get("shares", 0)
stop_loss = info.get("stop_loss", -5)
take_profit = info.get("take_profit", 10)
lines.append(
f"• *{name}({code})*\n"
f" 买入价 ¥{buy_price:.2f} × {shares}股\n"
f" 止损 {stop_loss:+.1f}% / 止盈 {take_profit:+.1f}%"
)
await update.message.reply_text("\n\n".join(lines), parse_mode="Markdown")
async def cmd_watch(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""添加关注股票"""
# 权限检查
user_id = update.effective_user.id
if not check_permission(user_id):
await update.message.reply_text("⛔ 无权限使用此 Bot")
return
if len(context.args) < 2:
await update.message.reply_text(
"❌ 用法: /watch <代码> <名称>\n"
"例: /watch 300750 宁德时代"
)
return
code = context.args[0].zfill(6)
name = " ".join(context.args[1:])
config = load_user_config(user_id)
config["watchlist"][code] = name
save_user_config(user_id, config)
await update.message.reply_text(
f"✅ 已添加关注: *{name}({code})*",
parse_mode="Markdown"
)
async def cmd_unwatch(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""删除关注股票"""
# 权限检查
user_id = update.effective_user.id
if not check_permission(user_id):
await update.message.reply_text("⛔ 无权限使用此 Bot")
return
if not context.args:
await update.message.reply_text("❌ 用法: /unwatch <代码>")
return
code = context.args[0].zfill(6)
config = load_user_config(user_id)
if code not in config.get("watchlist", {}):
await update.message.reply_text(f"❌ 未找到关注股票: {code}")
return
name = config["watchlist"][code]
del config["watchlist"][code]
save_user_config(user_id, config)
await update.message.reply_text(f"✅ 已删除关注: *{name}({code})*", parse_mode="Markdown")
async def cmd_status(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""查看监控状态"""
user_id = update.effective_user.id
# 读取用户的持仓和关注池数量
config = load_user_config(user_id)
portfolio_count = len(config.get("portfolio", {}))
watchlist_count = len(config.get("watchlist", {}))
# 统计总用户数
total_users = len(get_all_users())
# 读取全局配置获取通知渠道
global_config = load_config()
notif = global_config.get("notification", {})
channels = []
if notif.get("telegram", {}).get("enabled"):
channels.append("Telegram")
if notif.get("dingtalk", {}).get("enabled"):
channels.append("钉钉")
if notif.get("email", {}).get("enabled"):
channels.append("邮件")
notif_status = "、".join(channels) if channels else "未启用"
msg = (
"📊 *监控状态*\n\n"
f"持仓股票: {portfolio_count} 只\n"
f"关注股票: {watchlist_count} 只\n"
f"通知渠道: {notif_status}\n\n"
"提示: 主程序需单独运行 `python monitor.py`"
)
await update.message.reply_text(msg, parse_mode="Markdown")
# ── 新闻命令 ──────────────────────────────────────────────────
async def cmd_news(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""即时新闻"""
await update.message.reply_text("📰 正在获取最新资讯...")
try:
news = get_instant_news()
await update.message.reply_text(news)
except Exception as e:
logger.error(f"获取新闻失败: {e}")
await update.message.reply_text("❌ 获取新闻失败,请稍后重试")
async def cmd_morning(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""早间新闻"""
await update.message.reply_text("🌅 正在获取早间新闻...")
try:
news = get_morning_news()
await update.message.reply_text(news)
except Exception as e:
logger.error(f"获取早间新闻失败: {e}")
await update.message.reply_text("❌ 获取新闻失败,请稍后重试")
async def cmd_evening(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""晚间新闻"""
await update.message.reply_text("🌆 正在获取晚间总结...")
try:
news = get_evening_news()
await update.message.reply_text(news)
except Exception as e:
logger.error(f"获取晚间新闻失败: {e}")
await update.message.reply_text("❌ 获取新闻失败,请稍后重试")
# ── 主程序 ────────────────────────────────────────────────────
def main():
# 加载配置获取 Bot Token
config = load_config()
bot_token = config.get("notification", {}).get("telegram", {}).get("bot_token")
if not bot_token or bot_token == "YOUR_BOT_TOKEN":
logger.error("❌ 未配置 Telegram Bot Token,请在 config.yaml 中填入")
sys.exit(1)
# 创建 Bot
app = ApplicationBuilder().token(bot_token).build()
# 注册命令
app.add_handler(CommandHandler("start", cmd_start))
app.add_handler(CommandHandler("help", cmd_start))
app.add_handler(CommandHandler("add", cmd_add))
app.add_handler(CommandHandler("remove", cmd_remove))
app.add_handler(CommandHandler("list", cmd_list))
app.add_handler(CommandHandler("watch", cmd_watch))
app.add_handler(CommandHandler("unwatch", cmd_unwatch))
app.add_handler(CommandHandler("status", cmd_status))
# 新闻命令
app.add_handler(CommandHandler("news", cmd_news))
app.add_handler(CommandHandler("morning", cmd_morning))
app.add_handler(CommandHandler("evening", cmd_evening))
# 启动
logger.info("🤖 Telegram Bot 启动成功")
logger.info("发送 /start 查看帮助")
app.run_polling()
if __name__ == "__main__":
main()