-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
148 lines (124 loc) · 4.83 KB
/
main.py
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
import asyncio
import aiohttp
from datetime import datetime, timedelta
import random
import logging
# 导入配置
from config import (
API_URL, # 分数API
WEBHOOK_URL,
PROXY_URL,
USE_PROXY,
INTERVAL,
TIME_OFFSET,
ALWAYS_NOTIFY,
APP_NAME,
TOKENS_CONFIG
)
# 配置logging
def setup_logging():
"""配置日志格式和级别"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
return logging.getLogger(__name__)
logger = setup_logging()
# 随机延迟函数
async def random_delay():
"""生成随机延迟时间(10-20秒)"""
delay = random.uniform(10, 20)
logger.info(f"等待 {delay:.2f} 秒...")
await asyncio.sleep(delay)
async def fetch_points(session, api_url, api_token):
"""获取分数数据"""
headers = {
"accept": "application/json",
"authorization": f"Bearer {api_token}",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
try:
async with session.get(api_url, headers=headers, ssl=False) as response:
if response.status == 200:
data = await response.json()
return data.get('points', 0)
else:
logger.error(f"获取分数失败: {response.status}")
return None
except Exception as e:
logger.error(f"获取分数出错: {str(e)}")
return None
def build_message(tokens_points):
"""构建包含所有token分数的通知消息"""
adjusted_time = datetime.now() + timedelta(hours=TIME_OFFSET)
timestamp = adjusted_time.strftime('%Y-%m-%d %H:%M:%S')
message = f"🔍 【{APP_NAME} 状态报告】\n⏰ 时间: {timestamp}\n\n"
for token_name, (points, change) in tokens_points.items():
message += f"👤 账户: {token_name} 💰 当前分数: {points} (+{change})\n"
return message.strip()
async def send_message_async(webhook_url, message_content, use_proxy, proxy_url):
"""发送消息到webhook"""
headers = {'Content-Type': 'application/json'}
payload = {
"msgtype": "text",
"text": {
"content": message_content
}
}
proxy = proxy_url if use_proxy else None
async with aiohttp.ClientSession() as session:
async with session.post(webhook_url, json=payload, headers=headers, proxy=proxy) as response:
if response.status == 200:
logger.info("消息发送成功!")
else:
logger.error(f"发送消息失败: {response.status}")
async def monitor_single_token(session, token_config):
"""获取单个token的分数"""
try:
logger.info(f"开始检查Token: {token_config['name']}")
points = await fetch_points(session, API_URL, token_config['token'])
logger.info(f"获取到分数: {points}")
return token_config['name'], points
except Exception as e:
logger.error(f"❌ 监控Token {token_config['name']} 时出错: {str(e)}")
return token_config['name'], None
finally:
logger.info(f"检查完成: {token_config['name']}")
async def monitor_points(interval, webhook_url, use_proxy, proxy_url):
"""主监控函数"""
iteration = 1
previous_points = {} # 用于存储上次的得分
while True:
try:
logger.info(f"\n开始第 {iteration} 轮检查...")
tokens_points = {}
async with aiohttp.ClientSession() as session:
for token_config in TOKENS_CONFIG:
token_name, points = await monitor_single_token(session, token_config)
if points is not None:
# 计算得分变化
previous = previous_points.get(token_name, 0)
change = points - previous
tokens_points[token_name] = (points, change)
# 更新上次得分
previous_points[token_name] = points
await random_delay()
if tokens_points and ALWAYS_NOTIFY:
message = build_message(tokens_points)
await send_message_async(webhook_url, message, use_proxy, proxy_url)
logger.info("✅ 消息发送成功")
logger.info(f"第 {iteration} 轮检查完成\n")
iteration += 1
except Exception as e:
logger.error(f"监控过程出错: {str(e)}")
await asyncio.sleep(5)
continue
await asyncio.sleep(interval)
if __name__ == "__main__":
asyncio.run(monitor_points(
interval=INTERVAL,
webhook_url=WEBHOOK_URL,
use_proxy=USE_PROXY,
proxy_url=PROXY_URL
))