Пример #1
0
                            reply_markup=markup)

    bot.register_next_step_handler(send, say_value)


@bot.message_handler(content_type=['text'])
def say_value(message):
    global state
    if message.text == 'в рублях' or message.text == 'в долларах':
        get_course(message)

    else:
        print(message.text)
        rub = crypto.rub()
        dict = crypto.get_crypto_dict('https://www.rbc.ru/crypto/')
        x = get_crypto(dict, rub, message.text, state)
        print(dict, rub, message.text, state, sep=',   ')
        if state.lower() == 'доллар':
            word = '$'
        else:
            word = '₽'

        bot.send_message(message.chat.id,
                         f'Цена валюты в данный момент - {x} {word}')

        get_course(message)


if __name__ == '__main__':
    bot.polling(none_stop=True, interval=0)
Пример #2
0
        if not first_day - timedelta(days=1) <= result.get('date') <= last_day:
            result['error_message'] = 'Можу дату інформацію лише ' \
                                      'в межах {} - {}'.format(first_day.strftime('%d.%m'),
                                                               last_day.strftime('%d.%m'))
            return result

    result['is_parsed'] = True
    return result


def send_session_data(chat_id, data):
    """Send information about sessions to chat=`chat_id`."""
    for key, value in data.items():
        title = key
        url = '{}{}'.format(value.get('url'), '#imax_cinetech_2d_3d_4dx_week')
        sessions = ', '.join(value.get('sessions'))
        description = value.get('description')

        formed_msg = '\U0001F538{}.\n{}\n' \
                     '\U0001F538Доступні сесії:' \
                     ' {}.\n{}'.format(title, description, sessions, url)

        bot.send_message(chat_id, formed_msg)
        sleep(2)


if __name__ == '__main__':
    locale.setlocale(locale.LC_ALL, '')
    today = datetime.today()
    bot.polling(none_stop=True, interval=0)
Пример #3
0
@bot.message_handler(commands=['life'])
def default_test(message):
    keyboard = types.InlineKeyboardMarkup()
    url_button = types.InlineKeyboardButton(text="Перейти на VK",
                                            url="https://vk.com")
    keyboard.add(url_button)
    m_button = types.InlineKeyboardButton(text='Тестовая кнопка',
                                          callback_data='dead')
    keyboard.add(m_button)
    bot.send_message(message.chat.id,
                     "Привет! Нажми на кнопку и перейди в VK.",
                     reply_markup=keyboard)


@bot.callback_query_handler(func=lambda call: True)
def do_callback(call):
    if call.data == 'dead':
        mess = choice(['Первый вариант', 'второй вариант', 'третий вариант'])
        bot.send_message(call.message.chat.id, mess)


# @bot.message_handler(func=lambda message: True)
# def say_hello(message):
#     if message.text.lower() == 'Привет':
#         bot.send_message(message.chat.id, 'Чеза привет уцы')
#     else:
#         bot.reply_to( message, message.text + ' салам вац')

if __name__ == '__main__':
    bot.polling()
Пример #4
0
            conn.close()
        except Exception as ex:
            addLog(
                'e',
                f'Something [{type(ex).__name__}] went wrong in create_table(): {str(ex)}'
            )

    if type_of_table == 'states':
        create_table_states()


if __name__ == '__main__':
    logging.getLogger('requests').setLevel(logging.CRITICAL)
    logging.basicConfig(
        format=
        '[%(asctime)s] %(filename)s:%(lineno)d %(levelname)s - %(message)s',
        level=logging.INFO,
        filename='bot.log',
        datefmt='%d.%m.%Y %H:%M:%S')
    while True:
        if not os.path.isfile('states.db'):
            create_table('states')
        #infinity_polling_start()
        try:
            bot.polling(none_stop=True)
        except Exception as ex:
            addLog(
                'e',
                f'Something [{type(ex).__name__}] went wrong in bot.polling(): {str(ex)}'
            )
            time.sleep(5)
Пример #5
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from telebot import TeleBot

from client import BotClient

telegram_bot = TeleBot("354252761:AAH92i35ZjkO56emVjEQvmY67YCRUnWWb8w")


@telegram_bot.message_handler(commands=["start"])
def send_book_name(message):
    client = BotClient()
    body = client.get_http_response()
    book_name = client.get_book_name(body)
    telegram_bot.reply_to(message, book_name)


telegram_bot.polling()
Пример #6
0
                                   .format(weather.get_min_temp(),
                                           weather.get_max_temp()))
                __bot.send_message(message.chat.id, "Інформація: \n" + weather.get_info())
            except Exception as err:
                # weather.set_local('львів')
                print(err)

        if message.text.lower() in 'погода':
            __mess()

        elif (message.text.split()[0].lower() in ('місто', 'село')) and (len(message.text.split()) > 1):
            # weather.set_local(message.text.split(' ')[1].lower())
            __mess()

        elif (message.text.split()[0].lower() in 'дата') and (len(message.text.split()) > 1):
            weather.set_date(message.text.split(' ')[1])
            __mess()

        elif message.text.lower() in 'сьогодні':
            weather.set_date(str(datetime.today().date()))
            __mess()

    except Exception as a:
        print(a)


if __name__ == "__main__":
    weather = Weather()

    __bot.polling(none_stop=True, interval=1)
Пример #7
0
class Telegram:
    """Telegram is an alternative UI to the web API for the project. It works via telegram commands.
    If you need just to send a message to the project channel / group, use system_service.send_telegram_message()"""

    def __init__(self, core: Core):
        self.core = core
        self.bot: Optional[TeleBot] = None
        self.is_started = False

    @synchronized
    def start(self):
        """
        Telegram bot can be started only if these bot settings are set:
        - telegram_token
        - telegram_admins
        - telegram_polling
        """
        app_bot = self.core.system_service.get_bot()
        if app_bot.telegram_token and app_bot.telegram_admins and app_bot.telegram_polling:
            Thread(target=self._start).start()
            return True

    def _start(self):
        try:
            self.bot = TeleBot(self.core.system_service.get_bot().telegram_token, skip_pending=True)
            self._init_commands()
            self.is_started = True
            self.core.log.debug("telegram started")
            self.bot.polling(none_stop=True)
        except Exception as e:
            self.is_started = False
            self.core.log.error(f"telegram polling: {str(e)}")

    @synchronized
    def stop(self):
        self.is_started = False
        if self.bot:
            self.bot.stop_bot()
        self.core.log.debug("telegram stopped")

    def _init_commands(self):
        @self.bot.message_handler(commands=["start", "help"])
        @auth(admins=self.core.system_service.get_bot().telegram_admins, bot=self.bot)
        def help_handler(message: Message):
            result = """
/workers - List all workers
/start_worker ${worker_name} - Start the worker
/stop_worker ${worker_name} - Start the worker
            """
            self._send_message(message.chat.id, result)

        @self.bot.message_handler(commands=["ping"])
        @auth(admins=self.core.system_service.get_bot().telegram_admins, bot=self.bot)
        def ping_handler(message: Message):
            text = message.text.replace("/ping", "").strip()
            self._send_message(message.chat.id, f"pong {text}")

        @self.bot.message_handler(commands=["workers"])
        @auth(admins=self.core.system_service.get_bot().telegram_admins, bot=self.bot)
        def workers_handler(message: Message):
            result = ""
            for w in self.core.db.worker.find({}, "name"):
                result += f"{w.name}, source={w.source}, started={w.started}\n"
            self._send_message(message.chat.id, result)

        @self.bot.message_handler(commands=["start_worker"])
        @auth(admins=self.core.system_service.get_bot().telegram_admins, bot=self.bot)
        def start_handler(message: Message):
            chat_id = message.chat.id
            worker_name = message.text.replace("/start_worker", "").strip()
            if not worker_name:
                return self._send_message(chat_id, "usage: /start_worker ${worker_name}")

            worker = self.core.db.worker.find_one({"name": worker_name})
            if worker:
                self.core.worker_service.start_worker(worker.id)
                return self._send_message(chat_id, "worker was started")
            else:
                self._send_message(message.chat.id, "worker was not found")

        @self.bot.message_handler(commands=["stop_worker"])
        @auth(admins=self.core.system_service.get_bot().telegram_admins, bot=self.bot)
        def stop_handler(message: Message):
            chat_id = message.chat.id
            worker_name = message.text.replace("/stop_worker", "").strip()
            if not worker_name:
                return self._send_message(chat_id, "usage: /stop_worker ${worker_name}")

            worker = self.core.db.worker.find_one({"name": worker_name})
            if worker:
                self.core.worker_service.stop_worker(worker.id)
                return self._send_message(chat_id, "worker was stopped")
            else:
                return self._send_message(chat_id, "worker was not found")

    def _send_message(self, chat_id: int, message: str):
        for text in split_string(message, 4096):
            self.bot.send_message(chat_id, text)  # type:ignore
Пример #8
0
bot = TeleBot(BOT_API_KEY)


@bot.message_handler()
def handler(message: Message) -> None:
    if message.chat.id not in AUTHORIZED_CHATS:
        logging.info("Unhautorized user, ChatId: %s" % message.chat.id)
        bot.send_message(message.chat.id,
                         "Você não está autorizado a usar este serviço.")
        return None

    buttons = [[InlineKeyboardButton(msg, callback_data=msg)]
               for msg in message.text.split("\n")]

    reply_markup = InlineKeyboardMarkup(buttons)
    logging.info("Sending message, options: %s" %
                 ";".join([bt[0].text for bt in buttons]))
    for channel_id in TELEGRAM_CHANNELS_ID:
        with try_except_ignore(Exception, context=f"Chat id: {channel_id}"):
            bot.send_message(chat_id=channel_id,
                             text='🚨ATENTOS🚨',
                             reply_markup=reply_markup)


logging.basicConfig(format="[%(asctime)s] %(levelname)s: %(message)s",
                    datefmt="%d-%m-%Y %H:%M:%S",
                    level=logging.INFO)

if __name__ == "__main__":
    bot.polling(none_stop=True, interval=0, timeout=2)
Пример #9
0
login.login_message = 'Для входа в систему необходима авторизация.'
login.login_message_category = 'warning'

import application.core.models as models


@app.shell_context_processor
def make_shell_context():
    return {
        'db': db,
        'User': models.User,
        'Dish': models.Dish,
        'CartItem': models.CartItem,
        'DishCategory': models.DishCategory,
        'Order': models.Order
    }


from application.bot import bp as bot_bp
app.register_blueprint(bot_bp)
from application.auth import bp as auth_bp
app.register_blueprint(auth_bp, url_prefix='/auth')
from application.admin import bp as admin_bp
app.register_blueprint(admin_bp)
from application.utils import filters

if 'ADMIN_DEV' not in os.environ and 'PRODUCTION' not in os.environ:
    logger.setLevel(logging.DEBUG)
    telegram_bot.remove_webhook()
    telegram_bot.polling(none_stop=True)
Пример #10
0
                chat_id=call.message.chat.id,
                message_id=call.message.message_id,
                text=
                "Hi👋🏻\n🔅Welcome to FaceApp bot.\n➖➖➖➖➖➖➖➖\n⛑For use this robot you just need to send your picture for face changing.\n⚠️Note : Picture must be a single picture and have a bright face.",
                reply_markup=markup)
        elif call.data == "help":
            bot.send_message(
                call.message.chat.id,
                "⚜ Magic Team ⚜\n➖➖➖➖➖➖➖➖\n🔹 Programmer : @FaceApp_Full\n🔸 Channel : @FaceApp_Full"
            )
        else:
            s = bot.get_chat_member(channel, call.message.chat.id)
            if s.status == "member" or s.status == "creator" or s.status == "administrator":
                try:
                    code = call.data
                    ff = TemporaryFile()
                    ff.write(
                        requests.get(
                            "http://dev.magic-team.ir/faceapp/download/?hash="
                            + code).content)
                    ff.seek(0)
                    bot.send_photo(call.message.chat.id,
                                   ff,
                                   reply_to_message_id=call.message.message_id)
                    ff.close()
                except Exception as e:
                    print(e)


bot.polling(True)
Пример #11
0
def capture(message):
    telebot.send_photo(message.chat.id, image_capture.capture())


@telebot.message_handler(commands=['capture_sample'])
def capture_sample(message):
    s = image_capture.capture_video(10)
    destiny_path = os.path.join(root, "tmp.h264")
    mp4_destiny_path = destiny_path[:destiny_path.rfind('.')] + 'mp4'
    image_capture.write_stream(s, destiny_path)
    command = ['MP4Box', '-add', destiny_path, mp4_destiny_path]
    if subprocess.call(command) == 0:
        telebot.send_video(message.chat.id,
                           open(mp4_destiny_path, 'rb').read())
        if os.path.exists(mp4_destiny_path):
            os.remove(mp4_destiny_path)
        if os.path.exists(destiny_path):
            os.remove(destiny_path)


@telebot.message_handler(commands=['is_alive'])
def is_alive(message):
    telebot.reply_to(message, messages.get("IS_ALIVE", ""))


stopper = Event()
motion_monitor = MotionMonitor(stopper, capture)
motion_monitor.start()

telebot.polling(interval=0.1)
stopper.set()
Пример #12
0
    target_directory = join("static", "voice", str(user_id))
    file_path = ''.join([
        target_directory, "/",
        splitext(basename(urlparse(file_url).path))[0], ".wav"
    ])

    if not exists(file_path):
        if not exists(target_directory):
            makedirs(target_directory)
        convert_to_wav(file_url, file_path)


@bot.message_handler(content_types=['photo'])
def handle_photo_msg(message):
    user_id = message.json['from']['id']
    file_id = message.json['photo'][-1]['file_id']
    data = urlopen(bot.get_file_url(file_id)).read()

    if has_face(data):
        target_directory = join("static", "photo", str(user_id))
        data_path = join(target_directory,
                         basename(bot.get_file(file_id).file_path))
        if not exists(data_path):
            if not exists(target_directory):
                makedirs(target_directory)
            with open(data_path, 'wb') as f:
                f.write(data)


bot.polling(timeout=20)
Пример #13
0
def bot():
    bot = TeleBot(TOKEN)
    #Ответ на команды /start и /help
    @bot.message_handler(commands=['start', 'help'])
    def handle_start_help(message):
        bot.reply_to(
            message,
            f'Привет {message.chat.first_name}\nЯ Пробити Кот и я могу дать тебе попанский пресс или список всех попанских матчей на сегодня\
для этого  напиши команду:\n{COMMANDS_EXPRESS}{COMMANDS_MATCHES}')

    # Обрабатывается голосовые сообщения
    @bot.message_handler(content_types=['voice'])
    def handle_voice(message):
        bot.reply_to(
            message,
            f'У тебя очень красивый голос, {message.chat.first_name}, но я не могу распозновать голосовые сообщения'
        )

    #Обработка картиночек
    @bot.message_handler(content_types=['photo'])
    def handle_photos(message):
        answers = ['Ха ору :D', ')))', 'Давай еще :D']
        bot.reply_to(message, f'{random.choice(answers)}')

    @bot.message_handler(func=lambda message: 'прес' in message.text.lower(),
                         content_types=['text'])
    def popan_press(message):
        name = get_name(message)
        log('history.log',
            f'{asctime()} {name} спросил экспресс - {message.text}\n')
        try:
            if (
                    len(message.text.split()) == 4
            ):  # 4 arguments command, minCoefOfExpress, minCoefOfMatch, maxCoefOfMatch
                minCoefOfExpress = float(message.text.split()[1].replace(
                    ',', '.'))
                minCoefOfMatch = float(message.text.split()[2].replace(
                    ',', '.'))
                maxCoefOfMatch = float(message.text.split()[3].replace(
                    ',', '.'))
                msg, press = popan_press_bot(minCoefOfExpress, minCoefOfMatch,
                                             maxCoefOfMatch)
            elif (len(message.text.split()) == 2
                  ):  # 2 arguments command and minCoefOfExpress
                minCoefOfExpress = float(message.text.split()[1].replace(
                    ',', '.'))
                msg, press = popan_press_bot(minCoefOfExpress)
            elif (len(message.text.split()) == 1):
                msg, press = popan_press_bot()
            else:
                raise ValueError('Ошибка в количестве аргументов')
        except ValueError as error_msg:
            msg = f"{error_msg}\n\nВведите команду в формате:\n{COMMANDS_EXPRESS}"
            press = [
                f"Не удалось собрать экспресс по заданным параметрам {error_msg}"
            ]
        finally:
            bot.reply_to(message, msg)

        log('history.log', f'{asctime()} пресс отправлен\n')
        logMsg = str()
        for line in press:
            logMsg += line + '\n'
        log('history.log', logMsg + "\n")

    # @bot.message_handler(commands=['contest'])
    # def contest_press(message):
    #     name = get_name(message)
    #     log('contest.log', f'{asctime()} {name} спросил КОНКУРСНЫЙ пресс\n')
    #     msg, press = contest_press_bot()
    #     bot.reply_to(message, msg)

    #     log('contest.log', f'{asctime()} пресс выдан\n')
    #     msg = str()
    #     for line in press:
    #         msg += line + '\n'
    #     log('contest.log', msg + "\n")

    @bot.message_handler(func=lambda message: 'матчи' in message.text.lower(),
                         content_types=['text'])
    def matches_list(message):
        name = get_name(message)
        log('history.log', f'{asctime()} {name} спросил список матчей\n')
        try:
            if len(message.text.split(
            )) == 3:  # 3 arguments command, minCoefOfMatch, maxCoefOfMatch
                minCoefOfMatch = float(message.text.split()[1].replace(
                    ',', '.'))
                maxCoefOfMatch = float(message.text.split()[2].replace(
                    ',', '.'))
                msg = popan_list_bot(minCoefOfMatch, maxCoefOfMatch)
            elif len(message.text.split()) < 3:
                msg = popan_list_bot()
        except ValueError as error_msg:
            msg = [
                f'Не удалось собрать матчи по данным параметрам\n{error_msg}\n\n{COMMANDS_MATCHES}'
            ]

        if len(msg) == 1:
            bot.reply_to(message, msg[0])
        else:
            for i in range(len(msg)):
                part = f'Часть {i+1} из {len(msg)}\n' + msg[i]
                bot.reply_to(message, part)
        name = get_name(message)
        log('history.log', f'{asctime()} список для {name} выдан\n')

    # Обрабатывается текстовые  сообщения
    @bot.message_handler(content_types=['text'])
    def handle_text(message):
        bot.reply_to(
            message,
            f'Извини, {message.chat.first_name}, но я пока не могу свободно общаться.\n\
Чтобы получить прогнозы или список матчей нужно вводить команды:\n\
{COMMANDS_EXPRESS}{COMMANDS_MATCHES}')

        name = get_name(message)
        log('history.log', f'{asctime()} {name} написал:\n {message.text}\n\n')

    bot.polling()
Пример #14
0
                send_error(m.chat.id)


def callback_listener(call):
    logger.info(call)
    try:
        message_dispatched = dispatch(bot, chats, call.from_user.id, call.data, call.message.message_id)

        if not message_dispatched:
            logging.warning(u'Message2 is not dispatched (chat id - {0}) | message: {1}'.format(call.from_user.id, call.data))
            send_error(call.from_user.id)

    except Exception as e:
        if chats.get(call.from_user.id) is not None:
            del chats[call.from_user.id]
        logging.error(u'Error2 by chat with id {0} | error: {1}'.format(call.from_user.id, e))
        send_error(call.from_user.id)


if __name__ == '__main__':
    bot = TeleBot(config.token)
    bot.set_update_listener(listener)

    @bot.callback_query_handler(func=lambda call: True)
    def test_callback(call):
        callback_listener(call)

    bot.polling(none_stop=True)
    while True:
        time.sleep(200)
Пример #15
0
class ReviewBlock:
    def __init__(self, token):
        self._token = token
        self._bot = TeleBot(self._token)

        self._MESSAGES = {
            0: 'Enter your name', 1: 'Enter your last name',
            2: 'Enter your email', 3: 'Enter your phone',
            4: 'Enter your review', 5: 'Thank you for your review'
        }

        self._REVIEW_STEPS = {
            1: 'name', 2: 'last_name',
            3: 'email', 4: 'phone',
            5: 'review'
        }

        self._review_dict = {}

        @self._bot.message_handler(commands=["start"])
        def _start(message):
            self._start_command(message)

        @self._bot.message_handler(content_types=['text'])
        def _review(message):
            self._review_command(message)

        self._bot.polling()

    @staticmethod
    def _get_user_state(chat_id):
        states = json.loads(State.objects.get(chat_id=chat_id).to_json())
        return states['state']

    @staticmethod
    def _update_user_state(chat_id, new_state):
        State.objects(chat_id=chat_id).update_one(state=new_state)

    def _get_current_message(self, chat_id):
        return self._MESSAGES[self._get_user_state(chat_id)]

    def _start_command(self, message):
        chat_id = message.chat.id
        self._bot.send_message(message.chat.id, 'Hello. Leave your review.')
        try:
            State.objects.create(chat_id=chat_id)
        except Exception:
            self._update_user_state(chat_id, 0)
        self._bot.send_message(chat_id, self._get_current_message(chat_id))
        self._update_user_state(chat_id, self._get_user_state(chat_id) + 1)

    def _review_command(self, message):
        chat_id = message.chat.id
        state = self._get_user_state(chat_id)
        message_text = self._get_current_message(chat_id)
        self._bot.send_message(chat_id, message_text)
        self._review_dict[self._REVIEW_STEPS[state]] = message.text
        self._update_user_state(chat_id, state + 1)
        if self._get_user_state(chat_id) >= len(self._MESSAGES):
            Review.objects.create(**self._review_dict)
            self._update_user_state(chat_id, 0)
#!/usr/bin/env python3

import os

from telebot import TeleBot

from utils import TokenNotDefined


TOKEN = os.environ.get('TOKEN')
if not TOKEN:
    raise TokenNotDefined('TOKEN must be defined')

bot = TeleBot(TOKEN)


@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
    bot.reply_to(message, 'Welcome to {{ cookiecutter.bot_name | title }} Bot')


@bot.message_handler(func=lambda message: True)
def echo_message(message):
    bot.reply_to(message, message.text)


if __name__ == '__main__':
    bot.polling()
Пример #17
0
def telegram_bot(token):
    options = webdriver.ChromeOptions()
    options.headless = True

    driver = webdriver.Chrome(
        r'C:\ROOKIE_codes\projects\IMPORTANT\useful_modules\selenium_module\chromedriver.exe',
        options=options)

    bot = TeleBot(token)

    @bot.message_handler(commands=['start'])
    def start_message(message):
        bot.send_message(message.chat.id, 'Hello, Dear!')
        users.append(message.chat.id)

    def check_coin():
        driver.get('https://www.worldcoinindex.com/')
        for cookie in pickle.load(
                open(
                    r'C:\ROOKIE_codes\projects\IMPORTANT\telegram_bots\cookie\session',
                    'rb')):
            driver.add_cookie(cookie)

        print('All is good!')

        driver.refresh()
        time.sleep(2)

        prices = driver.find_elements_by_class_name('lastprice')
        names = driver.find_elements_by_class_name('bitcoinName')
        percents = driver.find_elements_by_class_name('percentage')
        text = []
        price_bitcoin = []
        price_ethereum = []
        popul_coin = []
        name_text = []
        for n, c, p in zip(names[1:], prices[1:], percents):
            try:
                text.append(f'{n.text} - {c.text[2:]} euro. Percent: {p.text}')
                name_text.append(n.text)

                if 'Bitcoin' in n.text:
                    price_bitcoin.append(c.text[2:].replace(',', ''))

                if 'Ethereum' in n.text:
                    price_ethereum.append(c.text[2:].replace(',', ''))
            except:
                continue

        print("Coins is found")

        for name in name_text:
            if 'Bitcoin' == name and int(price_bitcoin[0]) >= 26000:
                for u in users:
                    bot.send_message(
                        u,
                        f"!!BITCOIN PRICE NOW!!\n-----> {price_bitcoin[0]} EURO <-----"
                    )
            if 'Ethereum' == name and int(
                    price_ethereum[0].split('.')[0]) >= 1500:
                for u in users:
                    bot.send_message(
                        u,
                        f"!!ETHEREUM PRICE NOW!!\n-----> {price_ethereum[0].split('.')[0]} EURO <-----"
                    )
            else:
                continue

    schedule.every().minute.do(check_coin)
    Thread(target=schedule_checker).start()

    bot.polling(none_stop=True, interval=0)