Ejemplo n.º 1
0
def event_info(call):
    try:
        event_id = call.data[5:]
        chosen_event = Events.get(Events.id == event_id)
        admin = Users.get(Users.id == chosen_event.creator)
        telebot.keyboard = InlineKeyboardMarkup()
        url = InlineKeyboardButton(text="Адрес",
                                   url="https://www.google.ru/maps/place/" +
                                   chosen_event.address)
        telebot.keyboard.add(url)
        text = '📄 Описание: {}\n⌚ Время: {}\n📅 Дата: {}'.format(
            chosen_event.text, str(chosen_event.time), str(chosen_event.date))
        text1 = '🙂 Создатель: {}\n{}\n📱 Телефон: {}\n📊 Репутация: {}'.format(
            admin.first_name, admin.last_name, admin.telephone,
            str(admin.reputation))
        bot.send_message(call.message.chat.id,
                         text=text,
                         reply_markup=telebot.keyboard)
        bot.send_message(call.message.chat.id, text=text1)
        text2 = 'Участники:' + '\n'
        for members in chosen_event.members.split():
            chosen_user = Users.get(Users.id == int(members))
            text2 += '🙂 {} {}\n📱 Телефон: {}'.format(chosen_user.first_name,
                                                     chosen_user.last_name,
                                                     chosen_user.telephone)
        if len(text2) > 11:
            bot.send_message(call.message.chat.id, text=text2)
    except Events.DoesNotExist or Users.DoesNotExist:
        pass
Ejemplo n.º 2
0
def find_friend(msg):
    if not access(msg):
        return
    """

    Функция извлекает из базы данных ключевые слова
    пользователя и сверяет их с ключевыми словами
    других пользователей. При совпадении происходит
    рассылка и обмен контактами.

    """
    user = Users.get(Users.id == msg.chat.id)
    hobbies = list(user.hobbies.split())
    bot.send_message(msg.chat.id, text='Выполняю поиск...')
    for i in hobbies:
        for j in Users.select():
            hobbies_friend = list(j.hobbies.split())
            if i in hobbies_friend and j.id != user.id:
                bot.send_message(j.id,
                                 text='Я нашёл тебе друга!\n🙂 {} {}\n'
                                 '📊 Репутация: {}\n'
                                 '📱 Телефон: {}'.format(
                                     user.first_name, user.last_name,
                                     str(user.reputation), user.telephone))
                bot.send_message(msg.chat.id,
                                 text='Я нашёл тебе друга!\n🙂 {} {}\n'
                                 '📊Репутация: {}\n'
                                 '📱Телефон: {}'.format(j.first_name,
                                                       j.last_name,
                                                       str(j.reputation),
                                                       j.telephone))
                return
    bot.send_message(msg.chat.id, text='Друг не найден(')
 def register(self, cognito:str, email) -> bool:
      user = Users.objects(cognito_id=cognito)
      print("In register")
      if user:
          return False
      det = UserDetails(email=email,tags=[])
      user = Users(cognito_id=cognito, details = det,followers=Followers(),following=Following(),direct_chats=[],reporters_members=[],viewers=[],communities=[],profile_posts=[],blocked=[])
      user.save()
      return True
Ejemplo n.º 4
0
def phone(msg):
    chosen_user = Users.get(Users.id == msg.chat.id)
    chosen_user.telephone = msg.contact.phone_number
    chosen_user.save()
    if telebot.action[msg.chat.id] == 'reg_hobbies':
        telebot.keyboard = ReplyKeyboardRemove()
        value_reg(msg)
Ejemplo n.º 5
0
async def hello(msg: types.Message):
    await bot.send_message(msg.from_user.id,
                           f"Hello {msg.from_user.first_name}!",
                           reply_markup=menu_btns)
    global id_
    id_ = msg.from_user.id
    users[id_] = Users(f'{id_}')
Ejemplo n.º 6
0
def access(msg):
    chosen_user = Users.get(Users.id == msg.chat.id)
    if chosen_user.telephone == 'NULL':
        bot.send_message(msg.chat.id,
                         text='У вас нет доступа к этой комманде',
                         reply_markup=telebot.keyboard)
        return False
    else:
        return True
Ejemplo n.º 7
0
def delete(msg):
    """

    Функция используется только администратором

    """
    chosen_user = Users.get(Users.id == msg.chat.id)
    chosen_user.delete_instance()
    bot.send_message(msg.chat.id,
                     text='Вы были успешно удалены из базы данных')
Ejemplo n.º 8
0
def receive_message(msg):
    if msg.chat.id not in telebot.action.keys():
        telebot.action[msg.chat.id] = 'answer'
    try:
        chosen_user = Users.get(Users.id == msg.chat.id)
        chosen_user.save()
    except Users.DoesNotExist:
        hello(msg)

    actions(msg)
Ejemplo n.º 9
0
def fun_call(call):
    if call.data == 'fun_end':
        fun_call_end(call)
        return
    chosen_fun = telebot.lines[int(call.data[4:])]
    user = Users.get(Users.id == call.message.chat.id)
    if telebot.action[call.message.chat.id] == 'fun_add':
        fun_call_add(call, chosen_fun, user)
    if telebot.action[call.message.chat.id] == 'fun_remove':
        fun_call_remove(call, chosen_fun, user)
Ejemplo n.º 10
0
async def hello(msg: types.Message):
    await bot.send_message(
        msg.from_user.id,
        f"Прекрасный день для закупок {msg.from_user.first_name}!",
        'Согласен?',
        reply_markup=menu_btns)
    global id_
    id_ = msg.from_user.id
    users[id_] = Users(f'{id_}')
    await Form.starting.set()
Ejemplo n.º 11
0
def receive_weather(msg):
    user = Users.get(Users.id == msg.chat.id)
    if user.latitude == 0 or user.longitude == 0:
        telebot.keyboard = ReplyKeyboardMarkup()
        telebot.keyboard.add(
            KeyboardButton("Отправить геолокацию", request_location=True))
        bot.send_message(msg.chat.id,
                         text='Прости, но я не знаю твоей геолокации:(',
                         reply_markup=telebot.keyboard)
        return
    else:
        weather(msg, user.latitude, user.longitude)
Ejemplo n.º 12
0
        def test_sign_in_doctor(self, check_hash):
            with app.app_context():
                # записываем в БД эту запись
                user = User(sign_login='******',
                            sign_password='******',
                            sign_role=2)
                db.session.add(user)
                db.session.commit()

                # создаем экземпляр класса Users
                user = Users('login2', 'password2')
                assert user.sign_in(check_hash) == 'doctor_space'
 def get_users_by_name(self,name):
     users = Users.objects(details__name__icontains=name)
     res = {}
     for i,user in enumerate(users):
         res_part={}
         res_part["id"] = user.id
         res_part["name"] = user.details.name
         res_part["pp"] = user.details.pp
         res_part["email"] = user.details.email
         res_part["about"] = user.details.about
         res[i] = res_part
     return res
Ejemplo n.º 14
0
async def hello(msg: types.Message):
    if msg.from_user.id == ID:
        await bot.send_message(msg.from_user.id,
                               f"Привет Админ!!",
                               reply_markup=admin_buttons)
    else:
        await bot.send_message(msg.from_user.id,
                               f"Привет {msg.from_user.first_name}!",
                               reply_markup=menu_btns)
        await States_.state_menu.set()
        global id_
        id_ = msg.from_user.id
        users[id_] = Users(f'{id_}')
Ejemplo n.º 15
0
def hello(msg):
    """

    Функция проверяет наличие пользователя в базе данных.
    Если его нет - создаётся новая ячейка, в которую записывается
    id чата пользователя.
    Если он есть - бот отправляет приветствие.

    """
    try:
        user = Users.get(Users.id == msg.chat.id)
        bot.send_message(
            msg.chat.id,
            text=
            'Приветствую вас, {}!\nЕсли вам нужна помощь, используйте команду /help'
            .format(user.first_name))
    except Users.DoesNotExist:
        bot.send_message(msg.chat.id,
                         text="Привет! Рад с тобой познакомиться!")
        first_name = msg.from_user.first_name
        last_name = msg.from_user.last_name
        if msg.from_user.first_name is None:
            first_name = 'Unnamed'
        if msg.from_user.last_name is None:
            last_name = ' '
        chosen_user = Users.create(id=msg.chat.id,
                                   telephone='NULL',
                                   hobbies='',
                                   first_name=first_name,
                                   last_name=last_name,
                                   reputation=0,
                                   latitude=0.0,
                                   longitude=0.0,
                                   weather=0,
                                   weather_time=datetime.time(0, 0, 0),
                                   fun='')
        chosen_user.save()
        registration(msg)
Ejemplo n.º 16
0
def value_reg(msg):
    """

    Функция первоначальной регистрации пользователя, в базе данных
    остаётся номер телефона пользователя, имя, фамилия, увлечения.

    """
    user = Users.get(Users.id == msg.chat.id)
    telebot.keyboard = ReplyKeyboardRemove()
    if 'Я прочитал и ознакомился с правилами' == msg.text or telebot.action[msg.chat.id] == 'reg_hobbies' or \
            telebot.action[msg.chat.id] == 'reg_end':
        if telebot.action[msg.chat.id] == 'reg_telephone':
            telebot.keyboard = ReplyKeyboardMarkup()
            bot.send_message(
                msg.chat.id,
                text=
                "Отлично! Теперь тебе нужно внести данные, это не займёт много времени!",
                reply_markup=telebot.keyboard)
            telebot.keyboard.add(
                KeyboardButton("Отправить номер телефона",
                               request_contact=True))
            bot.send_message(msg.chat.id,
                             text='Отправь мне свой номер телефона',
                             reply_markup=telebot.keyboard)
            telebot.action[msg.chat.id] = 'reg_hobbies'
        elif telebot.action[msg.chat.id] == 'reg_hobbies':
            bot.send_message(
                msg.chat.id,
                text=
                'Записал твой номер. Теперь отметь хэштэги по своим интересам, чтобы другим людям '
                'было проще найти тебя.',
                reply_markup=telebot.keyboard)
            user.country = msg.text
            user.save()
            telebot.action[msg.chat.id] = 'reg_end'
        elif telebot.action[msg.chat.id] == 'reg_end':
            bot.send_message(
                msg.chat.id,
                text='Записал твои хобби, спасибо за регистрацию!')
            user.hobbies += msg.text
            user.save()
            fun_adding(msg)
    elif msg.text == 'Я отказываюсь предоставлять доступ к моим данным':
        telebot.keyboard = ReplyKeyboardRemove()
        bot.send_message(
            msg.chat.id,
            text=
            'В таком случае вы не будете иметь доступ к коммандам\n/events, '
            '/find_friend, /fun',
            reply_markup=telebot.keyboard)
Ejemplo n.º 17
0
def receive_reputation(msg):
    user = Users.get(Users.id == msg.chat.id)
    if 2 > user.reputation > -2:
        bot.send_message(msg.chat.id,
                         text='Твоя репутация: ' + str(user.reputation) +
                         ' (нейтральная)')
    elif int(user.reputation) > 2:
        bot.send_message(msg.chat.id,
                         text='Твоя репутация: ' + str(user.reputation) +
                         ' (к тебе хорошо относятся другие пользователи)')
    else:
        bot.send_message(msg.chat.id,
                         text='Твоя репутация: ' + str(user.reputation) +
                         ' (к тебе плохо относятся другие пользователи)')
Ejemplo n.º 18
0
def weather(msg, latitude, longitude):
    """

    Функция отправляет пользователю актуальную погоду и
    предлагает включить уведомление на каждый день.

    """
    bot.send_message(msg.chat.id,
                     text=telebot.weather_text(latitude, longitude))
    user = Users.get(Users.id == msg.chat.id)
    if user.weather == 0:
        telebot.keyboard = ReplyKeyboardMarkup()
        telebot.keyboard.add(KeyboardButton('Да'), KeyboardButton('Нет'))
        bot.send_message(
            msg.chat.id,
            text="Хочешь, чтобы я сообщал тебе погоду каждый день?",
            reply_markup=telebot.keyboard)
        telebot.action[msg.chat.id] = 'weather_reg'
        return
Ejemplo n.º 19
0
def get_user(chosen_member, members, is_creator):
    """

    Функция извлекает информацию о пользователе по его id
    и добавляет кнопки для оценки

    """
    keyboard = InlineKeyboardMarkup()
    keyboard.add(
        InlineKeyboardButton(text='👍', callback_data='rep+_' + str(members)))
    keyboard.add(
        InlineKeyboardButton(text='👎', callback_data='rep-_' + str(members)))
    chosen_user = Users.get(Users.id == int(members))
    if is_creator == 1:
        text1 = '🔻' + chosen_user.first_name + ' ' + chosen_user.last_name
    else:
        text1 = chosen_user.first_name + ' ' + chosen_user.last_name
    bot.send_message(int(chosen_member), text=text1)
    bot.send_message(int(chosen_member),
                     text="*поставьте оценку*",
                     reply_markup=keyboard)
Ejemplo n.º 20
0
def weather_reg(msg):
    """

    Функция извлекает данные о времени и записывает в базу данных

    """
    user = Users.get(Users.id == msg.chat.id)
    if telebot.action[msg.chat.id] == 'weather_reg':
        if msg.text == 'Да' or msg.text == 'да':
            user.weather = 1
            user.save()
            telebot.keyboard = ReplyKeyboardRemove()
            bot.send_message(
                msg.chat.id,
                text='В какое время ты бы хотел получать уведомления?',
                reply_markup=telebot.keyboard)
            telebot.action[msg.chat.id] = 'weather_reg1'
        if msg.text == 'Нет' or msg.text == 'нет':
            user.weather = -1
            user.save()
            telebot.keyboard = ReplyKeyboardRemove()
            bot.send_message(msg.chat.id,
                             text="Хорошо, как скажешь)",
                             reply_markup=telebot.keyboard)
    else:
        try:
            user.weather_time = datetime.time(int(msg.text[0:2]),
                                              int(msg.text[3:5]))
            bot.send_message(
                msg.chat.id,
                text='Хорошо! Буду тебя предупреждать каждый день в ' +
                msg.text,
                reply_markup=telebot.keyboard)
            telebot.action[msg.chat.id] = 'answer'
            user.save()
        except Users.DoesNotExist or TypeError:
            bot.send_message(msg.chat.id,
                             text='Не правильный ввод, повтори ещё раз!',
                             reply_markup=telebot.keyboard)
Ejemplo n.º 21
0
def location(msg):
    if telebot.action[msg.chat.id] != 'event_create':
        telebot.keyboard = ReplyKeyboardRemove()
        user = Users.get(Users.id == msg.chat.id)
        user.latitude = msg.location.latitude
        user.longitude = msg.location.longitude
        user.save()
        bot.send_message(msg.chat.id,
                         text='Записал твою геолокацию, спасибо!',
                         reply_markup=telebot.keyboard)
        weather(msg, user.latitude, user.longitude)
    else:
        chosen_event = Events.select().where(
            (Events.count == -1) & (Events.creator == msg.chat.id)).get()
        chosen_event.address = str(msg.location.latitude) + ',' + str(
            msg.location.longitude)
        chosen_event.status = 4
        chosen_event.count = 0
        chosen_event.save()
        telebot.action[msg.chat.id] = 'answer'
        telebot.date = datetime.datetime(1, 1, 1)
        bot.send_message(msg.chat.id, text='Мероприятие успешно создано!')
        event_invite(msg)
Ejemplo n.º 22
0
def event_invite(msg):
    """

    Функция осуществляет рассылку всем пользователям,
    у которых выбранна данная категория мероприятия.

    """
    chosen_event = Events.select().where((Events.creator == msg.chat.id)
                                         & (Events.status == 4)).get()
    for i in Users.select():
        if msg.chat.id != i.id and i.fun.find(chosen_event.fun) + 1:
            telebot.keyboard = InlineKeyboardMarkup()
            telebot.keyboard.add(
                InlineKeyboardButton(text='Хочу пойти',
                                     callback_data='ev_invite' +
                                     str(chosen_event.id)))
            bot.send_message(i.id,
                             text='✉\nНовое мероприятие! ' + '\n' +
                             '⌚Время: ' + str(chosen_event.time) + '\n' +
                             '📅Дата: ' + str(chosen_event.date) + '\n' +
                             '📄Описание:' + chosen_event.text,
                             reply_markup=telebot.keyboard)
    chosen_event.status = 0
    chosen_event.save()
Ejemplo n.º 23
0
def display_users():
    return Users.display_users()
Ejemplo n.º 24
0
def save_user(user):
    return Users.save_user(user)
 def remove_follower(self,followers_id):
     self.user.update_one(pull__followers__active__with_id=followers_id)
     Users.objects(id=followers_id).update_one(pull__following__active__with_id=self.user.id)
Ejemplo n.º 26
0
while True:
    time1 = datetime.datetime.today()
    date = datetime.date.today()
    try:
        reminder = Reminder.select().where(
            (Reminder.time == datetime.time(time1.hour, time1.minute)) &
            (Reminder.date == datetime.date(date.year, date.month, date.day)))
        for i in reminder:
            bot.send_message(i.id,
                             text='🗓\nДолжен тебе напомнить:' + '\n' + i.text)
            i.delete_instance()
            i.save()
    except Reminder.DoesNotExist:
        pass
    try:
        user = Users.select().where((Users.weather == 1) & (
            Users.weather_time == datetime.time(time1.hour, time1.minute)))
        for i in user:
            bot.send_message(i.id,
                             text=telebot.weather_text(i.latitude,
                                                       i.longitude))
    except Users.DoesNotExist:
        pass
    try:
        event = Events.select().where(
            (Events.time == datetime.time(time1.hour, time1.minute))
            & (Events.date == datetime.date(date.year, date.month, date.day))
            & (Events.status == 0))
        for i in event:  # i - выбранное мероприятие
            cut = i.address.find(",")
            bot.send_message(int(i.creator),
                             text=telebot.weather_text(
Ejemplo n.º 27
0
def rep_positive(call):
    user = Users.get(Users.id == int(call.data[5:]))
    user.reputation -= 1
    bot.edit_message_text("*пользователь оценён*", call.from_user.id,
                          call.message.message_id)
    user.save()
Ejemplo n.º 28
0
def create_user(user_name, full_name, password):
    new_user = Users(user_name, full_name, password)
    return new_user
Ejemplo n.º 29
0
def event_call(call):
    if call.data[0:9] == 'ev_invite':
        try:
            chosen_user = Users.get(Users.id == call.message.chat.id)
            chosen_event = Events.get(Events.id == int(call.data[9:]))
            if chosen_event.members.find(str(call.message.chat.id)) == -1:
                telebot.keyboard = InlineKeyboardMarkup()
                telebot.keyboard.add(
                    InlineKeyboardButton(text='Принять',
                                         callback_data='ev_accept' +
                                         str(chosen_event.id) + ':' +
                                         str(call.message.chat.id)))
                telebot.keyboard.add(
                    InlineKeyboardButton(text='Отклонить',
                                         callback_data='ev_reject' +
                                         str(chosen_event.id) + ':' +
                                         str(call.message.chat.id)))
                bot.send_message(
                    chosen_event.creator,
                    text='✉\nНа ваше мероприятие записался человек!\n🙂 {} {}\n'
                    '📊 Репутация: {}\n📱 Телефон: {}'.format(
                        chosen_user.first_name, chosen_user.last_name,
                        str(chosen_user.reputation), chosen_user.telephone),
                    reply_markup=telebot.keyboard)
                bot.edit_message_text("Ваша заявка отправлена",
                                      call.from_user.id,
                                      call.message.message_id)
        except Users.DoesNotExist or Events.DoesNotExist:
            bot.send_message(
                call.message.chat.id,
                text="К сожалению, мероприятия больше не существует")
    elif call.data[0:9] == 'ev_accept':
        event_id = int(call.data[9:call.data.find(':')])
        user_id = int(call.data[call.data.find(':') + 1:])
        chosen_event = Events.get(Events.id == event_id)
        if chosen_event.members.find(str(user_id)) == -1:
            telebot.keyboard = InlineKeyboardMarkup()
            url = InlineKeyboardButton(
                text="Адрес",
                url="https://www.google.ru/maps/place/" + chosen_event.address)
            telebot.keyboard.add(url)
            bot.send_message(
                user_id,
                text=
                '✉\nВаша заявка одобрена!\n⌚ Время: {}\n📅 Дата: {}\n📄 Описание: {}'
                .format(str(chosen_event.time), str(chosen_event.date),
                        chosen_event.text),
                reply_markup=telebot.keyboard)
            chosen_event.count += 1
            chosen_event.members += str(user_id) + ' '
            chosen_event.save()
            bot.send_message(
                chosen_event.creator,
                text=
                'Пользователю отправлена полная информация о мероприятии...')
        else:
            bot.send_message(
                chosen_event.creator,
                text='Этот пользователь уже приглашён на мероприятие')

    elif call.data[0:9] == 'ev_reject':
        event_id = int(call.data[9:call.data.find(':')])
        creator = int(call.data[call.data.find(':') + 1:])
        chosen_event = Events.get(Events.id == event_id)
        bot.send_message(creator,
                         text='✉\nВаша заявка на мероприятие: "' +
                         chosen_event.text + '" отклонена!')
Ejemplo n.º 30
0
def answer(msg):
    """

    Функция работает с текстом, присланным пользователем,
    распознаёт слова и перенаправляет на ветки для
    последующих команд.

    """
    text = msg.text.lower()
    for i in telebot.words.welcome:
        i = i.lower()
        if i.find(text) != -1:
            return telebot.words.welcome[random.randint(
                0,
                len(telebot.words.welcome) - 1)]
    for i in telebot.words.leave:
        i = i.lower()
        if i.find(text) != -1:
            return telebot.words.leave[random.randint(
                0,
                len(telebot.words.leave) - 1)]
    if text.find("как") + 1 and text.find("дела") + 1:
        telebot.keyboard = ReplyKeyboardMarkup()
        telebot.keyboard.add(
            KeyboardButton("Плохо" + telebot.emoji.pictures['грусть']),
            KeyboardButton("Хорошо" + telebot.emoji.pictures['улыбка']),
            KeyboardButton("Отлично" + telebot.emoji.pictures['улыбка1']))
        return "У меня всё хорошо, а у вас?"
    elif text.find('!#!') + 1:  # функция используется только администратором
        for i in Users.select():
            if i.id != msg.chat.id:
                bot.send_message(i.id, text='БОГ: ' + msg.text[4:])
        bot.send_message(msg.chat.id,
                         text='Ваше сообщение отправлено всем пользователям!')
    elif text.find("плохо") + 1:
        telebot.keyboard = ReplyKeyboardRemove()
        return "Надеюсь, что в скором времени будет хорошо:)" + telebot.emoji.pictures[
            'подмигивание']
    elif text.find("хорошо") + 1:
        telebot.keyboard = ReplyKeyboardRemove()
        return "Рад за вас!"
    elif text.find("отлично") + 1:
        telebot.keyboard = ReplyKeyboardRemove()
        return "Это просто прекрасно!"
    elif text.find("погода") + 1 or text.find("погоду") + 1 or text.find(
            "погоде") + 1 or text.find("погодой") + 1:
        receive_weather(msg)
    elif text.find("отзыв") + 1:
        review(msg)
    elif text.find('репутация') + 1:
        receive_reputation(msg)
    elif text.find('поменя') + 1 and text.find('время') + 1 and text.find(
            'уведомлени') + 1:
        receive_change_weather(msg)
    elif text.find('найди') + 1 and text.find('друга'):
        find_friend(msg)
    elif text.find('напомин') + 1 or text.find('напомни') + 1:
        receive_memory(msg)
    elif text.find('развлечен') + 1:
        receive_fun(msg)
    elif text.find('мероприяти') + 1:
        receive_event(msg)
    else:
        bot.send_message(msg.chat.id, text='Я тебя не понимаю')