Skip to content

Commit

Permalink
Merge branch 'develop' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
chen-tf committed Aug 19, 2021
2 parents f88643d + 4eff44c commit ff85792
Show file tree
Hide file tree
Showing 11 changed files with 167 additions and 88 deletions.
2 changes: 1 addition & 1 deletion Procfile
Original file line number Diff line number Diff line change
@@ -1 +1 @@
web: python3 App.py
web: python3 app.py
18 changes: 9 additions & 9 deletions App.py → app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,24 @@

import schedule

import App
import Bot
import PTConfig
import Service
import app
import pt_bot
import pt_config
import pt_service

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=PTConfig.LOGGING_LEVEL, force=True)
level=pt_config.LOGGING_LEVEL, force=True)
logger = logging.getLogger('App')
if __name__ == '__main__':
t = threading.Thread(target=App.my_job)
t = threading.Thread(target=app.my_job)
t.start()
logger.debug('Momo price tracker bot started.')
Bot.run()
pt_bot.run()


def my_job():
Service.sync_price()
schedule.every(PTConfig.PERIOD_HOUR).hours.do(Service.sync_price)
schedule.every(pt_config.PERIOD_HOUR).hours.do(pt_service.sync_price)
schedule.every(pt_config.PERIOD_HOUR).hours.do(pt_service.disable_not_active_user_sub_good)
while True:
schedule.run_pending()
time.sleep(2)
67 changes: 41 additions & 26 deletions Bot.py → pt_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,36 @@

import requests
import telegram
from telegram import ChatAction
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

import PTConfig
import PTError
import Service
from Entity import UserGoodInfo, GoodInfo
from Service import get_good_info, add_good_info, add_user_good_info, upsert_user
import pt_config
import pt_error
import pt_service
from pt_entity import UserGoodInfo, GoodInfo
from pt_service import get_good_info, add_good_info, add_user_good_info, upsert_user

updater = Updater(token=PTConfig.BOT_TOKEN, use_context=True)
updater = Updater(token=pt_config.BOT_TOKEN, use_context=True)
dispatcher = updater.dispatcher
bot = telegram.Bot(token=PTConfig.BOT_TOKEN)
bot = telegram.Bot(token=pt_config.BOT_TOKEN)
logger = logging.getLogger('Bot')


def run():
bot_dispatcher = None
if PTConfig.TELEGRAM_BOT_MODE == 'polling':
bot_updater = Updater(token=PTConfig.BOT_TOKEN, use_context=True)
if pt_config.TELEGRAM_BOT_MODE == 'polling':
bot_updater = Updater(token=pt_config.BOT_TOKEN, use_context=True)
bot_dispatcher = bot_updater.dispatcher
bot_updater.start_polling()
else:
import os
port = int(os.environ.get('PORT', '8443'))
bot_updater = Updater(PTConfig.BOT_TOKEN)
bot_updater = Updater(pt_config.BOT_TOKEN)

bot_updater.start_webhook(listen="0.0.0.0",
port=port,
url_path=PTConfig.BOT_TOKEN,
webhook_url=PTConfig.WEBHOOK_URL + PTConfig.BOT_TOKEN)
url_path=pt_config.BOT_TOKEN,
webhook_url=pt_config.WEBHOOK_URL + pt_config.BOT_TOKEN)
bot_dispatcher = bot_updater.dispatcher

# add handlers
Expand Down Expand Up @@ -68,17 +69,17 @@ def auto_add_good(update, context):
url = update.message.text
if 'https://momo.dm' in url:
match = re.search('https.*momo.dm.*', url)
response = requests.request("GET", match.group(0), headers={'user-agent': PTConfig.USER_AGENT},
timeout=PTConfig.MOMO_REQUEST_TIMEOUT)
response = requests.request("GET", match.group(0), headers={'user-agent': pt_config.USER_AGENT},
timeout=pt_config.MOMO_REQUEST_TIMEOUT)
url = response.url
r = urlparse(url)
d = parse_qs(r.query)
if 'i_code' not in d or len(d['i_code']) < 1:
raise PTError.NotValidMomoURL
raise pt_error.NotValidMomoURL

# Check the number of user sub goods
if Service.count_user_good_info_sum(user_id) >= PTConfig.USER_SUB_GOOD_LIMITED:
raise PTError.ExceedLimitedSizeError
if pt_service.count_user_good_info_sum(user_id) >= pt_config.USER_SUB_GOOD_LIMITED:
raise pt_error.ExceedLimitedSizeError

good_id = str(d['i_code'][0])
good_info = get_good_info(good_id=good_id)
Expand All @@ -91,13 +92,13 @@ def auto_add_good(update, context):
add_user_good_info(user_good_info)
msg = '成功新增\n商品名稱:%s\n價格:%s\n狀態:%s' % (good_info.name, good_info.price, stock_state_string)
context.bot.send_message(chat_id=update.effective_chat.id, text=msg)
except PTError.GoodNotExist:
except pt_error.GoodNotExist:
context.bot.send_message(chat_id=update.effective_chat.id, text='商品目前無展售或是網頁不存在')
except PTError.CrawlerParseError:
except pt_error.CrawlerParseError:
context.bot.send_message(chat_id=update.effective_chat.id, text='商品頁面解析失敗')
except PTError.ExceedLimitedSizeError:
context.bot.send_message(chat_id=update.effective_chat.id, text='追蹤物品已達%s件' % PTConfig.USER_SUB_GOOD_LIMITED)
except PTError.NotValidMomoURL:
except pt_error.ExceedLimitedSizeError:
context.bot.send_message(chat_id=update.effective_chat.id, text='追蹤物品已達%s件' % pt_config.USER_SUB_GOOD_LIMITED)
except pt_error.NotValidMomoURL:
context.bot.send_message(chat_id=update.effective_chat.id, text='無效momo商品連結')
except Exception as e:
logger.error("Catch an exception.", exc_info=True)
Expand All @@ -106,7 +107,7 @@ def auto_add_good(update, context):

def my(update, context):
user_id = str(update.message.from_user.id)
my_goods = Service.find_user_sub_goods(user_id)
my_goods = pt_service.find_user_sub_goods(user_id)
if len(my_goods) == 0:
context.bot.send_message(chat_id=update.effective_chat.id, text='尚未追蹤商品')
return
Expand All @@ -121,16 +122,30 @@ def my(update, context):
stock_state_string = '商品目前無展售或是網頁不存在'
my_good[2] = stock_state_string
good_id = my_good[3]
my_good[3] = Service.generate_momo_url_by_good_id(good_id)
my_good[3] = pt_service.generate_momo_url_by_good_id(good_id)
msgs = msgs + (msg % tuple(my_good))
context.bot.send_message(chat_id=update.effective_chat.id, text=msgs)


def clear(update, context):
user_id = str(update.message.from_user.id)
Service.clear(user_id)
pt_service.clear(user_id)
context.bot.send_message(chat_id=update.effective_chat.id, text='已清空追蹤清單')


def send(msg, chat_id):
bot.sendMessage(chat_id=chat_id, text=msg)
if is_blocked_by_user(chat_id):
return
try:
bot.sendMessage(chat_id=chat_id, text=msg)
except:
logger.error('Send message and catch the exception.', exc_info=True)


def is_blocked_by_user(chat_id):
try:
bot.send_chat_action(chat_id=str(chat_id), action=ChatAction.TYPING)
except telegram.error.Unauthorized as e:
if e.message == 'Forbidden: bot was blocked by the user':
return True
return False
File renamed without changes.
6 changes: 3 additions & 3 deletions DataSource.py → pt_datasource.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
import psycopg2.extras
from psycopg2.pool import ThreadedConnectionPool

import PTConfig
import pt_config

psycopg2.extras.register_uuid()
pool = ThreadedConnectionPool(2, 10, host=PTConfig.DB_HOST, database=PTConfig.DB_NAME, user=PTConfig.DB_USER,
password=PTConfig.DB_PASSWORD)
pool = ThreadedConnectionPool(2, 10, host=pt_config.DB_HOST, database=pt_config.DB_NAME, user=pt_config.DB_USER,
password=pt_config.DB_PASSWORD)
logging.info("Connection Pool established")


Expand Down
7 changes: 7 additions & 0 deletions Entity.py → pt_entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,31 @@ class UserGoodInfo:
good_id: str
original_price: int
is_notified: bool
STATE_DISABLE = 0
STATE_ENABLE = 1

def __init__(self, user_id: str, chat_id: str, good_id: str, original_price: int, is_notified: bool) -> None:
self.user_id = user_id
self.chat_id = chat_id
self.good_id = good_id
self.original_price = original_price
self.is_notified = is_notified
self.state = 1


class GoodInfo:
STOCK_STATE_OUT_OF_STOCK = 0
STOCK_STATE_IN_STOCK = 1
STOCK_STATE_NOT_EXIST = 2
STATE_DISABLE = 0
STATE_ENABLE = 1

good_id: str
price: int
name: str
checksum: str
stock_state: int
state: int

def __init__(self, good_id: str, price: int, name: str, checksum: str, stock_state: int) -> None:
self.good_id = good_id
Expand All @@ -33,3 +39,4 @@ def __init__(self, good_id: str, price: int, name: str, checksum: str, stock_sta
self.stock_state = 1
else:
self.stock_state = stock_state
self.state = 1
File renamed without changes.
Loading

0 comments on commit ff85792

Please sign in to comment.