|
1 |
| -from django.http import HttpResponse |
| 1 | +from django.http import HttpResponse, HttpResponseBadRequest |
| 2 | +from bot.models import User, Message |
| 3 | +from datetime import datetime |
| 4 | +import json |
| 5 | +from django.views.decorators.csrf import csrf_exempt |
2 | 6 |
|
3 | 7 |
|
4 | 8 | def index(request):
|
5 | 9 | return HttpResponse("Hello, world. This is the bot app.")
|
| 10 | + |
| 11 | + |
| 12 | +@csrf_exempt |
| 13 | +def talkin_to_me_bruh(request): |
| 14 | + # please insert magic here |
| 15 | + try: |
| 16 | + json_message = json.loads(request.body) |
| 17 | + except json.decoder.JSONDecodeError as err: |
| 18 | + return HttpResponse(str(err)) |
| 19 | + |
| 20 | + def _is_user_registered(user_id: int) -> bool: |
| 21 | + if User.objects.filter(user_id__exact=user_id).count() > 0: |
| 22 | + return True |
| 23 | + return False |
| 24 | + |
| 25 | + def _update_id_exists(update_id: int) -> bool: |
| 26 | + if Message.objects.filter(update_id__exact=update_id).count() > 0: |
| 27 | + return True |
| 28 | + return False |
| 29 | + |
| 30 | + def _add_message_to_db(json_dict: dict) -> (None, True): |
| 31 | + try: |
| 32 | + sender_id = json_dict['message']['from'].get('id') |
| 33 | + sender_object = User.objects.filter(user_id__exact=sender_id).get() |
| 34 | + update_id = json_dict.get('update_id') |
| 35 | + message_text = json_dict['message'].get('text') |
| 36 | + message_date = json_dict['message'].get('date') |
| 37 | + except KeyError: |
| 38 | + return None |
| 39 | + if None in (sender_id, update_id, message_text, message_date): |
| 40 | + return None |
| 41 | + |
| 42 | + if _update_id_exists(update_id): |
| 43 | + return True |
| 44 | + |
| 45 | + if _is_user_registered(sender_id): |
| 46 | + try: |
| 47 | + Message( |
| 48 | + update_id=int(update_id), |
| 49 | + text=str(message_text), |
| 50 | + sender=sender_object, |
| 51 | + date=datetime.fromtimestamp(int(message_date)), |
| 52 | + ).save() |
| 53 | + return True |
| 54 | + except (KeyError, ValueError): |
| 55 | + return None |
| 56 | + else: |
| 57 | + raise ValueError('Sender is rejected') |
| 58 | + |
| 59 | + try: |
| 60 | + result = _add_message_to_db(json_message) |
| 61 | + except ValueError as e: |
| 62 | + return HttpResponseBadRequest(str(e)) |
| 63 | + if result is True: |
| 64 | + return HttpResponse('OK') |
| 65 | + else: |
| 66 | + return HttpResponseBadRequest('Malformed or incomplete JSON data received') |
0 commit comments