-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.py
More file actions
114 lines (91 loc) · 3.13 KB
/
tools.py
File metadata and controls
114 lines (91 loc) · 3.13 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
# By Pytel
import os
import json
import asyncio
import async_timeout
def create_config(config_file: str):
"""
Creates a new config file
Args:
config_file (str, optional): Path to config file.
"""
config = {}
config['API_TOKEN'] = input('Enter API token: ')
config['SERVER_ID'] = int(input('Enter server ID: '))
config['CATEGORY_ID'] = int(input('Enter category ID: '))
json.dump(config, open(config_file, 'w', encoding='utf-8'),
indent=4, sort_keys=True)
def load_config(config_file: str) -> tuple:
"""
Loads config file
Args:
config_file (str, optional): Path to config file.
Returns:
tuple: Tuple containing API_TOKEN, CHANNEL_ID, SERVER_ID, CATEGORY_ID
"""
config = json.load(open(config_file, 'r', encoding='utf-8'))
#print(json.dumps(config, indent=4, sort_keys=True))
return config['API_TOKEN'], config['SERVER_ID'], config['CATEGORY_ID']
def pipe_is_empty(pipe_path: str) -> bool:
"""
Checks if a named pipe size is 0.
If the pipe does not exist, it returns True.
Args:
pipe_path (str): Path to the pipe
Returns:
bool: True if pipe is empty or does not exist, False otherwise
"""
try:
if os.path.exists(pipe_path):
return os.path.getsize(pipe_path) == 0
else:
print(f"Pipe '{pipe_path}' does not exist.")
return True # Pipe does not exist or cannot be accessed
except Exception as e:
print(f"Error while checking pipe '{pipe_path}': {e}")
return True # Error occurred while checking the pipe
async def read_pipe(pipe: str, timeout: int=5) -> str:
"""
Reads text from a named pipe.
Automatically tests if the pipe is empty.
Args:
pipe (str): Path to the pipe
timeout (int, optional): Timeout in seconds. Defaults to 5.
Returns:
str: Data from the pipe or empty string if pipe is empty
"""
if pipe_is_empty(pipe):
return ""
try:
# timeout is not working!
async with async_timeout.timeout(timeout):
with open(pipe, 'r', encoding='utf-8') as f:
data = f.read()
return data
except FileNotFoundError:
print(f"Pipe '{pipe}' does not exist.")
except PermissionError:
print(f"No permission to read from pipe '{pipe}'.")
except asyncio.TimeoutError:
print("Opening the pipe took too long.")
except Exception as e:
if 'Bad file descriptor' in str(e):
print(f"Pipe '{pipe}' has been closed.")
else:
print(f"Error reading from pipe '{pipe}': {e}")
return ""
def create_pipe(pipe: str):
try:
os.mkfifo(pipe)
except FileExistsError:
pass
def split_message(message: str, max_length: int = 2000):
"""
Splits a message into multiple messages with max length of max_length
Args:
message (str): Message to split
max_length (int, optional): Max length of a message. Defaults to 2000.
Returns:
list: List of messages
"""
return [message[i:i+max_length] for i in range(0, len(message), max_length)]