示例#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
示例#2
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)
示例#3
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='Друг не найден(')
示例#4
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
示例#5
0
def delete(msg):
    """

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

    """
    chosen_user = Users.get(Users.id == msg.chat.id)
    chosen_user.delete_instance()
    bot.send_message(msg.chat.id,
                     text='Вы были успешно удалены из базы данных')
示例#6
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)
示例#7
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)
示例#8
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)
示例#9
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)
示例#10
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) +
                         ' (к тебе плохо относятся другие пользователи)')
示例#11
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
示例#12
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)
示例#13
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)
示例#14
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)
示例#15
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)
示例#16
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 + '" отклонена!')
示例#17
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()