コード例 #1
0
def send_new_posts_photo(message):
    if message.caption == None and dbworker.get_current_state(
            message.chat.id) == config.States.S_SEND.value:
        bot.send_message(message.chat.id,
                         'Картинка есть, остался текст',
                         reply_to_message_id=message.message_id,
                         reply_markup=keyboard2)
        # send_message(message, 'Напоминаю. ' + text_task, 2)
        dbworker.set_half_state(message.chat.id, message.photo[0].file_id)
        dbworker.set_state(message.chat.id, config.States.S_HALF_PHOTO.value)
    elif message.caption == None and dbworker.get_current_state(
            message.chat.id) == config.States.S_HALF_PHOTO.value:
        bot.send_message(message.chat.id,
                         'Картинка перезаписана, остался текст',
                         reply_to_message_id=message.message_id,
                         reply_markup=keyboard2)
        # send_message(message, 'Напоминаю. ' + text_task, 2)
        dbworker.set_half_state(message.chat.id, message.photo[0].file_id)
        dbworker.set_state(message.chat.id, config.States.S_HALF_PHOTO.value)
    else:
        try:
            name = (str(message.from_user.first_name) + " " +
                    str(message.from_user.last_name),
                    "@" + str(message.from_user.username)
                    )[message.from_user.username != None]
            if message.caption == None:
                message.caption = dbworker.get_half_state(message.chat.id)
            text = name + "\n" + str(message.caption)
            send_post(message, message.photo[0].file_id, text)
            dbworker.set_half_state(message.chat.id, None)
            dbworker.set_state(message.chat.id, config.States.S_START.value)
        except Exception as e:
            print(e)
            send_message(message, 'Что-то не так. Попробуйте еще раз', 2)
    return
コード例 #2
0
def cmd_choose_wallpaper(message):
    if dbworker.get_current_state(message.chat.id) == config.States.S_WALLPAPER.value:
        file_info = bot.get_file(message.document.file_id)
        keyboard = types.ReplyKeyboardMarkup(row_width=2)
        item1 = types.KeyboardButton("Своя.")
        item2 = types.KeyboardButton("Стандартная.")
        item3 = types.KeyboardButton("Отменить кастомизацию.")
        keyboard.add(item1, item2, item3)
        bot.send_message(message.chat.id, "Выберете заставку рабочего стола:", reply_markup=keyboard)
        url = 'https://api.telegram.org/file/bot{0}/{1}'.format(config.TOKEN, file_info.file_path)
        conn = sqlite3.connect("database.db")
        cursor = conn.cursor()
        sql = "UPDATE user_custom SET Box_start_graphic='{0}' where user_id={1}".format(url, message.from_user.id)
        cursor.execute(sql)
        conn.commit()
        conn.close()
        dbworker.set_state(message.chat.id, config.States.S_CHOOSE_DL_M_WALLPAPER.value)

    if dbworker.get_current_state(message.chat.id) == config.States.S_DOWNLOAD_WALLPAPER.value:
        file_info = bot.get_file(message.document.file_id)
        url = 'https://api.telegram.org/file/bot{0}/{1}'.format(config.TOKEN, file_info.file_path)
        keyboard = types.ReplyKeyboardMarkup(row_width=2)
        item1 = types.KeyboardButton("Отменить кастомизацию.")
        keyboard.add(item1)
        bot.send_message(message.chat.id, "Оставьте контактные данные и нажмите Далее", reply_markup=keyboard)
        conn = sqlite3.connect("database.db")
        cursor = conn.cursor()
        sql = "UPDATE user_custom SET Wallpaper='{0}' where user_id={1}".format(url, message.from_user.id)
        cursor.execute(sql)
        conn.commit()
        conn.close()
        dbworker.set_state(message.chat.id, config.States.S_FINAL.value)
コード例 #3
0
def get_lang(message):
    if not (message.text == 'ru' or message.text == 'en'):
        bot.send_message(message.chat.id, "Language can be only en or ru!")
    else:
        dbworker.set_data(message.chat.id, 'lang', message.text)

        if dbworker.get_current_state(
                message.chat.id) == dbconfiguration.CAESAR_LANG_ET:
            bot.send_message(message.chat.id,
                             '''So, there is your output file!''')
            bot.send_document(
                message.chat.id,
                Caesar.encrypt_text(
                    dbworker.get_data(message.chat.id, 'file'),
                    dbworker.get_data(message.chat.id, 'shift'),
                    dbworker.get_data(message.chat.id,
                                      'lang')).encode('UTF-8'))
            dbworker.clear_data(message.chat.id)

        if dbworker.get_current_state(
                message.chat.id) == dbconfiguration.CAESAR_LANG_DT:
            bot.send_message(message.chat.id,
                             '''So, there is your output file!''')
            bot.send_document(
                message.chat.id,
                Caesar.decrypt_text(
                    dbworker.get_data(message.chat.id, 'file'),
                    dbworker.get_data(message.chat.id, 'shift'),
                    dbworker.get_data(message.chat.id,
                                      'lang')).encode('UTF-8'))
            dbworker.clear_data(message.chat.id)

        dbworker.set_state(message.chat.id, dbconfiguration.CAESAR, bot)
コード例 #4
0
def all_msg(message):

	try:

		stage = dbworker.get_current_state(message.chat.id)
		# определяет на какой стадии пользователь

		print(' : ' + str(message.chat.id) + ' - ' + message.text)
		# потом это будет вести лог

		if stage in config.state_pull and not stage == "0":
			# для игнорирования сообщений при составлении заявки

			print('Client in getOrders')

		elif stage == config.States.S_CLIENT_ON_IB.value or stage == config.States.S_CLIENT_ON_CL.value or stage == config.States.S_CLIENT_ON_BD.value or stage == config.States.F_SUPPORT_CLIENT.value:
			# обрабатывает сообщения для пересылки между пользователем и поддержкой

			cl_sp = dbworker.get_current_state(message.chat.id)
			# получаем статус клиента, зачеем второй раз? А я откуда знаю, лень переписывать

			# в зависимости от стадии клиент он, после составления заявки, он будет сразу писать своему оператору поддержки
			# для понимания кто написал. добавляется приписки '\n\nСообщение перехвачено от клиента '
			if cl_sp == config.States.S_CLIENT_ON_IB.value:

				bot.send_message(str(config.ulahin), message.text + '\n\nСообщение перехвачено от клиента ' + message.chat.id)

			elif cl_sp == config.States.S_CLIENT_ON_CL.value:

				bot.send_message(str(config.volihina), message.text + '\n\nСообщение перехвачено от клиента ' + message.chat.id)

			elif cl_sp == config.States.S_CLIENT_ON_BD.value:

				bot.send_message(str(config.dariy), message.text + '\n\nСообщение перехвачено от клиента ' + message.chat.id)

			elif cl_sp == config.States.F_SUPPORT_CLIENT.value:
				# или если пишет оператор, то добавляет приписку от кого

				bot.send_message(dbworker.get_order_state(message.chat.id, 'client_id'), 'Сообщение отправлено от:'+ config.support_name(message.chat.id) + '\n\n' + message.text)

			else:

				print(' === ' + ' all_msg client-sup ' + ' === ' + str(message.chat.id))
				# на всякий пожарный

		else:

			print('Non state message')
			# сообщение прошло, но пользователь не имеет статуса
			
	except:

		print(' === ' + ' ERROR in all_msg' + ' === ' + str(message.chat.id))
コード例 #5
0
def enter_field_list(message):
    # global fields
    fields = re.findall(r'\w+', message.text)
    bot.send_message(message.chat.id, 'Thank you, I\'m checkin\' your info.')

    lst = [
        'TotalCases', 'NewCases', 'TotalDeaths', 'NewDeaths', 'TotalRecovered',
        'ActiveCases', 'SeriousCritical'
    ]

    # t = dbworker.get_current_state(str(message.chat.id) + 'day')
    if dbworker.get_current_state(str(message.chat.id) +
                                  'day').strip() == 'today':
        day = 0
    elif dbworker.get_current_state(str(message.chat.id) +
                                    'day').strip() == 'yesterday':
        day = 1
    else:
        pass
    # country = dbworker.get_current_state(str(message.chat.id) + 'country')
    countries = dbworker.get_current_state(str(message.chat.id) +
                                           'countries').split(', ')

    errors = [i for i in fields if i not in lst]
    # print(errors)
    if errors == []:
        if fields != []:
            dbworker.set_state(message.chat.id, config_my.States.S_START.value)
            df = stat(day)
            for_sending = df[df.Country.isin(countries)][['Country', *fields]]
            dbworker.del_state(str(message.chat.id) + 'day')
            dbworker.del_state(str(message.chat.id) + 'country')
            dbworker.del_state(str(message.chat.id) + 'countries')
            bot.send_message(
                message.chat.id,
                tabulate(for_sending,
                         headers=for_sending.columns,
                         tablefmt="pipe"))
        else:
            bot.send_message(
                message.chat.id,
                "Something has gone wrong! Enter the list of fields properly")

    else:
        bot.send_message(
            message.chat.id,
            "There\'s a number of fields with typos or something that\'s not in our list.\n"
            "Here they are:" + ", ".join(errors) + "\n"
            "To get lists of available fields use /listfields")
コード例 #6
0
def enter_country_or_region(message):
    # global countries, country
    dbworker.del_state(str(message.chat.id) + 'countries')  # Если в базе когда-то был выбор списка стран, удалим (мы же новый пишем)
    countries = [x.strip() for x in re.split(',', message.text)]
    country = dbworker.get_current_state(str(message.chat.id)+'country')

    bot.send_message(message.chat.id, 'Thank you, I\'m checkin\' your info.')
    x = stat()['Country']
    if country.strip() == 'regions':
        lst = [i for i in list(x[:8]) if i != '']
    else:
        lst = [i for i in x[8:220]]
    # bot.send_message(message.chat.id,', '.join(lst))
    errors = [i for i in countries if i not in lst]

    if errors == []:
        if countries != []:
            bot.send_message(message.chat.id, "Ok, Now you gotta specify the information you need. \n"
                                              "Enter the list of fields\n"
                                              "Type /listfields to get the list of available fields.\n"
                                              "You could type /info to recollect what we are doing now.\n"
                                              "Type /reset to start anew.")
            dbworker.set_state(str(message.chat.id)+'countries', ', '.join(countries))
            dbworker.set_state(message.chat.id, config.States.S_ENTER_FIELD_LIST.value)
        else:
            bot.send_message(message.chat.id, "Something has gone wrong! Enter the list of countries/regions properly")
    else:
        bot.send_message(message.chat.id, "There\'s a number of countries/regions with typos or something that\'s not in our list.\n"
                                          "Here they are:" + ", ".join(errors)+"\n"
                                          "To get lists of available regions/countries use /listcountries or /listregions")
コード例 #7
0
def cmd_start(message):
    state = dbworker.get_current_state(message.chat.id)
    if state == config.States.S_ENTER_TEXT:
        bot.send_message(message.chat.id, "Кажется, кто-то обещал отправить своё имя, но так и не сделал этого ")
    else:  # Под "остальным" понимаем состояние "0" - начало диалога
        bot.send_message(message.chat.id, "Hello! Let's start.Send selfie and photo")
        dbworker.set_state(message.chat.id, config.States.S_ENTER_NAME)
コード例 #8
0
ファイル: bot.py プロジェクト: Kirili4ik/tg-tickets-bot
def send_to_start(message):
    if dbworker.get_current_state(message.chat.id) == config.States.S_ST.value:
        bot.send_message(
            message.chat.id,
            "Отслеживай появление билетов на спортивные мероприятия!\n"
            "Напишите /start для начала работы\n"
            "Напишите /info для информации о боте")
コード例 #9
0
ファイル: bot.py プロジェクト: unuliar/somelieBOT
def user_entering_rating(message):
    if message.text.isdigit:
        if float(message.text) > 0 and float(message.text) < 5:
            dbworker.add_to_end(str(message.chat.id) + '_data', '&min_rating=' + message.text)
            get_wine_from_api(message, config.static_params + dbworker.get_current_state(str(message.chat.id) + '_data'))
            return
    bot.send_message(message.chat.id, 'Неверно указан рейтинг')
コード例 #10
0
ファイル: main.py プロジェクト: Yaroher2442/STARZAP_BOT
def mainMenu(message): 
    print(message.chat.id,dbworker.get_current_state(message.chat.id))
    if (message.text== 'Вернуться в меню ⬅') :
        dbworker.set_state(message.chat.id, config.States.S_START_EARNING.value)
        openMainMenu(message)
    # if (message.text == 'Опции ⚙️'):
    #     keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True,one_time_keyboard=True)
    #     button_back = types.KeyboardButton(text="Вернуться в меню ⬅")
    #     btn_update = types.KeyboardButton(text="Обновить базу данных бота 🔨")
    #     keyboard.add(btn_update,button_back)
    #     bot.send_message(message.from_user.id,'Выбирете',reply_markup=keyboard)
    #     dbworker.set_state(message.chat.id,config.States.S_OPTION.value)
    if (message.text == 'Найти запчати по каталогу 🚗'):
        keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)
        button_back = types.KeyboardButton(text="Вернуться в меню ⬅")
        keyboard.add(button_back)
        bot.send_message(message.from_user.id,'Выбирете',reply_markup=keyboard)
        dbworker.set_state(message.chat.id,config.States.S_EASY_SEARCH.value)
        S_EASY_SEARCH(message)
    if (message.text == 'Найти по vin (в разработке)'):
        keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)
        button_back = types.KeyboardButton(text="Вернуться в меню ⬅")
        keyboard.add(button_back)
        phrase='''Данный раздел в стадии разработки'''
        bot.send_message(message.from_user.id, phrase,reply_markup=keyboard)
        dbworker.set_state(message.chat.id,config.States.S_VIN_SEARCH.value)
    if (message.text == 'Помощь ❓'):
        keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)
        button_back = types.KeyboardButton(text="Вернуться в меню ⬅")
        keyboard.add(button_back)
        bot.send_message(message.from_user.id, 'тут текст помощи', reply_markup=keyboard)
        pass
コード例 #11
0
def location(message):
    global longitude
    global latitude
    #  print(message.location is not None)
    #  print((dbworker.get_current_state(message.chat.id) == config.States.S_ENTER_GEO.value) is True)
    if (dbworker.get_current_state(message.chat.id)
            == config.States.S_ENTER_GEO.value) and (message.location
                                                     is not None):
        longitude = message.location.longitude
        latitude = message.location.latitude
        coord = str(message.location.longitude) + ',' + str(
            message.location.latitude)
        r = requests.get('https://geocode-maps.yandex.ru/1.x/?apikey=' +
                         config.apikey + '&format=json&geocode=' + coord)
        if len(r.json()['response']['GeoObjectCollection']
               ['featureMember']) > 0:
            address = \
            r.json()['response']['GeoObjectCollection']['featureMember'][0]['GeoObject']['metaDataProperty']['GeocoderMetaData']['text']
            bot.send_message(message.chat.id,
                             f"*Я нашла тебя:*\n{address}\n",
                             parse_mode='Markdown')
            bot.send_message(
                message.chat.id,
                f"Теперь займемся барчиками поблизости /bounds.\n")
            dbworker.set_state(message.chat.id,
                               config.States.S_RECEIVE_GEO.value)
        else:
            bot.send_message(message.chat.id, 'Не удалось получить твой адрес')
    else:
        bot.send_message(message.chat.id,
                         'Не удалось получить твои координаты')
コード例 #12
0
def any_error(message):
    bot.send_message(
        message.chat.id,
        'Hello, this is unknown error. Read the instructions more carefully.')
    bot.send_message(
        message.chat.id,
        'You are in %s mode now' % dbworker.get_current_state(message.chat.id))
コード例 #13
0
ファイル: bot.py プロジェクト: UlahinAlex/PD_TG_bot
def any_msg_channel(message):
    if dbworker.get_current_state(
            message.chat.id) == config.States.F_CLIENT_SUPPORT.value:
        bot.send_message(88168468,
                         message.text + '\nСообщение перехвачено от клиента')
    else:
        print('Non state message')
コード例 #14
0
ファイル: worker.py プロジェクト: bopopescu/mw_bot
def tour_msg(message):
    state = dbworker.get_current_state(message.chat.id)
    balance = getBalance(message.from_user.id)
    sub_status = checkSubscriber(message.from_user.id)
    if sub_status:
        if state == config.States.S_YN_POST.value:
            bot.send_message(message.chat.id,
                             constants.msg_enter_text,
                             reply_markup=reset_markup())
        else:
            bot.send_message(message.chat.id,
                             constants.msg_enter_text,
                             reply_markup=reset_markup())
            dbworker.set_state(message.chat.id, config.States.S_YN_POST.value)
    else:
        if balance < 5:
            bot.send_message(message.chat.id,
                             getStrFailTour(message.from_user.id))
        else:
            if state == config.States.S_YN_TOUR.value:
                bot.send_message(message.chat.id,
                                 constants.msg_cost_5 +
                                 constants.msg_enter_text,
                                 reply_markup=reset_markup())
            else:
                bot.send_message(message.chat.id,
                                 constants.msg_cost_5 +
                                 constants.msg_enter_text,
                                 reply_markup=reset_markup())
                dbworker.set_state(message.chat.id,
                                   config.States.S_YN_TOUR.value)
コード例 #15
0
def handele_text(message):
    conversation_state = dbworker.get_current_state(message.chat.id)
    if conversation_state == constants.States.ENTER_PICTURE_TOPIC:
        dbworker.set_state(message.chat.id, constants.States.SENT_PICTURE_TOPIC)
        send_picture_by_topic(message.chat.id, message.text)
    else:
        bot.reply_to(message, constants.text_messages['plain_text'])
コード例 #16
0
ファイル: bot.py プロジェクト: Kirili4ik/tg-tickets-bot
def cmd_update(message):
    state = dbworker.get_current_state(message.chat.id)
    if state != config.States.S_F.value and state != config.States.S_H.value:
        bot.send_message(
            message.chat.id,
            'Нечего обновлять. Выберите, что бы вы хотели отследить после команды /start\n'
        )
        return

    bot.send_message(message.chat.id, "Обновляю...")

    if state == config.States.S_F.value:
        mess = get_links_f()
        img_link = 'http://old.fc-ural.ru/UPLOAD/2015/01/04/oboi2015_(3)_1000_0.jpg'

    elif state == config.States.S_H.value:
        mess = get_links_h()
        img_link = 'http://1723.ru/forums/uploads/post-1-1576389069.jpg'

    if mess != 'Нет билетов':
        bot.send_photo(chat_id=message.chat.id, photo=img_link)
        return True

    bot.send_message(message.chat.id, mess)
    return False
コード例 #17
0
def welcome(message):
    conn = sqlite3.connect("database.db")
    cursor = conn.cursor()
    sql = "SELECT * FROM user_role_schm where user_id = '{0}' and access not null".format(message.from_user.id)
    a = cursor.execute(sql).fetchone()
    conn.close()
    if a:
        FILEID = 'BAACAgIAAxkDAAIBxl5lH2r1r05dKYn6CzQlrGMZVmvkAAIrBwAC81coSwEmYV_wTwp4GAQ'
        markup = types.ReplyKeyboardMarkup(row_width=2)
        item1 = types.KeyboardButton("Прошивки")
        item2 = types.KeyboardButton("Техническая документация")
        item3 = types.KeyboardButton("Программы и утилиты")
        item4 = types.KeyboardButton("Приложения и кинотеатры")
        item5 = types.KeyboardButton("Удаленное управление")
        item6 = types.KeyboardButton("Техническая поддержка")
        item7 = types.KeyboardButton("Приобрести оборудование")
        item8 = types.KeyboardButton("Тестирование")
        markup.add(item1, item2, item3, item4, item5, item6, item7, item8)
        bot.send_video(message.chat.id, FILEID, reply_markup=markup)
        dbworker.set_state(message.chat.id, config.States.S_DISABLED.value)
    else:
        if dbworker.get_current_state(message.chat.id) == config.States.WAIT_AUTH_APPROVE.value:
    	    bot.send_message(message.chat.id, "Ваш запрос еще не был обработан, пожалуйста ожидайте, через некоторое время попробуйте отправить команду /start")
        else:
            dbworker.set_state(message.chat.id, config.States.NOT_AUTH_USER.value)
            bot.send_message(message.chat.id, "Здравствуйте. Вы видите данное сообщение так как не имеете прав на доступ к боту. Для получения доступа, пожалуйста, пришлите одним сообщением ваши ФИО, название организации и номер телефона для связи.")
            bot.send_message(message.chat.id,"Также Вы можете задать нам вопрос отправив его одним сообщением")
コード例 #18
0
ファイル: testbot.py プロジェクト: DanilKozlov/telergam-bot
def work_func(week, day_of_week, id_user):
    listA = []
    listA = dbworker.get_current_state(week, day_of_week)
    if not listA:
        bot.send_message(id_user, 'Ура!!! Нет пар')
    for l in listA:
        bot.send_message(id_user, l)
コード例 #19
0
ファイル: relize.py プロジェクト: Yaroher2442/STARZAP_BOT
def Admin_task_del(message):
    print(dbworker.get_current_state(message.chat.id))
    if (message.text == 'Назад'):
        dbworker.set_state(message.chat.id, config.States.S_ADMIN.value)
        Admin_work(message)
    state = dbworker.get_current_state(message.chat.id)
    if ('№' in message.text):
        keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)
        btn_confirm = types.KeyboardButton(text="Да")
        btn_back = types.KeyboardButton(text="Назад")
        keyboard.add(btn_confirm, btn_back)
        bot.send_message(message.chat.id,
                         "Выбран {} Уверены ?".format(message.text),
                         reply_markup=keyboard)
    if (message.text == 'Да'):
        bot.send_message(message.chat.id, "Удалено")
        Admin_work(message)
コード例 #20
0
ファイル: bot.py プロジェクト: unuliar/somelieBOT
def update_viewed_counter(message):
    curr = dbworker.get_current_state(str(message.chat.id) + '_num')
    if len(curr) > 0:
        curr = int(curr) + 1
    else:
        curr = 0
    dbworker.set_state(str(message.chat.id) + '_num', curr)
    return curr
コード例 #21
0
ファイル: relize.py プロジェクト: Yaroher2442/STARZAP_BOT
def Admin_task_settigs(message):
    print(dbworker.get_current_state(message.chat.id))
    if (message.text == 'Назад'):
        dbworker.set_state(message.chat.id, config.States.S_ADMIN.value)
        Admin_work(message)
    if (message.text == 'Изменить одну из задач'):
        obj = tasks.Task_worker()
        keyboard = types.ReplyKeyboardMarkup(row_width=2,
                                             resize_keyboard=True,
                                             one_time_keyboard=True)
        lst_btn = [
            types.KeyboardButton(text='№ ' + str(i[0]))
            for i in obj.show_list()
        ]
        button_back = types.KeyboardButton(text="Назад")
        keyboard.add(*lst_btn, button_back)
        mes = [
            i[0] + '-' + i[1] + ' \n ' + i[2] + ' \n '
            for i in obj.show_list()
        ]
        bot.send_message(message.chat.id,
                         'Какую задачу изменить? \n' + ''.join(mes),
                         reply_markup=keyboard)
        dbworker.set_state(message.chat.id,
                           config.States.S_ADMIN_TASK_CHANGE.value)
    if (message.text == 'Удалить одну из задач'):
        obj = tasks.Task_worker()
        keyboard = types.ReplyKeyboardMarkup(row_width=2,
                                             resize_keyboard=True,
                                             one_time_keyboard=True)
        lst_btn = [
            types.KeyboardButton(text='№ ' + str(i[0]))
            for i in obj.show_list()
        ]
        button_back = types.KeyboardButton(text="Назад")
        keyboard.add(*lst_btn, button_back)
        mes = [
            i[0] + '-' + i[1] + ' \n ' + i[2] + ' \n '
            for i in obj.show_list()
        ]
        bot.send_message(message.chat.id,
                         'Какую задачу Удалить? \n' + ''.join(mes),
                         reply_markup=keyboard)
        dbworker.set_state(message.chat.id,
                           config.States.S_ADMIN_TASK_DELITE.value)
    if (message.text == 'Добавть новую задачу'):
        obj = tasks.Task_worker()
        print('add')
        dbworker.set_state(message.chat.id,
                           config.States.S_ADMIN_TASK_ADD_text.value)
        keyboard = types.ReplyKeyboardMarkup(row_width=1,
                                             resize_keyboard=True,
                                             one_time_keyboard=True)
        keyboard.add(types.KeyboardButton(text="Назад"))
        bot.send_message(message.chat.id,
                         'Введите текст задачи:',
                         reply_markup=keyboard)
        Admin_task_add(message)
コード例 #22
0
def cmd_start(message):
    state = dbworker.get_current_state(message.chat.id)
    if state == config.States.S_ENTER_NAME.value:
        bot.send_message(message.chat.id, "Кажется, кто-то обещал отправить своё имя, но так и не сделал этого :( Жду...")
    elif state == config.States.S_SEND_PIC.value:
        bot.send_message(message.chat.id, "Кажется, кто-то хотел загрузить картинку, но так и не сделал этого :( Жду...")
    else:  # Под "остальным" понимаем состояние "0" - начало диалога
        bot.send_message(message.chat.id, "Привет! Как я могу к тебе обращаться?")
        dbworker.set_state(message.chat.id, config.States.S_ENTER_NAME.value)
コード例 #23
0
def get_shift(message):
    try:
        shift = int(message.text)
        if shift <= 0:
            raise ValueError
    except ValueError:
        bot.send_message(message.chat.id, "Secret key must be natural number!")
    else:
        dbworker.set_data(message.chat.id, 'shift', shift)

        if dbworker.get_current_state(
                message.chat.id) == dbconfiguration.CAESAR_SHIFT_ENCRYPT:
            bot.send_message(message.chat.id,
                             '''So, there is your output file!''')
            bot.send_document(
                message.chat.id,
                Caesar.encrypt(dbworker.get_data(message.chat.id, 'file'),
                               dbworker.get_data(message.chat.id, 'shift')))
            dbworker.set_state(message.chat.id, dbconfiguration.CAESAR, bot)
            dbworker.clear_data(message.chat.id)

        if dbworker.get_current_state(
                message.chat.id) == dbconfiguration.CAESAR_SHIFT_DECRYPT:
            bot.send_message(message.chat.id,
                             '''So, there is your output file!''')
            bot.send_document(
                message.chat.id,
                Caesar.decrypt(dbworker.get_data(message.chat.id, 'file'),
                               dbworker.get_data(message.chat.id, 'shift')))
            dbworker.set_state(message.chat.id, dbconfiguration.CAESAR, bot)
            dbworker.clear_data(message.chat.id)

        if dbworker.get_current_state(
                message.chat.id) == dbconfiguration.CAESAR_SHIFT_ET:
            dbworker.set_state(message.chat.id, dbconfiguration.CAESAR_LANG_ET,
                               bot)
            bot.send_message(message.chat.id, '''Input language (ru or en)!''')

        if dbworker.get_current_state(
                message.chat.id) == dbconfiguration.CAESAR_SHIFT_DT:
            dbworker.set_state(message.chat.id, dbconfiguration.CAESAR_LANG_DT,
                               bot)
            bot.send_message(message.chat.id, '''Input language (ru or en)!''')
コード例 #24
0
ファイル: main.py プロジェクト: Yaroher2442/STARZAP_BOT
def get_start(message):
    print(message.chat.id,dbworker.get_current_state(message.chat.id))
    keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)
    button_start = types.KeyboardButton(text="Начать!")
    keyboard.add(button_start)
    phrase='Здравствуйте , я бот Starzap, помогу Вам найти и подобрать новые или б/у запчасти '
    bot.send_message(message.chat.id, phrase, reply_markup=keyboard)
    dbworker.set_state(message.chat.id, config.States.S_START_EARNING.value)
    connection = sqlite3.connect(config.db_user_dataset)
    dump_worker.add_user(connection,message.chat.id)
コード例 #25
0
ファイル: main.py プロジェクト: Yaroher2442/STARZAP_BOT
def openMainMenu(message):
    print(message.chat.id,dbworker.get_current_state(message.chat.id))
    if (message.text == 'Начать!' or message.text == 'Вернуться в меню ⬅'):
        keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)
        button_earning = types.KeyboardButton(text="Найти запчати по каталогу 🚗")
        button_partners = types.KeyboardButton(text="Найти по vin (в разработке)")
        # button_options = types.KeyboardButton(text="Опции ⚙️")
        button_help = types.KeyboardButton(text="Помощь ❓")
        keyboard.add(button_earning, button_partners,button_help)
        bot.send_message(message.from_user.id, 'Выберите одно из предложенных действий', reply_markup=keyboard)
        dbworker.set_state(message.chat.id, config.States.S_CHOISE_METHOD.value)
コード例 #26
0
def my_time(message):
    '''this function print left time'''
    state = dbworker.get_current_state(message.chat.id)
    if state == config.States.S_START.value:
        bot.send_message(message.chat.id,  'введите имя пользователя, информацию о котором нужно получить.')
        dbworker.set_state(message.chat.id, config.States.USER_INFO_GET.value)
    elif state == config.States.USER_INFO_GET.value:
        bot.send_message(message.chat.id, 'введите имя.')
    else:
        bot.send_message(message.chat.id,  'введите имя пользователя, информацию о котором нужно получить.')
        dbworker.set_state(message.chat.id, config.States.USER_INFO_GET.value)
コード例 #27
0
def get_file(message):

    raw = bot.get_file(message.document.file_id)
    downloaded_file = bot.download_file(raw.file_path)
    dbworker.set_data(message.chat.id, 'file', downloaded_file)
    bot.send_message(message.chat.id, '''Success (get file)!''')

    if dbworker.get_current_state(
            message.chat.id) == dbconfiguration.CAESAR_FILE_ENCRYPT:
        dbworker.set_state(message.chat.id,
                           dbconfiguration.CAESAR_SHIFT_ENCRYPT, bot)

    if dbworker.get_current_state(
            message.chat.id) == dbconfiguration.CAESAR_FILE_DECRYPT:
        dbworker.set_state(message.chat.id,
                           dbconfiguration.CAESAR_SHIFT_DECRYPT, bot)

    bot.send_message(
        message.chat.id,
        '''Send me any natural number (this is your secret key).''')
コード例 #28
0
def cmd_start(message):
    dbworker.set_state(message.chat.id, config.States.S_START.value)
    state = dbworker.get_current_state(message.chat.id)
    # Под "остальным" понимаем состояние "0" - начало диалога
    bot.send_message(message.chat.id, "Greetings again! I'm coronabot :) \n"
                                      "You gotta specify which day's statistics you want to get: /today or /yesterday.\n"
                                      "Type /info to know what I am and what I can do for you.\n"
                                      "Tye /commands to list the available commands.\n"
                                      "Type /reset to discard previous selections and start anew.")
    bot.send_photo(message.chat.id, pict[randint(0, 5)])
    dbworker.set_state(message.chat.id, config.States.S_ENTER_DAY.value)
コード例 #29
0
ファイル: bot.py プロジェクト: BioWar/telegram-bots
def cmd_start(message):
    state = dbworker.get_current_state(message.chat.id)
    if state == config.States.S_ENTER_NAME.value:
        bot.send_message(message.chat.id, "Send your name")
    elif state == config.States.S_ENTER_AGE.value:
        bot.send_message(message.chat.id, "Send your age")
    elif state == config.States.S_SEND_PIC.value:
        bot.send_message(message.chat.id, "Send your picture")
    else:
        bot.send_message(message.chat.id, "Hello send your name")
        dbworker.set_state(message.chat.id, config.States.S_ENTER_NAME.value)
コード例 #30
0
def cmd_start(message):
    state = bd.get_current_state(message.chat.id)
    if state == config.States.S_WISH.value:
        bot.send_message(message.chat.id, "Кажется, кто-то обещал дать команду :( Жду...")
    elif state == config.States.S_NOTIFICATIONS.value:
        bot.send_message(message.chat.id, "Кажется, кто-то обещал отправить пункт назначения :( Жду...")
    elif state == config.States.S_SIGHTS.value:
        bot.send_message(message.chat.id, "Я до сих пор не знаю, где показывать развлекательные места :( Жду...")
    else:  # Под "остальным" понимаем состояние "0" - начало диалога
        bot.send_message(message.chat.id, "Привет, меня зовут Сережа! Чем могу быть полезен? Я умею включать уведомления и показывать крутые места)")
        bd.set_state(message.chat.id, config.States.S_WISH.value)