2018-05-25 00:38:27 +00:00
|
|
|
from bot import Bot
|
|
|
|
import logging
|
|
|
|
from report import Report
|
2018-05-29 05:07:15 +00:00
|
|
|
from twx.botapi import TelegramBot as Telegram
|
2018-05-25 00:38:27 +00:00
|
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class TelegramBot(Bot):
|
|
|
|
def crawl(self, user):
|
2018-05-29 05:07:15 +00:00
|
|
|
tb = Telegram(user.get_telegram_credentials())
|
2018-09-09 15:22:00 +00:00
|
|
|
seen_tg = user.get_seen_tg()
|
|
|
|
updates = tb.get_updates(offset=seen_tg+1).wait()
|
2018-05-25 00:38:27 +00:00
|
|
|
reports = []
|
|
|
|
for update in updates:
|
2018-09-09 14:58:07 +00:00
|
|
|
try:
|
|
|
|
if update.message.text.lower() == "/start":
|
|
|
|
user.add_telegram_subscribers(update.message.sender.id)
|
|
|
|
tb.send_message(update.message.sender.id, "You are now subscribed to report notifications.")
|
|
|
|
# TODO: /start message should be set in frontend
|
|
|
|
elif update.message.text.lower() == "/stop":
|
|
|
|
user.remove_telegram_subscribers(update.message.sender.id)
|
|
|
|
tb.send_message(update.message.sender.id, "You are now unsubscribed from report notifications.")
|
|
|
|
# TODO: /stop message should be set in frontend
|
|
|
|
elif update.message.text.lower() == "/help":
|
|
|
|
tb.send_message(update.message.sender.id, "Send reports here to share them with other users. Use /start and /stop to be included/excluded.")
|
|
|
|
# TODO: /help message should be set in frontend
|
|
|
|
else:
|
|
|
|
reports.append(Report(update.message.sender.username, self,
|
|
|
|
update.message.text, None, update.message.date))
|
2018-09-09 15:22:00 +00:00
|
|
|
user.save_seen_tg(update.message.id)
|
2018-09-09 14:58:07 +00:00
|
|
|
except AttributeError:
|
|
|
|
print(updates[0], updates[1]) # Telegram API returns an Error
|
|
|
|
return reports
|
2018-05-25 00:38:27 +00:00
|
|
|
return reports
|
|
|
|
|
|
|
|
def post(self, user, report):
|
2018-05-29 05:07:15 +00:00
|
|
|
tb = Telegram(user.get_telegram_credentials())
|
2018-05-25 00:38:27 +00:00
|
|
|
text = report.text
|
|
|
|
if len(text) > 4096:
|
|
|
|
text = text[:4096 - 4] + u' ...'
|
|
|
|
try:
|
|
|
|
for subscriber_id in user.get_telegram_subscribers():
|
|
|
|
tb.send_message(subscriber_id, text).wait()
|
|
|
|
except Exception:
|
|
|
|
logger.error('Error telegramming: ' + user.get_city() + ': '
|
|
|
|
+ report.id, exc_info=True)
|