Exemplo n.º 1
0
 def update_remove_upvote(self, uid, new_count, uuid, db):
     self.upvoters.remove(uid)
     self.count = new_count
     db.collection(Upvote.collection_name).document(uuid).update({
         u"upvoters": ArrayRemove([uid]),
         u"count": self.count
     })
def test_array_union():
    city_ref = db.collection(u'cities').document(u'DC')

    # Atomically add a new region to the 'regions' array field.
    city_ref.update({u'regions': db.ArrayUnion([u'greater_virginia'])})

    # // Atomically remove a region from the 'regions' array field.
    city_ref.update({u'regions': ArrayRemove([u'east_coast'])})
Exemplo n.º 3
0
 def remove_report(self, incident_id, db):
     for report in self.reports:
         if report.id == incident_id:
             self.reports.remove(report)
     db.collection(self.collection_name).document(self.user_uuid).update({
         u'reports':
         ArrayRemove(
             [db.collection(Event.collection_name).document(incident_id)])
     })
     return self.user_uuid
Exemplo n.º 4
0
def update_doc_array():
    db = firestore.Client()
    # [START fs_update_doc_array]
    city_ref = db.collection(u'cities').document(u'DC')

    # Atomically add a new region to the 'regions' array field.
    city_ref.update({u'regions': ArrayUnion([u'greater_virginia'])})

    # // Atomically remove a region from the 'regions' array field.
    city_ref.update({u'regions': ArrayRemove([u'east_coast'])})
    # [END fs_update_doc_array]
    city = city_ref.get()
    print(u'Updated the regions field of the DC. {}'.format(city.to_dict()))
def convert_data(v):
    # Replace the strings 'ServerTimestamp' and 'Delete' with the corresponding
    # sentinels.
    from google.cloud.firestore_v1beta1 import ArrayRemove
    from google.cloud.firestore_v1beta1 import ArrayUnion
    from google.cloud.firestore_v1beta1 import DELETE_FIELD
    from google.cloud.firestore_v1beta1 import SERVER_TIMESTAMP

    if v == "ServerTimestamp":
        return SERVER_TIMESTAMP
    elif v == "Delete":
        return DELETE_FIELD
    elif isinstance(v, list):
        if v[0] == "ArrayRemove":
            return ArrayRemove([convert_data(e) for e in v[1:]])
        if v[0] == "ArrayUnion":
            return ArrayUnion([convert_data(e) for e in v[1:]])
        return [convert_data(e) for e in v]
    elif isinstance(v, dict):
        return {k: convert_data(v2) for k, v2 in v.items()}
    else:
        return v
Exemplo n.º 6
0
def webhook_handler():
    body = request.get_json()
    logging.info('Request body:')
    logging.info(body)

    global labels_chat_id
    global labels

    if 'callback_query' in body:
        # Callback received
        try:
            query_id = body['callback_query'].get('id')
            data = body['callback_query'].get('data')
            user_id = body['callback_query'].get('from').get('id')
            chat_id = body['callback_query'].get('message').get('chat').get(
                'id')
            inline_message_id = body['callback_query'].get('message').get(
                'message_id')
            if body['callback_query'].get('message').get(
                    'reply_to_message') is not None:
                reply_id = body['callback_query'].get('message').get(
                    'reply_to_message').get('message_id')
                reply_from_id = body['callback_query'].get('message').get(
                    'reply_to_message').get('from').get('id')

            if data == 'no':
                bot.delete_message(chat_id, inline_message_id)

            if data == 'yes':
                if user_id == reply_from_id or user_id == secrets[
                        'alessandro_id']:
                    photos = body['callback_query'].get('message').get(
                        'reply_to_message').get('photo')
                    if photos is not None:
                        photo_id = photos[-1].get('file_id')
                        if photo_id is not None:
                            reply_markup = {
                                'inline_keyboard':
                                [[{
                                    'text': 'Primo',
                                    'callback_data': 'none'
                                }, {
                                    'text': '1',
                                    'callback_data': 'primo1'
                                }, {
                                    'text': '2',
                                    'callback_data': 'primo2'
                                }, {
                                    'text': '3',
                                    'callback_data': 'primo3'
                                }], [{
                                    'text': 'Riso',
                                    'callback_data': 'riso'
                                }],
                                 [{
                                     'text': 'Secondo',
                                     'callback_data': 'none'
                                 }, {
                                     'text': '1',
                                     'callback_data': 'secondo1'
                                 }, {
                                     'text': '2',
                                     'callback_data': 'secondo2'
                                 }],
                                 [{
                                     'text': 'Contorno',
                                     'callback_data': 'none'
                                 }, {
                                     'text': '1',
                                     'callback_data': 'contorno1'
                                 }, {
                                     'text': '2',
                                     'callback_data': 'contorno2'
                                 }, {
                                     'text': '3',
                                     'callback_data': 'contorno3'
                                 }, {
                                     'text': '4',
                                     'callback_data': 'contorno4'
                                 }],
                                 [{
                                     'text': 'Non vengo',
                                     'callback_data': 'noshow'
                                 }, {
                                     'text': 'Ordinato',
                                     'callback_data': 'ordered'
                                 }]]
                            }
                            reply_markup = json.dumps(reply_markup)
                            post = bot.send(chat_id,
                                            msg="Menù pranzo",
                                            photo_id=photo_id,
                                            keyboard=reply_markup)
                            post_json = post.decode('utf8')
                            post_id = json.loads(post_json)['result'].get(
                                'message_id')
                            orders = bot.send(chat_id, msg="Ordinazioni:")
                            orders_json = orders.decode('utf8')
                            orders_id = json.loads(orders_json)['result'].get(
                                'message_id')
                            init_database(orders_id, chat_id)
                            bot.pin(post_id, chat_id)
                            bot.delete_message(chat_id, inline_message_id)
                            bot.delete_message(chat_id, reply_id)
            elif data == 'none':
                pass
            else:
                doc_ref = db.collection(u'data').document(u'one')
                doc = doc_ref.get()
                order = Order.from_dict(doc.to_dict())

                if body['callback_query'].get('from').get(
                        'first_name') is not None:
                    username = body['callback_query'].get('from').get(
                        'first_name')
                elif body['callback_query'].get('from').get(
                        'username') is not None:
                    username = body['callback_query'].get('from').get(
                        'username')
                else:
                    username = body['callback_query'].get('from').get('id')

                if data == 'ordered':
                    doc_ref.update({'ordered': username})

                elif data == 'noshow':
                    if username in getattr(order, data):
                        doc_ref.update({data: ArrayRemove([username])})
                    else:
                        doc_ref.update({'seats': ArrayRemove([username])})
                        for key in list(Order.default_labels.keys()):
                            doc_ref.update({key: ArrayRemove([username])})
                        doc_ref.update({data: ArrayUnion([username])})

                else:
                    if username in getattr(order, data):
                        doc_ref.update({data: ArrayRemove([username])})
                    else:
                        doc_ref.update({data: ArrayUnion([username])})
                        doc_ref.update({'seats': ArrayUnion([username])})
                        doc_ref.update({'noshow': ArrayRemove([username])})

                doc = doc_ref.get()
                order = Order.from_dict(doc.to_dict())
                bot.edit_message(chat_id,
                                 order.post_id,
                                 str(order),
                                 parse_mode="Markdown")

            return bot.answer_callback(query_id)

        except Exception as e:
            logging.info(e)
            return make_response('Error in callback handling')

    # Useful variables
    try:
        message = body['message']
    except Exception:
        if body.get('edited_message') is not None:
            message = body['edited_message']
        else:
            return json.dumps(body)

    message_id = message.get('message_id')
    text = message.get('text')
    is_forward = message.get('forward_from')
    fr = message.get('from')
    fr_id = fr.get('id')
    chat = message['chat']
    chat_id = chat['id']
    is_private_chat = (fr_id == chat_id)
    reply_message = None
    reply_text = None
    fr = message.get('from')
    if message.get('reply_to_message') is not None:
        reply_message = message.get('reply_to_message')
        if message.get('reply_to_message').get('text') is not None:
            reply_text = message.get('reply_to_message').get('text')

    if (not text) or is_forward:
        # Image received?
        timestamp = message.get('date')
        message_date = datetime.fromtimestamp(timestamp).astimezone(
            pytz.timezone('Europe/Rome'))
        caption = message.get('caption')
        photos = message.get('photo')
        if 11 <= message_date.hour <= 13:
            if fr_id in secrets['sender_ids']:
                if photos is not None:
                    photo_id = photos[-1].get('file_id')
                    if photo_id is not None:
                        reply_markup = {
                            'inline_keyboard': [[{
                                'text': 'Yes',
                                'callback_data': 'yes'
                            }]]
                        }
                        reply_markup = json.dumps(reply_markup)
                        return bot.send(chat_id,
                                        msg="Menù pranzo?",
                                        reply=message_id,
                                        keyboard=reply_markup)
        if (caption and caption
                == 'testphoto') and (fr_id == secrets['alexalder_id']
                                     or fr_id == secrets['alessandro_id']):
            photo_id = photos[-1].get('file_id')
            if photo_id is not None:
                reply_markup = {
                    'inline_keyboard': [[{
                        'text': 'Yes',
                        'callback_data': 'yes'
                    }, {
                        'text': 'No',
                        'callback_data': 'no'
                    }]]
                }
                reply_markup = json.dumps(reply_markup)
                return bot.send(chat_id,
                                msg="Menù pranzo?",
                                reply=message_id,
                                keyboard=reply_markup)

        print('no text')
        return json.dumps(body)

    else:
        uniformed_text = text.lower()

    if text.startswith('/labels'):
        labels_chat_id = chat_id
        return bot.send(
            chat_id,
            msg="Manda la lista dei piatti, separati andando a capo (9 linee)")

    elif text.startswith('/conto'):
        return bot.send(chat_id, msg=secrets['bill_address'])

    elif text.startswith('/ping'):
        answers = ['Welo', 'Bopo']
        return bot.send(chat_id, msg=random.choice(answers))

    elif labels_chat_id == chat_id:
        lines = []
        if ';' in text:
            lines = [x.strip() for x in text.split(';')]
        else:
            lines = text.splitlines()
        if len(lines) == 9:
            doc_ref = db.collection(u'data').document(u'two')
            doc = doc_ref.get()
            dic = doc.to_dict()
            keys = list(Order.default_labels.keys())
            for i in range(9):
                dic[keys[i]] = lines[i].strip()
            dic[keys[10]] = datetime.today().day
            db.collection(u'data').document(u'two').set(dic)
            labels = None
            doc_ref = db.collection(u'data').document(u'one')
            doc = doc_ref.get()
            order = Order.from_dict(doc.to_dict())
            bot.edit_message(order.chat_id,
                             order.post_id,
                             str(order),
                             parse_mode="Markdown")
            reply_markup = {
                'inline_keyboard': [[{
                    'text': dic['primo1'],
                    'callback_data': 'primo1'
                }], [{
                    'text': dic['primo2'],
                    'callback_data': 'primo2'
                }], [{
                    'text': dic['primo3'],
                    'callback_data': 'primo3'
                }], [{
                    'text': 'Riso',
                    'callback_data': 'riso'
                }], [{
                    'text': dic['secondo1'],
                    'callback_data': 'secondo1'
                }], [{
                    'text': dic['secondo2'],
                    'callback_data': 'secondo2'
                }], [{
                    'text': dic['contorno1'],
                    'callback_data': 'contorno1'
                }], [{
                    'text': dic['contorno2'],
                    'callback_data': 'contorno2'
                }], [{
                    'text': dic['contorno3'],
                    'callback_data': 'contorno3'
                }], [{
                    'text': dic['contorno4'],
                    'callback_data': 'contorno4'
                }],
                                    [{
                                        'text': 'Non vengo',
                                        'callback_data': 'noshow'
                                    }, {
                                        'text': 'Ordinato',
                                        'callback_data': 'ordered'
                                    }]]
            }
            reply_markup = json.dumps(reply_markup)
            bot.edit_caption(order.chat_id,
                             order.post_id - 1,
                             "Menù pranzo",
                             keyboard=reply_markup)
            return bot.send(chat_id, msg="Label aggiornate")
        elif is_private_chat:
            return bot.send(
                chat_id,
                msg=
                "Errore nella lettura, il messaggio deve avere solo 9 righe con i 9 nomi dei piatti"
            )

    return json.dumps(body)
Exemplo n.º 7
0
        # [END_EXCLUDE]

    def __repr__(self):
        return (
            u'City(name={}, country={}, population={}, capital={}, regions={})'
            .format(self.name, self.country, self.population, self.capital,
                    self.regions))


## create an instnace of a class
city = City(u'New Delhi', u'Delhi', u'India')
print(city.to_dict())

## creating a collection and add data to document
doc_ref = db.collection(u'cities').document(u'new-delhi')
doc_ref.set(city.to_dict(), merge=True)

# update the data
doc_ref.update({
    u'capital': True,
    u'timestamp': firestore.SERVER_TIMESTAMP,
    u'regions': ['old_delhi', 'new_delhi', 'karol_bag', 'sarojni']
})

## update the array -> add and remove
doc_ref.update({u'regions': ArrayUnion([u'hauz_khas'])})

doc_ref.update({u'regions': ArrayRemove([u'new_delhi'])})

# verify data added
print("Sucessfully added to database.")