/
builtin_functions.py
171 lines (146 loc) · 4.45 KB
/
builtin_functions.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import os
import sys
from datetime import datetime
from textwrap import dedent
from typing import Optional
from telethon.tl.custom import Message
from tgpy import app
from tgpy.message_design import get_code
from tgpy.modules import (
Module,
delete_module_file,
get_module_names,
get_sorted_modules,
)
from tgpy.utils import (
RunCmdException,
filename_prefix,
get_version,
installed_as_package,
run_cmd,
REPO_ROOT,
execute_in_repo_root,
get_user,
running_in_docker,
get_hostname,
)
def ping():
return dedent(
f'''
Pong!
Running on {get_user()}@{get_hostname()}
Version: {get_version()}
'''
)
def restart(msg: Optional[str] = 'Restarted successfully'):
mod_code = dedent(
f'''
from tgpy.message_design import edit_message, get_code
msg = await client.get_messages({app.ctx.msg.chat_id}, ids={app.ctx.msg.id})
await edit_message(msg, get_code(msg), '{msg}')
'''
)
module = Module(
name='__restart_message',
once=True,
save_locals=False,
code=mod_code,
origin=f'{filename_prefix}restart_message',
priority=0,
)
module.save()
os.execl(sys.executable, sys.executable, '-m', 'tgpy', *sys.argv[1:])
def update():
old_version = get_version()
if running_in_docker():
return 'Can\'t update a docker container'
if installed_as_package():
update_args = [sys.executable, '-m', 'pip', 'install', '-U', 'tgpy']
try:
run_cmd(update_args)
except RunCmdException:
run_cmd(update_args + ['--user'])
elif REPO_ROOT:
with execute_in_repo_root():
try:
run_cmd(['git', 'pull'])
except FileNotFoundError:
return 'Git is not installed'
else:
return 'Could not find suitable update method'
new_version = get_version()
if old_version == new_version:
return 'Already up to date'
else:
restart(f'Updated successfully! Current version: {new_version}')
class ModulesObject:
async def add(self, name: str, code: Optional[str] = None) -> str:
name = str(name)
if code is None:
original: Message = await app.ctx.msg.get_reply_message()
if original is None:
return 'Use this function in reply to a message'
code = get_code(original)
if not code:
return 'No code found in reply message'
origin = f'{filename_prefix}module/{name}'
if name in self:
module = self[name]
module.code = code
else:
module = Module(
name=name,
once=False,
save_locals=True,
code=code,
origin=origin,
priority=datetime.now().timestamp(),
)
module.save()
return dedent(
f'''
Added module {name!r}.
Module's code will be executed every time TGPy starts.
'''
)
def remove(self, name) -> str:
try:
delete_module_file(name)
except FileNotFoundError:
return f'No module named {name!r}.'
return f'Removed module {name!r}.'
def __str__(self):
lst = '\n'.join(
f'{idx + 1}. {mod.name}' for idx, mod in enumerate(get_sorted_modules())
)
if not lst:
return dedent(
'''
You have no modules.
Learn about modules at https://tgpy.tmat.me/modules.
'''
)
return dedent(
'''
Your modules:
{}
Change modules with `modules.add(name)` and `modules.remove(name)`.
Learn more at https://tgpy.tmat.me/modules.
'''
).format(lst)
def __iter__(self):
return (mod.name for mod in get_sorted_modules())
def __getitem__(self, mod_name):
return Module.load(mod_name)
def __contains__(self, mod_name):
return mod_name in get_module_names()
def add_builtin_functions():
variables = app.api.variables
variables['ping'] = ping
variables['restart'] = restart
variables['update'] = update
variables['modules'] = ModulesObject()
constants = app.api.constants
constants['tgpy'] = app.api
constants['ctx'] = app.ctx
constants['client'] = app.client