Añadido de nuevo helper para escapar caracteres para Telegram
This commit is contained in:
@@ -1 +1,13 @@
|
|||||||
[]
|
[
|
||||||
|
{
|
||||||
|
"product_name": "server",
|
||||||
|
"distance": "0",
|
||||||
|
"latitude": "42.1",
|
||||||
|
"longitude": "3.1",
|
||||||
|
"condition": "all",
|
||||||
|
"min_price": "0",
|
||||||
|
"max_price": "100",
|
||||||
|
"title_keyword_exclude": [],
|
||||||
|
"exclude": []
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -3,7 +3,7 @@ import os
|
|||||||
import threading
|
import threading
|
||||||
import logging
|
import logging
|
||||||
import prettytable
|
import prettytable
|
||||||
import telegram
|
import helpers
|
||||||
|
|
||||||
from worker import Worker
|
from worker import Worker
|
||||||
from telegram import Update
|
from telegram import Update
|
||||||
@@ -35,10 +35,10 @@ async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
|
|||||||
message = """Añade un producto con `/add producto;precio_mínimo;precio_máximo,excluir_título(opcional, separado por comas);excluir_descripción_y_título(opciona, separado por comas);latitud(opcional);longitud(opcional),distancia(opcional)`\n
|
message = """Añade un producto con `/add producto;precio_mínimo;precio_máximo,excluir_título(opcional, separado por comas);excluir_descripción_y_título(opciona, separado por comas);latitud(opcional);longitud(opcional),distancia(opcional)`\n
|
||||||
Ejemplo: `/add placa base itx;0;150`\n
|
Ejemplo: `/add placa base itx;0;150`\n
|
||||||
Ejemplo 2: `/add cpu;10;30;;intel,core 2 duo,celeron;;;100`\n
|
Ejemplo 2: `/add cpu;10;30;;intel,core 2 duo,celeron;;;100`\n
|
||||||
Los campos opcionales que se dejen vacíos tomarán el valor configurado en el archivo `\.env`\n
|
Los campos opcionales que se dejen vacíos tomarán el valor configurado en el archivo `.env`\n
|
||||||
Lista los productos con `/list` o obtén la información de uno en concreto con `/list nombre del producto`\n
|
Lista los productos con `/list` o obtén la información de uno en concreto con `/list nombre del producto`\n
|
||||||
Borra un producto con `/remove nombre del producto`"""
|
Borra un producto con `/remove nombre del producto`"""
|
||||||
await update.message.reply_markdown_v2(telegram.helpers.escape_markdown(message))
|
await update.message.reply_markdown_v2(helpers.telegram_escape_characters(message))
|
||||||
|
|
||||||
async def add_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
async def add_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
message = """Tienes que pasar el número correcto de parámetros: `/add producto;precio_mínimo;precio_máximo,excluir_título(opcional, separado por comas);excluir_descripción_y_título(opciona, separado por comas);latitud(opcional);longitud(opcional),distancia(opcional)`\n
|
message = """Tienes que pasar el número correcto de parámetros: `/add producto;precio_mínimo;precio_máximo,excluir_título(opcional, separado por comas);excluir_descripción_y_título(opciona, separado por comas);latitud(opcional);longitud(opcional),distancia(opcional)`\n
|
||||||
@@ -89,7 +89,7 @@ Los campos opcionales que se dejen vacíos tomarán el valor configurado en el a
|
|||||||
message = f"Añadido {product_name} a seguimiento"
|
message = f"Añadido {product_name} a seguimiento"
|
||||||
else:
|
else:
|
||||||
message = f"{product_name} ya está en seguimiento!"
|
message = f"{product_name} ya está en seguimiento!"
|
||||||
await update.message.reply_markdown_v2(telegram.helpers.escape_markdown(message))
|
await update.message.reply_markdown_v2(helpers.telegram_escape_characters(message))
|
||||||
|
|
||||||
async def remove_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
async def remove_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
product_to_remove = update.message.text[len('/remove '):]
|
product_to_remove = update.message.text[len('/remove '):]
|
||||||
@@ -123,8 +123,8 @@ async def list_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
|
|||||||
table.align['Mín'] = 'r'
|
table.align['Mín'] = 'r'
|
||||||
table.align['Máx'] = 'r'
|
table.align['Máx'] = 'r'
|
||||||
for product in products:
|
for product in products:
|
||||||
table.add_row([product['product_name'], f"{product['min_price']}€", f"{product['max_price']}€"])
|
table.add_row([helpers.telegram_escape_characters(product['product_name']), f"{helpers.telegram_escape_characters(product['min_price'])}€", f"{helpers.telegram_escape_characters(product['max_price'])}€"])
|
||||||
await update.message.reply_markdown_v2(f'```{telegram.helpers.escape_markdown(table)}```')
|
await update.message.reply_markdown_v2(f'```{(table)}```')
|
||||||
|
|
||||||
def main()->None:
|
def main()->None:
|
||||||
products = parse_json_file()
|
products = parse_json_file()
|
||||||
|
|||||||
6
wallamanta/helpers.py
Normal file
6
wallamanta/helpers.py
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
TELEGRAM_ESCAPE_CHARACTERS = ['_', '*', '[', ']', '(', ')', '~', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']
|
||||||
|
|
||||||
|
def telegram_escape_characters(text):
|
||||||
|
for character in TELEGRAM_ESCAPE_CHARACTERS:
|
||||||
|
text = text.replace(character, f'\{character}')
|
||||||
|
return text
|
||||||
@@ -4,6 +4,7 @@ import telegram
|
|||||||
import os
|
import os
|
||||||
import logging
|
import logging
|
||||||
import json
|
import json
|
||||||
|
import helpers
|
||||||
|
|
||||||
TELEGRAM_CHANNEL_ID = os.getenv("TELEGRAM_CHANNEL_ID")
|
TELEGRAM_CHANNEL_ID = os.getenv("TELEGRAM_CHANNEL_ID")
|
||||||
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
|
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
|
||||||
@@ -76,11 +77,11 @@ class Worker:
|
|||||||
if not self.has_excluded_words(article['title'].lower(), article['description'].lower(), product['exclude']) and not self.is_title_key_word_excluded(article['title'].lower(), product['title_keyword_exclude']):
|
if not self.has_excluded_words(article['title'].lower(), article['description'].lower(), product['exclude']) and not self.is_title_key_word_excluded(article['title'].lower(), product['title_keyword_exclude']):
|
||||||
try:
|
try:
|
||||||
text = f"*Artículo*: {article['title']}\n*Descripción*: {article['description']}\n*Precio*: {article['price']} {article['currency']}\n[Ir al anuncio](https://es.wallapop.com/item/{article['web_slug']})".replace(".", "\.")
|
text = f"*Artículo*: {article['title']}\n*Descripción*: {article['description']}\n*Precio*: {article['price']} {article['currency']}\n[Ir al anuncio](https://es.wallapop.com/item/{article['web_slug']})".replace(".", "\.")
|
||||||
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage?chat_id={TELEGRAM_CHANNEL_ID}&text={telegram.helpers.escape_markdown(text)}&parse_mode=MarkdownV2"
|
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage?chat_id={TELEGRAM_CHANNEL_ID}&text={helpers.telegram_escape_characters(text)}&parse_mode=MarkdownV2"
|
||||||
logging.info(requests.get(url).json())
|
logging.info(requests.get(url).json())
|
||||||
except:
|
except:
|
||||||
text = f"*Artículo*: {article['title']}\n*Descripción*: {article['description']}\n*Precio*: {article['price']} {article['currency']}\n[Ir al anuncio](https://es.wallapop.com/item/{article['web_slug']})".replace(".", "\.")
|
text = f"*Artículo*: {article['title']}\n*Descripción*: {article['description']}\n*Precio*: {article['price']} {article['currency']}\n[Ir al anuncio](https://es.wallapop.com/item/{article['web_slug']})".replace(".", "\.")
|
||||||
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage?chat_id={TELEGRAM_CHANNEL_ID}&text={telegram.helpers.escape_markdown(text)}&parse_mode=MarkdownV2"
|
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage?chat_id={TELEGRAM_CHANNEL_ID}&text={helpers.telegram_escape_characters(text)}&parse_mode=MarkdownV2"
|
||||||
requests.get(url)
|
requests.get(url)
|
||||||
time.sleep(1) # Avoid Telegram flood restriction
|
time.sleep(1) # Avoid Telegram flood restriction
|
||||||
list.insert(0, article['id'])
|
list.insert(0, article['id'])
|
||||||
|
|||||||
Reference in New Issue
Block a user