-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig_manager.py
More file actions
355 lines (280 loc) · 11.7 KB
/
Copy pathconfig_manager.py
File metadata and controls
355 lines (280 loc) · 11.7 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
import os
import json
import logging
from typing import Dict, Any, List, Optional
class ConfigManager:
def __init__(self, config_file: str = "config.json"):
"""
Initialize the configuration manager.
Args:
config_file: Path to the configuration file
"""
self.config_file = config_file
self.logger = logging.getLogger(__name__)
self.config = self._load_config()
def _load_config(self) -> Dict[str, Any]:
"""
Load configuration from file.
Returns:
Configuration dictionary
"""
try:
if os.path.exists(self.config_file):
with open(self.config_file, 'r', encoding='utf-8') as f:
return json.load(f)
else:
# Create default configuration
default_config = self._create_default_config()
self._save_config(default_config)
return default_config
except Exception as e:
self.logger.error(f"Error loading configuration: {str(e)}")
return self._create_default_config()
def _create_default_config(self) -> Dict[str, Any]:
"""
Create default configuration.
Returns:
Default configuration dictionary
"""
return {
"telegram": {
"api_id": "",
"api_hash": "",
"bot_token": "",
"channels": [],
"subscribers": []
},
"llm": {
"api_key": "",
"base_url": "https://api.openai.com/v1",
"model": "gpt-4-vision-preview",
"max_tokens": 1000
},
"scheduler": {
"collection_interval": "1h",
"analysis_interval": "3h",
"cleanup_interval": "24h" # Add cleanup interval
},
# Add cleanup configuration
"cleanup": {
"folders": {
"media": {"max_age_days": 7, "keep_latest": 100},
"logs": {"max_age_days": 30, "keep_latest": 10},
"data": {"max_age_days": 14, "keep_latest": 20},
"analysis": {"max_age_days": 30, "keep_latest": 50}
}
},
"channel_descriptions": {},
"analysis_prompts": {
"default": "Analyze the following messages from various Telegram channels. Provide a concise summary highlighting key information, trends, and insights. Include the most important points from each channel, considering their context and focus.",
"tech_news": "Analyze these technology news updates. Focus on emerging trends, significant product launches, and important developments in the tech industry. Highlight potential impacts on the market and consumers.",
"finance": "Analyze these financial updates. Identify key market movements, important economic indicators, and significant company announcements. Provide context on how these developments might affect investors."
},
}
def _save_config(self, config: Dict[str, Any] = None):
"""
Save configuration to file.
Args:
config: Configuration dictionary to save (uses self.config if None)
"""
try:
config_to_save = config if config is not None else self.config
with open(self.config_file, 'w', encoding='utf-8') as f:
json.dump(config_to_save, f, ensure_ascii=False, indent=2)
self.logger.info(f"Configuration saved to {self.config_file}")
except Exception as e:
self.logger.error(f"Error saving configuration: {str(e)}")
def get_config(self, section: str = None, key: str = None) -> Any:
"""
Get configuration value.
Args:
section: Configuration section (optional)
key: Configuration key within section (optional)
Returns:
Configuration value, section, or entire config
"""
if section is None:
return self.config
if section not in self.config:
return None
if key is None:
return self.config[section]
return self.config[section].get(key)
def set_config(self, section: str, key: str, value: Any) -> bool:
"""
Set configuration value.
Args:
section: Configuration section
key: Configuration key within section
value: Value to set
Returns:
Success flag
"""
try:
if section not in self.config:
self.config[section] = {}
self.config[section][key] = value
self._save_config()
return True
except Exception as e:
self.logger.error(f"Error setting configuration {section}.{key}: {str(e)}")
return False
def add_channel(self, channel: str, description: str = None) -> bool:
"""
Add a channel to the configuration.
Args:
channel: Channel username or ID
description: Optional channel description
Returns:
Success flag
"""
try:
channels = self.config["telegram"]["channels"]
if channel not in channels:
channels.append(channel)
if description and channel not in self.config.get("channel_descriptions", {}):
if "channel_descriptions" not in self.config:
self.config["channel_descriptions"] = {}
self.config["channel_descriptions"][channel] = description
self._save_config()
return True
except Exception as e:
self.logger.error(f"Error adding channel {channel}: {str(e)}")
return False
def remove_channel(self, channel: str) -> bool:
"""
Remove a channel from the configuration.
Args:
channel: Channel username or ID
Returns:
Success flag
"""
try:
channels = self.config["telegram"]["channels"]
if channel in channels:
channels.remove(channel)
if "channel_descriptions" in self.config and channel in self.config["channel_descriptions"]:
del self.config["channel_descriptions"][channel]
self._save_config()
return True
except Exception as e:
self.logger.error(f"Error removing channel {channel}: {str(e)}")
return False
def add_subscriber(self, user_id: str) -> bool:
"""
Add a subscriber to the configuration.
Args:
user_id: User ID to add
Returns:
Success flag
"""
try:
subscribers = self.config["telegram"]["subscribers"]
if user_id not in subscribers:
subscribers.append(user_id)
self._save_config()
return True
except Exception as e:
self.logger.error(f"Error adding subscriber {user_id}: {str(e)}")
return False
def remove_subscriber(self, user_id: str) -> bool:
"""
Remove a subscriber from the configuration.
Args:
user_id: User ID to remove
Returns:
Success flag
"""
try:
subscribers = self.config["telegram"]["subscribers"]
if user_id in subscribers:
subscribers.remove(user_id)
self._save_config()
return True
except Exception as e:
self.logger.error(f"Error removing subscriber {user_id}: {str(e)}")
return False
def get_channels(self) -> List[str]:
"""
Get list of configured channels.
Returns:
List of channel usernames/IDs
"""
return self.config.get("telegram", {}).get("channels", [])
def get_subscribers(self) -> List[str]:
"""
Get list of subscribers.
Returns:
List of user IDs
"""
return self.config.get("telegram", {}).get("subscribers", [])
def get_channel_descriptions(self) -> Dict[str, str]:
"""
Get channel descriptions.
Returns:
Dictionary mapping channels to descriptions
"""
return self.config.get("channel_descriptions", {})
def get_analysis_prompt(self, prompt_type: str = "default") -> str:
"""
Get analysis prompt by type.
Args:
prompt_type: Prompt type
Returns:
Prompt string
"""
prompts = self.config.get("analysis_prompts", {})
return prompts.get(prompt_type, prompts.get("default", ""))
def set_analysis_prompt(self, prompt_type: str, prompt: str) -> bool:
"""
Set analysis prompt.
Args:
prompt_type: Prompt type
prompt: Prompt string
Returns:
Success flag
"""
try:
if "analysis_prompts" not in self.config:
self.config["analysis_prompts"] = {}
self.config["analysis_prompts"][prompt_type] = prompt
self._save_config()
return True
except Exception as e:
self.logger.error(f"Error setting analysis prompt {prompt_type}: {str(e)}")
return False
def main():
"""Example usage of the ConfigManager."""
# Initialize config manager
config_manager = ConfigManager()
# Set configuration values
config_manager.set_config("telegram", "api_id", "YOUR_API_ID")
config_manager.set_config("telegram", "api_hash", "YOUR_API_HASH")
config_manager.set_config("telegram", "bot_token", "YOUR_BOT_TOKEN")
# Add channels with descriptions
config_manager.add_channel("techcrunch", "Technology news and startup updates")
config_manager.add_channel("financenews", "Financial market analysis and updates")
config_manager.add_channel("worldevents", "Global news and current events")
# Add subscribers
config_manager.add_subscriber("USER_ID_1")
config_manager.add_subscriber("USER_ID_2")
# Set a custom analysis prompt
custom_prompt = (
"Analyze these messages with a focus on identifying key trends and patterns. "
"Highlight important information that would be valuable for users interested in "
"staying informed about developments in technology, finance, and global events."
)
config_manager.set_analysis_prompt("custom", custom_prompt)
# Display current configuration
full_config = config_manager.get_config()
print("Current configuration:")
print(json.dumps(full_config, indent=2))
# Get specific configuration values
api_key = config_manager.get_config("llm", "api_key")
channels = config_manager.get_channels()
channel_descriptions = config_manager.get_channel_descriptions()
print(f"\nConfigured channels: {channels}")
print(f"Channel descriptions: {channel_descriptions}")
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
main()