2022-02-21 23:41:36 +00:00
|
|
|
from django.core.management.base import BaseCommand, CommandError
|
|
|
|
|
|
|
|
from api.models import Profile
|
|
|
|
from api.messages import Telegram
|
2022-02-22 00:50:25 +00:00
|
|
|
from api.utils import get_tor_session
|
2022-02-21 23:41:36 +00:00
|
|
|
from decouple import config
|
|
|
|
import requests
|
|
|
|
import time
|
|
|
|
|
|
|
|
class Command(BaseCommand):
|
|
|
|
|
|
|
|
help = "Polls telegram /getUpdates method"
|
|
|
|
rest = 3 # seconds between consecutive polls
|
|
|
|
|
|
|
|
bot_token = config('TELEGRAM_TOKEN')
|
|
|
|
updates_url = f'https://api.telegram.org/bot{bot_token}/getUpdates'
|
|
|
|
|
2022-02-22 00:50:25 +00:00
|
|
|
session = get_tor_session()
|
2022-02-22 02:12:42 +00:00
|
|
|
telegram = Telegram()
|
2022-02-21 23:41:36 +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"""
|
|
|
|
|
|
|
|
offset = 0
|
|
|
|
while True:
|
|
|
|
time.sleep(self.rest)
|
|
|
|
|
|
|
|
params = {'offset' : offset + 1 , 'timeout' : 5}
|
2022-02-22 00:50:25 +00:00
|
|
|
response = self.session.get(self.updates_url, params=params).json()
|
2022-02-21 23:41:36 +00:00
|
|
|
if len(list(response['result'])) == 0:
|
|
|
|
continue
|
|
|
|
for result in response['result']:
|
|
|
|
text = result['message']['text']
|
|
|
|
splitted_text = text.split(' ')
|
|
|
|
if splitted_text[0] == '/start':
|
|
|
|
token = splitted_text[-1]
|
|
|
|
try :
|
|
|
|
profile = Profile.objects.get(telegram_token=token)
|
|
|
|
except:
|
|
|
|
print(f'No profile with token {token}')
|
|
|
|
continue
|
|
|
|
profile.telegram_chat_id = result['message']['from']['id']
|
|
|
|
profile.telegram_lang_code = result['message']['from']['language_code']
|
2022-02-22 02:12:42 +00:00
|
|
|
self.telegram.welcome(profile.user)
|
2022-02-21 23:41:36 +00:00
|
|
|
profile.telegram_enabled = True
|
|
|
|
profile.save()
|
|
|
|
|
|
|
|
offset = response['result'][-1]['update_id']
|
|
|
|
|
|
|
|
|