Skip to content

Commit be37281

Browse files
authored
Merge pull request #41 from misanram/Nueva-opción-setup
Nueva opción setup
2 parents 9bc8fdb + e8c841f commit be37281

8 files changed

Lines changed: 96 additions & 77 deletions

File tree

.gitignore

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
bot.log
21
.atico/
3-
.env
2+
bot.log
3+
.env

.travis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,4 @@ install:
1111
- pipenv install -d
1212
script:
1313
- pytest
14-
- flake8
14+
- flake8

README.md

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,29 +19,39 @@ $ source ./bin/activate
1919
$ ./bin/pip install git+https://github.com/misanram/pydeckard.git@Instalar-desde-GitHub
2020
~~~
2121

22-
A developer needs to install a few more packages:
22+
As a developer, you must install it in this other way:
2323

2424
~~~console
2525
$ ./bin/pip install git+https://github.com/misanram/pydeckard.git@Instalar-desde-GitHub[dev]
2626
~~~
2727

28-
Next step is to set your bot token for development:
28+
After installation, the next step is to create the .env configuration file and
29+
the file for automatic program startup.
2930

30-
~~~console
31-
$ echo 'TELEGRAM_BOT_TOKEN = "<token of your dev bot>"' > .env
32-
~~~
31+
During the process, you will be asked to enter your Telegram token and
32+
will be prompted with other configuration-related questions. The only required
33+
item is the Telegram token.
3334

34-
Now you can launch the bot with:
35+
To do this, activate the virtual environment and run:
3536

3637
~~~console
37-
$ python3 bot.py
38+
$ pydeckard --setup
3839
~~~
3940

40-
~~~systemd
41+
You can now launch the bot, activating the virtual environment and running::
4142

43+
~~~console
44+
$ pydeckard
45+
~~~
4246

47+
.. or delegate the startup of the application to your operating system
48+
using the instructions that setup has provided.
4349

50+
You can view the bot log using:
4451

52+
~~~console
53+
$ journalctl -u pydeckard.service -f systemd
54+
~~~
4555

4656
You can use the flag `--verbose` (or `-v') to get more information in the console:
4757

@@ -56,4 +66,4 @@ Use pytest:
5666

5767
~~~console
5868
$ python3 -m pytest
59-
~~~
69+
~~~

pydeckard/bot.py

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
11
#!/usr/bin/enb python3
2+
23
from datetime import datetime as DateTime
34
import itertools
45
import argparse
56
import logging
67
import sys
78
import time
9+
from logging.handlers import RotatingFileHandler
810

911
import telegram
1012
from telegram import Update
1113
from telegram.ext import ApplicationBuilder, filters, MessageHandler, CommandHandler, ContextTypes
1214
from telegram.constants import ParseMode
1315

14-
15-
from pydeckard import utils
1616
from pydeckard import config
17+
from pydeckard import utils
1718

1819

1920
class DeckardBot():
@@ -27,33 +28,29 @@ def get_options(self):
2728
parser = argparse.ArgumentParser(
2829
prog='bot',
2930
description='PyDeckard Bot',
30-
epilog='Text at the bottom of help',
31+
epilog='',
3132
)
3233
parser.add_argument('--setup', action='store_true', help='Start the setup wizard')
3334
args = parser.parse_args()
3435
if args.setup:
3536
utils.setup_bot()
3637

37-
3838
def set_logger(self):
39-
self.logger = logging.getLogger('bot')
40-
39+
self.logger = logging.getLogger('pydeckard')
4140
console_handler = logging.StreamHandler()
4241
logging.basicConfig(
43-
level=logging.DEBUG, # Pone el nivel de todos los logger a WARNING
44-
format='%(asctime)s [%(name)s] %(levelname)s: %(message)s',
45-
handlers=[console_handler],
46-
force=True
47-
)
48-
42+
level=logging.WARNING, # Pone el nivel de todos los logger a WARNING
43+
format='%(asctime)s [%(name)s] %(levelname)s: %(message)s',
44+
handlers=[console_handler],
45+
force=True,
46+
)
4947
# Ajustamos el nivel del logger bot
5048
self.logger.setLevel(config.LOG_LEVEL)
5149
config.log(self.logger.info)
5250

5351
def trace(self, msg):
5452
self.logger.info(msg)
5553

56-
5754
async def command_status(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
5855
self.trace('Received command: /status')
5956
python_version = sys.version.split(maxsplit=1)[0]
@@ -136,8 +133,10 @@ async def welcome(self, update: Update, context):
136133
"-> It could be kindly removed 🗑"
137134
else:
138135
if utils.is_bot(new_member):
139-
await context.bot.delete_message(update.message.chat_id,
140-
update.message.message_id)
136+
await context.bot.delete_message(
137+
update.message.chat_id,
138+
update.message.message_id,
139+
)
141140
if await context.bot.kick_chat_member(update.message.chat_id, new_member.id):
142141
msg = (f"*{new_member.username}* has been banned because I "
143142
"considered it was a bot. ")
@@ -186,8 +185,13 @@ def run(self):
186185

187186

188187
def main():
188+
"""
189+
Arranca el bot
190+
"""
191+
189192
bot = DeckardBot()
190193
bot.run()
191194

195+
192196
if __name__ == "__main__":
193-
main()
197+
main()

pydeckard/config.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ def bot_replies_enabled() -> bool:
103103
("elixir",): "BIBA ELICSÍR!! ¥",
104104
("cobol",): "BIBA KOBOL!! 💾",
105105
("fortran",): "BIBA FORRRTRÁN!! √",
106-
(r"c\+\+",): "BIBA CEMASMÁS!! ⊕",
106+
("c++",): "BIBA CEMASMÁS!! ⊕",
107107
("javascript",): "BIBA JABAESCRIP!! 🔮",
108108
("php",): "BIBA PEACHEPÉ!.! ⛱",
109109
("perl",): "BIBA PERRRRRL! 🐫",
@@ -121,3 +121,7 @@ def bot_replies_enabled() -> bool:
121121
"tiempo... como lágrimas en la lluvia. Es hora de morir. 🔫",
122122
("python", "pitón", "piton"): THE_ZEN_OF_PYTHON,
123123
}
124+
125+
MAXLEN_FOR_USERNAME_TO_TREAT_AS_HUMAN = 100
126+
127+
CHINESE_CHARS_MAX_PERCENT = 0.15

pydeckard/utils.py

Lines changed: 44 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -45,25 +45,23 @@ def is_tgmember_sect(first_name: str):
4545
return "tgmember.com" in first_name.lower()
4646

4747

48-
def is_bot(user: User):
48+
def is_bot(user: User) -> bool:
4949
"""
5050
Returns True if a new user is a bot. So far only the length of the
5151
username is checked. In the future, we can add more conditions and use a
5252
score/weight of the probability of being a bot.
5353
5454
:param user: The new User
55-
:typus user: User
55+
:type user: User
5656
:return: True if the new user is considered a bot (according to our rules)
5757
:rtype: bool
5858
"""
5959
# Add all the checks that you consider necessary
60-
return any(
61-
(
62-
not is_valid_name(user),
63-
too_much_chinese_chars(user.first_name),
64-
is_tgmember_sect(user.first_name),
65-
)
66-
)
60+
return any([
61+
not is_valid_name(user),
62+
too_much_chinese_chars(user.first_name),
63+
is_tgmember_sect(user.first_name),
64+
])
6765

6866

6967
@functools.lru_cache()
@@ -210,22 +208,21 @@ def setup_bot():
210208

211209
root_path = Path(sys.prefix)
212210
bin_path = Path(sys.executable).parent
213-
bot_executable = bin_path / 'bot'
211+
bot_executable = bin_path / 'pydeckard'
214212
env_path = root_path / '.env'
215213
system_name = platform.system()
216214

217215
print(f'\n--- Asistente de configuración para PyDeckard (SO: {system_name}) ---\n\n')
218216

219-
parameters = [('TELEGRAM_BOT_TOKEN', 'Introduzca el Token del Bot', None, str),
220-
('VERBOSITY', 'Nivel de verbosidad', (0.0, 1.0), float),
221-
('LOG_LEVEL', 'Nivel de registro de logs', ['DEBUG', 'INFO', 'WARNING', 'ERROR'], str),
222-
('POLL_INTERVAL', 'Intervalo de polling para la API de Telegram', (1, 10), int),
223-
('BOT_GREETING', 'Saludo del bot', None, str),
224-
('MAX_HUMAN_USERNAME_LENGTH', 'Longitud máxima del username', None, int),
225-
('MAX_CHINESE_CHARS_PERCENT', 'Máximo porcentaje de caracteres chinos en username', (0.0,
226-
1.0), float),
227-
('WELCOME_DELAY', 'Tiempo de retardo para la bienvenida (seg)', None, int),
228-
]
217+
parameters = [
218+
('TELEGRAM_BOT_TOKEN', 'Introduzca el Token del Bot', None, str),
219+
('LOG_LEVEL', 'Nivel de registro de logs', ['DEBUG', 'INFO', 'WARNING', 'ERROR'], str),
220+
('POLL_INTERVAL', 'Intervalo de polling para la API de Telegram', (1, 10), int),
221+
('BOT_GREETING', 'Saludo del bot', None, str),
222+
('MAX_HUMAN_USERNAME_LENGTH', 'Longitud máxima del username', None, int),
223+
('MAX_CHINESE_CHARS_PERCENT', 'Máximo porcentaje de caracteres chinos en username', (0.0, 1.0), float),
224+
('WELCOME_DELAY', 'Tiempo de retardo para la bienvenida (seg)', None, int),
225+
]
229226

230227
try:
231228
items_env = {key: validate_input(*args) for key, *args in parameters}
@@ -248,41 +245,47 @@ def setup_bot():
248245
service_path = root_path / 'pydeckard.service'
249246

250247
service_content = f"""[Unit]
251-
Description=PyDeckard
252-
After=network.target
253-
254-
[Service]
255-
Type=simple
256-
User={user_name}
257-
Group={group_name}
258-
WorkingDirectory={root_path}
259-
ExecStart={bot_executable}
260-
Environment=PYTHONUNBUFFERED=1
261-
Restart=always
262-
263-
[Install]
264-
WantedBy=multi-user.target
265-
Alias=PyDeckard.service
266-
"""
267-
248+
Description=PyDeckard
249+
After=network.target
250+
251+
[Service]
252+
Type=simple
253+
User={user_name}
254+
Group={group_name}
255+
WorkingDirectory={root_path}
256+
ExecStart={bot_executable}
257+
Environment=PYTHONUNBUFFERED=1
258+
Restart=always
259+
260+
[Install]
261+
WantedBy=multi-user.target
262+
Alias=PyDeckard.service
263+
"""
268264
with open(service_path, 'w') as f:
269265
f.write(service_content)
270266

271267
print(f'\nArchivo pydeckard.service creado en {root_path}')
268+
print(f'\nPara configurar, activar e iniciar el service en systemd ejecute los siguientes comandos:')
269+
272270
print(f'\nsudo cp {service_path} /etc/systemd/system/')
273271
print('sudo systemctl daemon-reload')
274272
print('sudo systemctl enable --now pydeckard')
275-
276273
sys.exit(0)
277274

278275
elif system_name == 'Darwin':
279-
print('Entorno macOS detectado, configuración realizada, pregúntele a Apple® como arrancarlo.')
276+
print(
277+
'Entorno macOS detectado, configuración realizada, pregúntele'
278+
' a Apple® como arrancarlo.'
279+
)
280280
sys.exit(1)
281281

282282
elif system_name == 'Windows':
283-
print('Entorno Windows detectado, configuración realizada, pregúntele a Microsoft® como arrancarlo.')
283+
print(
284+
'Entorno Windows detectado, configuración realizada, pregúntele
285+
' a Microsoft® como arrancarlo.'
286+
)
284287
sys.exit(1)
285288

286289
elif system_name == 'Java':
287290
print('Entorno Jython detectado. Usted mismo.')
288-
sys.exit(1)
291+
sys.exit(1)

pyproject.toml

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,8 @@ include = ["pydeckard*"]
3636
where = ["."]
3737

3838
[project.scripts]
39-
bot = "pydeckard.bot:main"
40-
39+
pydeckard = "pydeckard.bot:main"
4140

4241
[tool.ruff]
4342
line-length = 120
44-
target-version = "py312"
45-
43+
target-version = "py312"

test/test_utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def test_tipo_int4(monkeypatch):
137137

138138
assert validate_input('Dato', None, int) == 3
139139

140-
def test_tipo_int5(monkeypatch):
140+
def test_tipo_int5(monkeypatch):
141141
# Separador _
142142
monkeypatch.setattr('builtins.input', lambda _: '1_000_000')
143143

@@ -157,13 +157,13 @@ def test_tipo_int7(monkeypatch):
157157

158158
assert validate_input('Dato', None, int) == 10
159159

160-
def test_tipo_int8(monkeypatch):
160+
def test_tipo_int8(monkeypatch):
161161
# Hexadecimal con espacios
162162
monkeypatch.setattr('builtins.input', lambda _: ' 0xff ')
163163

164164
assert validate_input('Dato', None, int) == 255
165165

166-
166+
167167
def test_tipo_int15(monkeypatch, capsys):
168168
# Float
169169
entradas = iter(['1.0', '1'])

0 commit comments

Comments
 (0)