robosats/api/management/commands/telegram_watcher.py

67 lines
2.3 KiB
Python
Raw Normal View History

2022-10-25 18:04:12 +00:00
import time
from decouple import config
from django.core.management.base import BaseCommand
from api.messages import Telegram
2022-10-25 18:04:12 +00:00
from api.models import Profile
2022-08-08 15:58:06 +00:00
from api.utils import get_session
2022-10-20 09:56:10 +00:00
class Command(BaseCommand):
help = "Polls telegram /getUpdates method"
2022-10-20 09:56:10 +00:00
rest = 3 # seconds between consecutive polls
2022-10-20 09:56:10 +00:00
bot_token = config("TELEGRAM_TOKEN")
updates_url = f"https://api.telegram.org/bot{bot_token}/getUpdates"
2022-08-08 15:58:06 +00:00
session = get_session()
telegram = Telegram()
2022-10-20 09:56:10 +00:00
def handle(self, *args, **options):
"""Infinite loop to check for telegram updates.
If it finds a new user (/start), enables it's taker found
notification and sends a 'Hey {username} {order_id}' message back"""
2022-10-20 09:56:10 +00:00
offset = 0
while True:
time.sleep(self.rest)
2022-10-20 09:56:10 +00:00
params = {"offset": offset + 1, "timeout": 5}
response = self.session.get(self.updates_url, params=params).json()
2022-10-20 09:56:10 +00:00
if len(list(response["result"])) == 0:
continue
2022-10-20 09:56:10 +00:00
for result in response["result"]:
2022-10-20 09:56:10 +00:00
try: # if there is no key message, skips this result.
text = result["message"]["text"]
except Exception:
continue
2022-10-20 09:56:10 +00:00
splitted_text = text.split(" ")
if splitted_text[0] == "/start":
token = splitted_text[-1]
2022-10-20 09:56:10 +00:00
try:
profile = Profile.objects.get(telegram_token=token)
except Exception:
2022-10-20 09:56:10 +00:00
print(f"No profile with token {token}")
continue
2022-10-20 09:56:10 +00:00
2022-03-18 21:21:13 +00:00
attempts = 5
while attempts >= 0:
try:
2022-10-20 09:56:10 +00:00
profile.telegram_chat_id = result["message"]["from"]["id"]
profile.telegram_lang_code = result["message"]["from"][
"language_code"
]
2022-03-18 21:21:13 +00:00
self.telegram.welcome(profile.user)
profile.telegram_enabled = True
profile.save()
2022-03-26 15:23:34 +00:00
break
except Exception:
2022-03-26 15:23:34 +00:00
time.sleep(5)
2022-03-18 21:21:13 +00:00
attempts = attempts - 1
2022-10-20 09:56:10 +00:00
offset = response["result"][-1]["update_id"]