Skip to content

Commit

Permalink
dev env
Browse files Browse the repository at this point in the history
  • Loading branch information
Fernando Ocaña authored and Fernando Ocaña committed Jun 17, 2021
1 parent 49995a8 commit 2f4591c
Show file tree
Hide file tree
Showing 10 changed files with 47 additions and 62 deletions.
7 changes: 4 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.idea/workspace.xml
.idea/shelf/
db.sqlite
__pycache__
.idea/
venv/
db.sqlite
*.log
6 changes: 0 additions & 6 deletions .idea/inspectionProfiles/profiles_settings.xml

This file was deleted.

4 changes: 0 additions & 4 deletions .idea/misc.xml

This file was deleted.

8 changes: 0 additions & 8 deletions .idea/modules.xml

This file was deleted.

6 changes: 0 additions & 6 deletions .idea/vcs.xml

This file was deleted.

10 changes: 0 additions & 10 deletions .idea/wallbot.iml

This file was deleted.

8 changes: 4 additions & 4 deletions TODO.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
- [x] Definir dependencias
- [ ] Probar dependencias
- [x] Probar dependencias
- [x] Externalizar TOKEN
- [ ] Preparar directorio /data
- [ ] Logging
- [ ] Docker
- [x] Preparar directorio /data
- [x] Logging /log
- [x] Docker
2 changes: 1 addition & 1 deletion dbhelper.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def __init__(self, item_id, chat_id, title, price, url, publish_date, observacio


class DBHelper:
def __init__(self, dbname="db.sqlite"):
def __init__(self, dbname="/data/db.sqlite"):
self.dbname = dbname
self.conn = sqlite3.connect(dbname, check_same_thread=False)

Expand Down
File renamed without changes.
58 changes: 38 additions & 20 deletions ssbo.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,22 @@
from re import sub
from decimal import Decimal
import logging
from logging.handlers import RotatingFileHandler
import sys
import threading
import os
import locale

TOKEN = os.getenv("BOT_TOKEN", "Bot Token does not exist")
URL = "https://api.telegram.org/bot{}/".format(TOKEN)
URL_ITEMS = "https://api.wallapop.com/api/v3/general/search"
PROFILE = os.getenv("PROFILE")

if PROFILE is None:
db = DBHelper()
else:
db = DBHelper("db.sqlite")

db = DBHelper()

ICON_VIDEO_GAMES = u'\U0001F3AE' # 🎮
ICON_WARNING____ = u'\U000026A0' # ⚠️
Expand All @@ -36,7 +43,7 @@ def notel(chat_id, price, title, url_item, obs=None):
text += '\n'
if obs is not None:
text += ICON_COLLISION__ + ' '
text += price
text += locale.currency(price, grouping=True)
if obs is not None:
text += obs
text += ' ' + ICON_COLLISION__
Expand Down Expand Up @@ -78,15 +85,15 @@ def get_items(url, chat_id):
data = resp.json()
# print(data)
for x in data['search_objects']:
print(x)
print('\t'.join((datetime.datetime.today().strftime('%Y-%m-%d %H:%M'),
str(x['id']), str(x['price']), x['title'], x['user']['id'])))
# print('\t'.join((datetime.datetime.today().strftime('%Y-%m-%d %H:%M'),
# str(x['id']), str(x['price']), x['title'], x['user']['id'])))
# logging.info('\t'.join((str(x['id']), str(x['price']), x['title'], x['user']['id'])))
logging.info('Encontrado: id=%s, price=%s, title=%s, user=%s',str(x['id']), locale.currency(x['price'], grouping=True), x['title'], x['user']['id'])
i = db.search_item(x['id'], chat_id)
if i is None:
db.add_item(x['id'], chat_id, x['title'], x['price'], x['web_slug'], x['user']['id'])
notel(chat_id, str(x['price']), x['title'], x['web_slug'])
print('\t'.join((datetime.datetime.today().strftime('%Y-%m-%d %H:%M'),
'NEW ', str(x['id']), str(x['price']), x['title'])))
notel(chat_id, x['price'], x['title'], x['web_slug'])
logging.info('New: id=%s, price=%s, title=%s', str(x['id']), locale.currency(x['price'], grouping=True), x['title'])
else:
# Si está comparar precio...
money = str(x['price'])
Expand All @@ -100,10 +107,9 @@ def get_items(url, chat_id):
db.update_item(x['id'], money, new_obs)
obs = ' < ' + new_obs
notel(chat_id, x['price'], x['title'], x['web_slug'], obs)
print('\t'.join((datetime.datetime.today().strftime('%Y-%m-%d %H:%M'),
'BAJA', str(x['id']), x['price'], x['title'])))
logging.info('Baja: id=%s, price=%s, title=%s', str(x['id']), locale.currency(x['price'], grouping=True), x['title'])
except Exception as e:
print(e)
logging.error(e)


# INI Actualización de db a partir de la librería de Telegram
Expand Down Expand Up @@ -180,7 +186,7 @@ def add_search(message):
cs.username = message.from_user.username
cs.name = message.from_user.first_name
cs.active = 1
print(cs)
logging.info('%s', cs)
db.add_search(cs)


Expand All @@ -189,13 +195,25 @@ def add_search(message):
# print('echo: "' + message.text + '"')
# bot.reply_to(message, message.text)

logger = telebot.logger
formatter = logging.Formatter('[%(asctime)s] %(thread)d {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s',
'%m-%d %H:%M:%S')
ch = logging.StreamHandler(sys.stdout)
logger.addHandler(ch)
logger.setLevel(logging.ERROR) # or use logging.INFO
ch.setFormatter(formatter)
pathlog = 'wallbot.log'
if PROFILE is None:
pathlog = '/logs/' + pathlog

logging.basicConfig(
handlers=[RotatingFileHandler(pathlog, maxBytes=1000000, backupCount=10)],
# filename='wallbot.log',
level=logging.INFO,
format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %H:%M:%S')

locale.setlocale(locale.LC_ALL, 'es_ES.UTF-8')

#logger = telebot.logger
#formatter = logging.Formatter('[%(asctime)s] %(thread)d {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s',
# '%m-%d %H:%M:%S')
#ch = logging.StreamHandler(sys.stdout)
#logger.addHandler(ch)
#logger.setLevel(logging.INFO) # or use logging.INFO
#ch.setFormatter(formatter)


# FIN
Expand Down Expand Up @@ -230,13 +248,13 @@ def wallapop():

def main():
print("JanJanJan starting...")
logging.info("JanJanJan starting...")
db.setup()

threading.Thread(target=wallapop).start()

# recovery(1)
bot.polling(none_stop=True, timeout=3000)


if __name__ == '__main__':
main()

0 comments on commit 2f4591c

Please sign in to comment.