telegram_bots/feeds/tasks.py

51 lines
1.4 KiB
Python
Raw Normal View History

2019-03-14 07:17:08 +00:00
import traceback
2019-03-10 07:11:59 +00:00
import sentry_sdk
2019-01-26 09:36:44 +00:00
from celery_once import QueueOnce
2019-01-11 19:16:01 +00:00
from django.utils import timezone
2019-11-24 14:07:19 +00:00
from django.core.cache import cache
2019-01-19 06:52:00 +00:00
from djconfig import config
2021-03-20 13:21:13 +00:00
from telegram import Bot
2019-01-11 19:16:01 +00:00
from config.celery import app
2019-01-26 09:36:44 +00:00
2019-01-26 09:43:15 +00:00
@app.task(base=QueueOnce, once={'graceful': True})
2019-01-26 09:36:44 +00:00
def check_feeds():
2019-01-26 09:38:13 +00:00
from feeds.models import Feed
2019-11-24 14:07:19 +00:00
feeds = Feed.objects.all()
2019-03-14 06:53:06 +00:00
enqueued = []
2019-01-26 09:36:44 +00:00
for feed in feeds:
2019-03-14 06:53:06 +00:00
if feed.run_check():
enqueued.append(str(feed))
return f'Following tasks were enqueued: {enqueued}'
2019-01-11 19:16:01 +00:00
@app.task()
def execute_feed(feed_pk):
from feeds.models import Feed
2019-01-25 16:33:22 +00:00
2019-01-25 16:33:54 +00:00
config._reload_maybe()
2019-01-11 19:16:01 +00:00
2019-04-10 23:07:37 +00:00
feed = Feed.objects.get(pk=feed_pk)
with sentry_sdk.configure_scope() as scope:
2019-04-10 23:16:33 +00:00
scope.set_tag('feed', str(feed))
2019-04-10 23:07:37 +00:00
try:
2021-03-20 13:21:13 +00:00
bot = Bot(config.feed_bot_token)
2019-04-10 23:07:37 +00:00
print(f'Last ID for "{feed}" = "{feed.last_id}"')
for last_id in feed.config.execute(bot, feed.chat_id, feed.last_id):
if last_id:
feed.last_id = last_id
feed.save()
print(f'Saved last ID for "{feed}" = "{feed.last_id}"')
feed.last_check = timezone.now()
2019-02-04 09:15:53 +00:00
feed.save()
2019-04-10 23:07:37 +00:00
except Exception as e:
sentry_sdk.capture_exception(e)
traceback.print_exc()
finally:
if feed:
2019-11-24 14:07:19 +00:00
cache.delete(feed.lock_key)