コード例 #1
0
ファイル: funcmenu.py プロジェクト: mlgns/goiptelegrambot
def func_unrealsum(message):
    try:

        addunrsum = re.findall(r'^\d{1,7}\sдоход$', message.text)
        addunrexp = re.findall(r'^\d{1,7}\sрасход$', message.text)

        if message.text == content.BUTTON_MAIN_MENU or message.text == "/start":
            menu.first_menu(message)
            # добавить сумму, если сообщение подходит под рег выражение добавления дохода/расхода

        elif addunrsum != []:
            menu.unrealsum_menu(message)
            income = addunrsum[0].split()[0]
            # summ(сумма), simline (симлайн), project(проект), destination(реквизит), description(описание транз), unrealsumm (неподв деньги)

            bot.send_message(message.chat.id, 'Ты добавил доход {} р.'.format(income))
            database.Database.add_transaction(database.DATABASE_NAME, income, 'nosimline', 'testproj', '0',
                                              'доходная ручная транза', income)

        elif addunrexp != []:
            menu.unrealsum_menu(message)
            expenses = addunrexp[0].split()[0]
            bot.send_message(message.chat.id, 'Ты добавил расход {} р.'.format(expenses))
            database.Database.add_transaction(database.DATABASE_NAME, '-{}'.format(expenses), 'nosimline', 'testproj',
                                              '0', 'расходная ручная транза', '-{}'.format(expenses))

        else:
            menu.unrealsum_menu(message)
            bot.send_message(message.chat.id,
                             'Твое сообщение {} не подходит под условие. Прочитай подсказку'.format(message.text))

    except Exception as e:
        print(e)
        bot.reply_to(message, 'Error add unrealsum button. Contact the administrator and please DONT use bot.')
コード例 #2
0
def register_user(message):
    reply_message = 'Welcome ' + \
        str(message.from_user.first_name) + ' to F1 predictions!'

    try:
        cursor.execute("SELECT * FROM users WHERE username=?",
                       (message.from_user.username, ))
        user = cursor.fetchall()
    except mariadb.Error as e:
        logger.error(
            f'Error SELECTING FROM users WHERE username... MariaDB output: {e}'
        )

    if not user:
        try:
            cursor.execute(
                "INSERT IGNORE INTO users (username,user_id,points) VALUES (?, ?, ?)",
                (message.from_user.username, message.from_user.id, 0))
            conn.commit()
        except mariadb.Error as e:
            logger.error(f'Error INSERTING username... MariaDB output: {e}')

        bot.reply_to(message, reply_message)
        logger.info('User created in database')
        return True

    bot.reply_to(message, "Wait, are you registered? I think so...")
コード例 #3
0
ファイル: menu.py プロジェクト: mlgns/goiptelegrambot
def create_report(message):
    try:
        chat_id = message.chat.id

        genrep = types.InlineKeyboardButton(content.BUTTON_GENREPORT)
        homepage = types.InlineKeyboardButton(content.BUTTON_MAIN_MENU)

        # отчет по всем проектам bot tribunal
        # parsprofit = types.InlineKeyboardButton(content.BUTTON_PARSPROFIT)
        # markup.add(parsprofit)

        markup = types.ReplyKeyboardMarkup(True, True)

        markup.add(genrep)
        markup.add(homepage)

        bot.send_message(chat_id,
                         "Чтобы сгенерировать отчет нажмите кнопку",
                         reply_markup=markup)

        bot.register_next_step_handler(message, funcmenu.func_create_report)

        # отправить деньги сделать перевод (реквест)

    except Exception as e:
        bot.reply_to(
            message,
            'Error createreport menu. Contact the administrator and please DONT use bot.'
        )
コード例 #4
0
ファイル: menu.py プロジェクト: mlgns/goiptelegrambot
def main_menu(message):
    try:
        chat_id = message.chat.id
        if message.text == content.BUTTON_HISTORY:
            history_menu(message)
            return
        elif message.text == content.BUTTON_MONEY:
            bot.send_message(chat_id, content.sendmoneymantra)
            send_money(message)
            return
        elif message.text == content.BUTTON_REPORT:
            bot.send_message(chat_id, 'Вы в меню создании отчета')
            create_report(message)
            return
        elif message.text == content.BUTTON_UNREALSUM:
            bot.send_message(chat_id, content.addexporsum)
            unrealsum_menu(message)
            return
        else:
            first_menu(message)
            return
    except Exception as e:
        bot.reply_to(
            message,
            'Error main menu. Contact the administrator and please DONT use bot.'
        )
コード例 #5
0
ファイル: menu.py プロジェクト: mlgns/goiptelegrambot
def first_menu(message):
    try:
        chat_id = message.chat.id
        markup = types.ReplyKeyboardMarkup(True, True)

        history = types.InlineKeyboardButton(content.BUTTON_HISTORY)
        duty = types.InlineKeyboardButton(content.BUTTON_MONEY)
        report = types.InlineKeyboardButton(content.BUTTON_REPORT)
        unreal = types.InlineKeyboardButton(content.BUTTON_UNREALSUM)

        markup.add(history)
        markup.add(duty)
        markup.add(report)
        markup.add(unreal)

        bot.send_message(chat_id,
                         content.STR_SELECT_FROM_LIST(),
                         reply_markup=markup)
        bot.register_next_step_handler(message, main_menu)

        return
    except Exception as e:
        bot.reply_to(
            message,
            'error first menu. Contact the administrator and please DONT use bot.'
        )
コード例 #6
0
ファイル: menu.py プロジェクト: mlgns/goiptelegrambot
def send_money(message):
    try:
        chat_id = message.chat.id

        send = types.InlineKeyboardButton(content.BUTTON_SENDMONEY)
        homepage = types.InlineKeyboardButton(content.BUTTON_MAIN_MENU)
        simbalance = types.InlineKeyboardButton(content.BUTTON_SIMBALANCE)

        markup = types.ReplyKeyboardMarkup(True, True)
        markup.add(send)
        markup.add(simbalance)
        markup.add(homepage)

        bot.send_message(
            chat_id,
            'Для того чтобы узнать баланс нажмите кнопку\nЕсли баланс получить не удалось - можете попробовать еще раз.',
            reply_markup=markup)
        bot.register_next_step_handler(message, funcmenu.func_send_money)

        #отправить деньги сделать перевод (реквест)

    except Exception as e:
        bot.reply_to(
            message,
            'Error sendmoney menu. Contact the administrator and please DONT use bot.'
        )
コード例 #7
0
def list_of_values(message: Message):
    bot.reply_to(
        message=message,
        text='<b>' + getattr(
            text,
            dbm.get_user_language(message.from_user.id) + "_get_top_three")() +
        '</b>\n' + dbm.get_top_three(message),
        parse_mode='HTML')
コード例 #8
0
def send_welcome(message):
    if not users_db.find_one({'chat_id': message.chat.id}):
        users_db.insert_one({
            'chat_id': message.chat.id,
            'username': message.from_user.username
        })
        bot.reply_to(message,
                     f'{HELLO_MESSAGE}, {message.from_user.first_name}')
    else:
        bot.send_message(message.chat.id, HELLO_AGAIN_MESSAGE)
コード例 #9
0
ファイル: main.py プロジェクト: dmitriipolushin/SpotifyBot
def send_command_message(message):
    chat_id = message.chat.id
    msg = '''
    This bot can help you find and share music on Spotify. 
It works automatically, no need to add it anywhere. 
Simply open any of your chats and type @spotiSearchBot something in the message field. 
Then tap on a result to send.
For example, try typing @spotiSearchBot Gangnam Style here.
You can search both by track and by artist '''
    bot.reply_to(message, msg)
コード例 #10
0
ファイル: etsiit_bot.py プロジェクト: csp98/ETSIIT_BOT
def obtener_calendario(m):

    try:
        #log(m)

        mandar_calendario(m)

    except Exception as e:
        bot.reply_to(m, 'Se ha producido un error, intentelo mas tarde')
        exception_log(e, m)
コード例 #11
0
ファイル: etsiit_bot.py プロジェクト: csp98/ETSIIT_BOT
def obtener_localizacion(m):

    try:
        #log(m)

        cid = m.chat.id

        bot.send_location(cid, 37.196689, -3.624534)
    except Exception as e:
        bot.reply_to(m, 'Se ha producido un error, intentelo mas tarde')
        exception_log(e, m)
コード例 #12
0
def send_weather(message):
    place = message.text
    try:
        observation = owm.weather_at_place(place)
        w = observation.get_weather()
    except Exception as e:
        bot.reply_to(message, e)
        return
    temp = w.get_temperature('celsius')['temp']
    answer = f'Weather in {place}: \n{temp} °C, ' + w.get_detailed_status(
    ) + '\n'
    bot.reply_to(message, answer)
コード例 #13
0
def reply(message):
    if re.search(r'^#TASK', message.reply_to_message.text):
        reply_to_text = message.reply_to_message.text
        task_id = re.sub('#TASK', '', reply_to_text)
        chat_id = int(re.search(r'^\d+', task_id).group())
        text = re.sub(r'\+\d+$', '', reply_to_text)
        msg = bot.send_message(chat_id, f'Ответ на заявку:\n{text}')
        bot.forward_message(chat_id, message.chat.id, message.message_id)
        bot.reply_to(message, 'Ответ успешно доставлен')
        dump_data(message.from_user, msg.chat, message.text, ptype='TASK REPLY')
    else:
        bot.reply_to(message, 'Ответ необходимо дать на сообщение с номером заявки!')
コード例 #14
0
ファイル: etsiit_bot.py プロジェクト: csp98/ETSIIT_BOT
def horario(m):

    try:
        #log(m)
        cid = m.chat.id
        texto = "Elige el grado"
        msg = bot.send_message(cid, texto, reply_markup=teclado_horario)
        bot.register_next_step_handler(msg, aux_horario)

    except Exception as e:
        bot.reply_to(m, 'Se ha producido un error, intentelo mas tarde')
        exception_log(e, m)
コード例 #15
0
def about_author(message: Message):
    bot.send_chat_action(action='typing', chat_id=message.from_user.id)
    if dbm.get_user_language(message.from_user.id) == "NONE" and (
            message.text != "English" and message.text != "Русский"):
        # bot.send_message(message.chat.id, text.UNDEFINED_LANGUAGE)
        bot.reply_to(message, text.UNDEFINED_LANGUAGE)
    else:
        message_text = getattr(
            text,
            dbm.get_user_language(message.from_user.id) + "_about_author")()
        # bot.send_message(message.chat.id, message_text, parse_mode='HTML')
        bot.reply_to(message, message_text, parse_mode='HTML')
コード例 #16
0
ファイル: etsiit_bot.py プロジェクト: csp98/ETSIIT_BOT
def ayuda(m):

    #log(m)

    cid = m.chat.id

    try:
        mensaje = open('../informacion/ayuda.txt', 'r').read()
        bot.send_message(cid, mensaje)

    except Exception as e:
        exception_log(e, m)
        bot.reply_to(m, 'Se ha producido un error, intentelo mas tarde')
コード例 #17
0
ファイル: etsiit_bot.py プロジェクト: csp98/ETSIIT_BOT
def obtener_web(m):

    try:
        #log(m)

        cid = m.chat.id
        mensaje = 'Aquí tienes la web de la ETSIIT: '

        bot.send_message(cid, mensaje + 'http://etsiit.ugr.es/')

    except Exception as e:
        bot.reply_to(m, 'Se ha producido un error, intentelo mas tarde')
        exception_log(e, m)
コード例 #18
0
def set_ENG_language(message: Message):
    bot.send_chat_action(action='typing', chat_id=message.from_user.id)
    if dbm.get_user_language(message.from_user.id) == "Russian":
        # bot.send_message(message.chat.id, "Этот язык уже установлен")
        bot.reply_to(message, "Этот язык уже установлен")
    else:
        dbm.update(user_id=message.from_user.id,
                   item='User_language',
                   new_value='Russian')
        # bot.send_message(message.chat.id, getattr(text, dbm.get_user_language(message.from_user.id) + "_set")())
        bot.reply_to(
            message,
            getattr(text,
                    dbm.get_user_language(message.from_user.id) + "_set")())
コード例 #19
0
def set_ENG_language(message: Message):
    bot.send_chat_action(action='typing', chat_id=message.from_user.id)
    if dbm.get_user_language(message.from_user.id) == "English":
        # bot.send_message(message.chat.id, "This language is already set")
        bot.reply_to(message, "This language is already set")
    else:
        dbm.update(user_id=message.from_user.id,
                   item='User_language',
                   new_value='English')
        # bot.send_message(message.chat.id, getattr(text, dbm.get_user_language(message.from_user.id) + "_set")())
        bot.reply_to(
            message,
            getattr(text,
                    dbm.get_user_language(message.from_user.id) + "_set")())
コード例 #20
0
def handle(message, method_name, allow_no_chat=False):
    try:
        handler = PenisHandler(bot, message, allow_no_chat=allow_no_chat)
    except SocialCreditError as e:
        text = bot.translator.translate(str(e), DEFAULT_LANGUAGE)
        bot.reply_to(message, text)
        return
    try:
        method = getattr(handler, method_name)
        method()
    except SocialCreditError as e:
        handler.send_system(str(e))
    except Exception as e:
        logger.exception(str(e))
        bot.reply_to(message, "I've done goofed")
コード例 #21
0
ファイル: etsiit_bot.py プロジェクト: csp98/ETSIIT_BOT
def obtener_menu_dia(m):
    try:

        #log(m)

        cid = m.chat.id

        texto = "Selecciona dia para saber el menú"

        msg = bot.send_message(cid, texto, reply_markup=teclado_menu)

        bot.register_next_step_handler(msg, aux_menu_dia)

    except Exception as e:
        bot.reply_to(m, 'Se ha producido un error, intentelo mas tarde')
        exception_log(e, m)
コード例 #22
0
def preparing_2(message):
    lang_num = language_define(message)
    ask_text = take_phrase_2('place_input', 'day_after_tomorrow', lang_num)
    keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)
    button_geo = types.KeyboardButton(text=take_phrase_1('geolocation', lang_num), request_location=True)
    keyboard.add(button_geo)
    sent = bot.reply_to(message, ask_text, reply_markup = keyboard)
    bot.register_next_step_handler(sent, weather_2)
コード例 #23
0
ファイル: etsiit_bot.py プロジェクト: csp98/ETSIIT_BOT
def obtener_menu_semana(m):

    try:

        #log(m)

        cid = m.chat.id

        menu = get_menu_semana()

        menu = "\n\n".join(menu)

        bot.send_message(cid, menu)

    except Exception as e:
        bot.reply_to(m, 'Se ha producido un error, intentelo mas tarde')
        exception_log(e, m)
コード例 #24
0
ファイル: menu.py プロジェクト: mlgns/goiptelegrambot
def unrealsum_menu(message):
    try:
        chat_id = message.chat.id
        main = types.InlineKeyboardButton(content.BUTTON_MAIN_MENU)

        markup = types.ReplyKeyboardMarkup(True, True)
        markup.add(main)

        bot.send_message(chat_id,
                         "Чтобы добавить расход или доход нажмите кнопку",
                         reply_markup=markup)
        bot.register_next_step_handler(message, funcmenu.func_unrealsum)

    except Exception as e:
        bot.reply_to(
            message,
            'Error unrealsum menu. Contact the administrator and please DONT use bot.'
        )
コード例 #25
0
ファイル: menu.py プロジェクト: mlgns/goiptelegrambot
def history_menu(message):
    try:
        chat_id = message.chat.id
        markup = types.ReplyKeyboardMarkup(True, True)
        low = types.InlineKeyboardButton(content.BUTTON_LOW)
        middle = types.InlineKeyboardButton(content.BUTTON_MIDDLE)
        high = types.InlineKeyboardButton(content.BUTTON_HIGH)
        homepage = types.InlineKeyboardButton(content.BUTTON_MAIN_MENU)

        markup.add(low)
        markup.add(middle)
        markup.add(high)
        markup.add(homepage)

        bot.send_message(chat_id, content.HISTORY_MAIN(), reply_markup=markup)
        bot.register_next_step_handler(message, funcmenu.func_history_menu)
    except Exception as e:
        bot.reply_to(message, 'Error history menu')
コード例 #26
0
def count_all_messages(message):
    global message_storage
    global members_id

    add_one_to_message_counter_in_chats(message)

    if message.content_type == "text":
        if message.from_user.id not in members_id:
            members_id.append(message.from_user.id)
            message_storage.append(ChatMember(message.from_user.id))

        for chat_member in message_storage:
            if chat_member.get_id() == message.from_user.id:
                chat_member.append_message(message.text)
                if chat_member.check_message_length() is True:
                    bot.reply_to(message, FLOOD_MESSAGES[random.randint(0, 1)], 
                        parse_mode='HTML', disable_web_page_preview=True)
                    break
コード例 #27
0
ファイル: funcmenu.py プロジェクト: mlgns/goiptelegrambot
def func_history_menu(message):
    try:
        bot.send_message(message.chat.id, "Ты нажал кнопку {}".format(message.text))
        if message.text == content.BUTTON_MAIN_MENU:
             menu.first_menu(message)
        #      показать 15 переводов
        elif message.text == content.BUTTON_LOW:
             menu.history_menu(message)
             data = database.Database.show_transaction(database.DATABASE_NAME, content.BUTTON_LOW)
             for dat in data:
                 bot.send_message(message.chat.id, "Индекс: {}; Simline: {}; Сумма: {};\n Дата: {}; Реквизиты: {}\n Описание: {}".format(dat['id'],
                                                                                                                          dat['simline'],
                                                                                                                          dat['summ'],
                                                                                                                          dat['date'],
                                                                                                                          dat['destination'],
                                                                                                                          dat['description']))
        #    показать 30 переводов
        elif message.text == content.BUTTON_MIDDLE:
             menu.history_menu(message)
             data = database.Database.show_transaction(database.DATABASE_NAME, content.BUTTON_MIDDLE)
             for dat in data:
                 bot.send_message(message.chat.id, "Индекс: {}; Simline: {}; Сумма: {};\n Дата: {}; Реквизиты: {}\n Описание: {}".format(dat['id'],
                                                                                                                          dat['simline'],
                                                                                                                          dat['summ'],
                                                                                                                          dat['date'],
                                                                                                                          dat['destination'],
                                                                                                                          dat['description']))
        #    показать 50 переводов
        elif message.text == content.BUTTON_HIGH:
             menu.history_menu(message)
             data = database.Database.show_transaction(database.DATABASE_NAME, content.BUTTON_HIGH)
             print(data)
             for dat in data:
                 bot.send_message(message.chat.id, "Индекс: {}; Simline: {}; Сумма: {};\n Дата: {}; Реквизиты: {}\n Описание: {}".format(dat['id'],
                                                                                                                          dat['simline'],
                                                                                                                          dat['summ'],
                                                                                                                          dat['date'],
                                                                                                                          dat['destination'],
                                                                                                                          dat['description']))
        else:
             menu.history_menu(message)
    except Exception as e:
             bot.reply_to(message, 'Error history button. Contact the administrator and please DONT use bot.')
             menu.main_menu(message)
コード例 #28
0
ファイル: funcmenu.py プロジェクト: mlgns/goiptelegrambot
def func_create_report(message):
    try:
        if message.text == content.BUTTON_MAIN_MENU:
            menu.first_menu(message)
        elif message.text == content.BUTTON_GENREPORT:
            menu.create_report(message)
            data = database.Database.show_transaction(database.DATABASE_NAME, '9999999')
            print(data[0]['summ'])
            # calculate summ and add human
            comment = {'':'Сумма всех транзакций в рублях:'}
            datawsumm = {'': 0}
            for pay in data:
                if pay['summ'] != '':
                   datawsumm[''] += pay['summ']

            data.append(comment)
            data.append(datawsumm)
            # format to human

            file = open(filename, "w", newline='')
            with file as f:
                 df = pd.DataFrame(data)  # transpose to look just like the sheet above
                 df.to_csv(filename)
                 df.to_excel(nicefile)
            file.close()

            # send to user

            file = open(nicefile, 'rb')
            bot.send_document(message.chat.id, file)
            file.close()

            print('Отчет сгенерирован')

        else:
            bot.send_message(message.chat.id, 'Неправильный формат сообщения, перечитайте форму')
            menu.create_report(message)



    except Exception as e:
        # print(e)
        bot.reply_to(message, 'Error create report button. Contact the administrator and please DONT use bot.')
コード例 #29
0
def preparing_0(message, data=None):
    if data: lang_num = 0 if 'Get' in data else 1
    else: lang_num = language_define(message)
        
    ask_text = take_phrase_2('place_input', 'today', lang_num)
    keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)
    button_geo = types.KeyboardButton(text=take_phrase_1('geolocation', lang_num), request_location=True)        
    keyboard.add(button_geo)
    sent = bot.reply_to(message, ask_text, reply_markup = keyboard)
    bot.register_next_step_handler(sent, weather_0)
コード例 #30
0
ファイル: bot_handlers.py プロジェクト: Kinahem/debt_bot
def dolg(message):
    mes = message.text[6:]
    mes = mes.lower()
    rep = mes.split()
    if len(rep) < 3:
        bot.reply_to(message, "Wrong input")
    else:
        user_id = find_id(rep[0])
        user1 = find_name(rep[0])
        user2 = find_name(rep[1])
        if (str(message.from_user.id) == config.user_id['misha']) or (
                str(message.from_user.id) == user_id and
            (user1 != user2) and user1 != ' ' and user2 != ' '):
            result = str(int(functions.eval_(rep[2])))
            if result == None:
                result = rep[2]
            data = {'user1': user1, 'user2': user2, 'dolg': result}
            dolg_col.insert_one(data)
            bot.reply_to(message, "Done")
        else:
            bot.send_message(message.chat.id, "Not allowed")
コード例 #31
0
ファイル: menu.py プロジェクト: acasadoquijada/ETSIIT_BOT
def aux_menu_dia(m):
    
    try:
        
        dias = { 'Lunes': 0, 'Martes': 1, 'Miercoles': 2,'Jueves': 3,'Viernes': 4,'Sabado': 5}
        
        dia_seleccionado = str(m.text)
        
        info_dias = obtener_menu()
        
        if(len(info_dias)==0):
            bot.reply_to(m,'Hay un error en la web de comedores, intentelo mas tarde',reply_markup=hideBoard)

        else:
        
            mensaje = "¡Hola!\n\nAquí tienes el menú del " + dia_seleccionado.lower() + ", ¡Buen provecho! \n\n"
            
            aux = BeautifulSoup(info_dias[dias[dia_seleccionado]],"lxml")
    
    
            mensaje += obtener_menu_dia(aux)
                    
            mensaje += "Precio por menú: 3,5€"
    
            bot.reply_to(m, mensaje, reply_markup=hideBoard) 
                
    except Exception as e:
        bot.reply_to(m,'Se ha producido un error, intentelo mas tarde')
        #exception_log(e,m)
コード例 #32
0
def ayuda_pasiva(m):
    
    try:
        
        if hasattr(m, 'text'):
            mensaje = ""
                
            #m.text[0] != "/" evita que la ayuda pasiva se active al user /horario_gii
            if "horario" in m.text.lower() and m.text[0] != "/":
                mensaje = open('../informacion/ayuda_pasiva_horario.txt', 'r').read()
                bot.reply_to(m,mensaje)
            
            if ("examenes" in m.text.lower() or "exámenes" in m.text.lower()) and m.text[0] != "/" :
                mensaje = open('../informacion/ayuda_pasiva_examenes.txt', 'r').read()
                bot.reply_to(m,mensaje)
                
            if("menu" in m.text.lower() and m.text[0] != "/"):
                mensaje = open('../informacion/ayuda_pasiva_menu.txt', 'r').read()
                bot.reply_to(m,mensaje)
        
    except Exception as e:
        exception_log(e,m)