Example #1
0
def main():
    """Instanciate a Defaults object"""

    # Create the EventHandler and pass it your bot's token.
    q = mq.MessageQueue(all_burst_limit=29,
                        all_time_limit_ms=1017,
                        group_burst_limit=15,
                        group_time_limit_ms=55000,
                        autostart=True)
    # set connection pool size for bot
    request = Request(con_pool_size=12)
    testbot = MQBot(configs.TOKEN, request=request, mqueue=q)
    pp = PicklePersistence(filename='rabot', store_bot_data=True)
    updater = telegram.ext.updater.Updater(bot=testbot,
                                           persistence=pp,
                                           use_context=True)

    # Get the dispatcher to register handlers CallbackQueryHandler(language)
    dp = updater.dispatcher
    dp.add_handler(MessageHandler(Filters.regex('^TOP$'), botify.top))
    dp.add_handler(
        MessageHandler(Filters.regex('^PROGRESS$'), botify.check_progress))
    dp.add_handler(MessageHandler(Filters.regex('^HELP$'), botify.help))
    dp.add_handler(MessageHandler(Filters.regex('^MY RA$'), botify.myra))
    dp.add_handler(MessageHandler(Filters.regex('^PROFILE$'), botify.profile))
    dp.add_handler(CommandHandler(command='start', callback=botify.start))
    dp.add_handler(CommandHandler(command='help', callback=botify.help))
    dp.add_handler(CommandHandler(command='top', callback=botify.top))
    dp.add_handler(CommandHandler(command='gid', callback=botify.gid))
    dp.add_handler(CommandHandler(command='solo', callback=botify.solo_learn))
    dp.add_handler(
        CommandHandler(command='progress', callback=botify.check_progress))
    dp.add_handler(
        CommandHandler(command='studyrooms', callback=botify.studyrooms))
    dp.add_handler(CommandHandler(command='teachers',
                                  callback=botify.teachers))
    dp.add_handler(
        CommandHandler(command='classrooms', callback=botify.classrooms))
    dp.add_handler(CommandHandler(command='rector', callback=botify.rector))
    dp.add_handler(CommandHandler(command='settopic',
                                  callback=botify.settopic))
    dp.add_handler(
        CommandHandler(command='support', callback=botify.ask_donation))
    dp.add_handler(CommandHandler(command='topic', callback=botify.topic))
    dp.add_handler(
        CommandHandler(command='stop', callback=botify.session_manager))
    dp.add_handler(
        MessageHandler(Filters.command & Filters.reply & Filters.group,
                       botify.bonus))
    dp.add_handler(
        MessageHandler(Filters.reply & (Filters.text | Filters.voice),
                       botify.reply_check))
    dp.add_handler(
        MessageHandler(Filters.status_update.new_chat_members,
                       botify.unauth_group))
    dp.add_handler(MessageHandler(Filters.text, botify.message_counter))
    dp.add_handler(MessageHandler(Filters.dice, botify.solo_learn))
    dp.add_handler(CallbackQueryHandler(botify.javis))
    dp.add_handler(PollHandler(botify.poll_private))
    dp.add_handler(PollAnswerHandler(botify.poll_listener))
    # log all errors
    #     dp.add_error_handler(botify.error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()
Example #2
0
 def __init__(self, *args, is_queued_def=True, mqueue=None, **kwargs):
     super(MQBot, self).__init__(*args, **kwargs)
     # below 2 attributes should be provided for decorator usage
     self._is_messages_queued_default = is_queued_def
     self._msg_queue = mqueue or mq.MessageQueue()
Example #3
0
 def __init__(self, is_queued_def=True, mqueue=None, *args, **kwargs):
     super(MQBot, self).__init__(token='536400210:AAF7-FzhpS308A4rN6-Wm9POHRPcEooMvlg', *args, **kwargs)
     # below 2 attributes should be provided for decorator usage
     self._is_messages_queued_default = is_queued_def
     self._msg_queue = mqueue or mq.MessageQueue()
Example #4
0
    def ready(self):
        if DjangoTelegramBot.ready_run:
            return
        DjangoTelegramBot.ready_run = True

        self.mode = WEBHOOK_MODE
        if settings.DJANGO_TELEGRAMBOT.get('MODE', 'WEBHOOK') == 'POLLING':
            self.mode = POLLING_MODE

        modes = ['WEBHOOK', 'POLLING']
        logger.info('Django Telegram Bot <{} mode>'.format(modes[self.mode]))

        bot_data = settings.DJANGO_TELEGRAMBOT

        if self.mode == WEBHOOK_MODE:
            webhook_site = settings.DJANGO_TELEGRAMBOT.get(
                'WEBHOOK_SITE', None)
            if not webhook_site:
                logger.warn(
                    'Required TELEGRAM_WEBHOOK_SITE missing in settings')
                return
            if webhook_site.endswith("/"):
                webhook_site = webhook_site[:-1]

            webhook_base = settings.DJANGO_TELEGRAMBOT.get(
                'WEBHOOK_PREFIX', '/')
            if webhook_base.startswith("/"):
                webhook_base = webhook_base[1:]
            if webhook_base.endswith("/"):
                webhook_base = webhook_base[:-1]

            cert = settings.DJANGO_TELEGRAMBOT.get('WEBHOOK_CERTIFICATE', None)
            certificate = None
            if cert and os.path.exists(cert):
                logger.info('WEBHOOK_CERTIFICATE found in {}'.format(cert))
                certificate = open(cert, 'rb')
            elif cert:
                logger.error(
                    'WEBHOOK_CERTIFICATE not found in {} '.format(cert))

        token = bot_data.get('TOKEN', None)

        if not token:
            pass
        else:
            allowed_updates = bot_data.get('ALLOWED_UPDATES', None)
            timeout = bot_data.get('TIMEOUT', None)
            proxy = bot_data.get('PROXY', None)

            if self.mode == WEBHOOK_MODE:
                try:
                    if bot_data.get('MESSAGEQUEUE_ENABLED', False):
                        q = mq.MessageQueue(
                            all_burst_limit=b.get(
                                'MESSAGEQUEUE_ALL_BURST_LIMIT', 29),
                            all_time_limit_ms=b.get(
                                'MESSAGEQUEUE_ALL_TIME_LIMIT_MS', 1024))
                        if proxy:
                            request = Request(
                                proxy_url=proxy['proxy_url'],
                                urllib3_proxy_kwargs=proxy[
                                    'urllib3_proxy_kwargs'],
                                con_pool_size=b.get(
                                    'MESSAGEQUEUE_REQUEST_CON_POOL_SIZE', 8))
                        else:
                            request = Request(con_pool_size=bot_data.get(
                                'MESSAGEQUEUE_REQUEST_CON_POOL_SIZE', 8))
                        bot = MQBot(token, request=request, mqueue=q)
                    else:
                        request = None
                        if proxy:
                            request = Request(proxy_url=proxy['proxy_url'],
                                              urllib3_proxy_kwargs=proxy[
                                                  'urllib3_proxy_kwargs'])
                        bot = telegram.Bot(token=token, request=request)

                    DjangoTelegramBot.dispatchers.append(
                        Dispatcher(bot, None, workers=0))
                    hookurl = '{}/{}/{}/'.format(webhook_site, webhook_base,
                                                 token)
                    max_connections = bot_data.get('WEBHOOK_MAX_CONNECTIONS',
                                                   40)
                    setted = bot.setWebhook(hookurl,
                                            certificate=certificate,
                                            timeout=timeout,
                                            max_connections=max_connections,
                                            allowed_updates=allowed_updates)
                    webhook_info = bot.getWebhookInfo()
                    real_allowed = webhook_info.allowed_updates if webhook_info.allowed_updates else [
                        "ALL"
                    ]

                    bot.more_info = webhook_info
                    logger.info(
                        'Telegram Bot <{}> setting webhook [ {} ] max connections:{} allowed updates:{} pending updates:{} : {}'
                        .format(bot.username, webhook_info.url,
                                webhook_info.max_connections, real_allowed,
                                webhook_info.pending_update_count, setted))

                except InvalidToken:
                    logger.error('Invalid Token : {}'.format(token))
                    return
                except TelegramError as er:
                    logger.error('Error : {}'.format(repr(er)))
                    return

            else:
                try:
                    updater = Updater(token=token, request_kwargs=proxy)
                    bot = updater.bot
                    bot.delete_webhook()
                    DjangoTelegramBot.updaters.append(updater)
                    DjangoTelegramBot.dispatchers.append(updater.dispatcher)
                    DjangoTelegramBot.__used_tokens.add(token)
                except InvalidToken:
                    logger.error('Invalid Token : {}'.format(token))
                    return
                except TelegramError as er:
                    logger.error('Error : {}'.format(repr(er)))
                    return

            DjangoTelegramBot.bots.append(bot)
            DjangoTelegramBot.bot_tokens.append(token)
            DjangoTelegramBot.bot_usernames.append(bot.username)

        logger.debug('Telegram Bot <{}> set as default bot'.format(
            DjangoTelegramBot.bots[0].username))

        def module_imported(module_name, method_name, execute):
            try:
                m = importlib.import_module(module_name)
                if execute and hasattr(m, method_name):
                    logger.debug('Run {}.{}()'.format(module_name,
                                                      method_name))
                    getattr(m, method_name)()
                else:
                    logger.debug('Run {}'.format(module_name))

            except ImportError as er:
                if settings.DJANGO_TELEGRAMBOT.get('STRICT_INIT'):
                    raise er
                else:
                    logger.error('{} : {}'.format(module_name, repr(er)))
                    return False

            return True

        # import telegram bot handlers for all INSTALLED_APPS
        for app_config in apps.get_app_configs():
            if module_has_submodule(app_config.module,
                                    TELEGRAM_BOT_MODULE_NAME):
                module_name = '%s.%s' % (app_config.name,
                                         TELEGRAM_BOT_MODULE_NAME)
                if module_imported(module_name, 'main', True):
                    logger.info('Loaded {}'.format(module_name))

        num_bots = len(DjangoTelegramBot.__used_tokens)
        if self.mode == POLLING_MODE and num_bots > 0:
            logger.info(
                'Please manually start polling update for {0} bot{1}. Run command{1}:'
                .format(num_bots, 's' if num_bots > 1 else ''))
            for token in DjangoTelegramBot.__used_tokens:
                updater = DjangoTelegramBot.get_updater(bot_id=token)
                logger.info('python manage.py botpolling --username={}'.format(
                    updater.bot.username))
Example #5
0
# @handler
# def video_markup_callback(update: Update, context, user, chat, message, _user):
#     query: telegram.CallbackQuery = update.callback_query
#     if query.data == 'DELETE':
#         context.bot.delete_message(chat_id=chat.id, message_id=query.message.message_id)
#     elif query.data.startswith("DOWNLOAD:"):
#         video_id = query.data[9:]
#         video_url = f'http://youtu.be/{video_id}'
#         downloaded_audio_from_video(update=update, context=context, user=user, video_url=video_url,
#                                     chat=chat, message=query.message, _user=_user)

if __name__ == '__main__':
    try:

        q = messagequeue.MessageQueue(all_burst_limit=20,
                                      all_time_limit_ms=1100)
        request = Request(con_pool_size=8)
        bot = MQBot(os.environ.get("BOT_TOKEN"), request=request, mqueue=q)
        updater = Updater(bot=bot, use_context=True)
        dispatcher = updater.dispatcher

        dispatcher.add_handler(CommandHandler("start", start))
        dispatcher.add_handler(
            MessageHandler(Filters.regex(re.compile(youtube_regex)),
                           youtube_link))
        # dispatcher.add_handler(MessageHandler(Filters.regex(re.compile(youtube_playlist_regex)), youtube_playlist))
        # updater.dispatcher.add_handler(CallbackQueryHandler(video_markup_callback))
        dispatcher.add_handler(MessageHandler(Filters.all, unknown))
        updater.start_polling()
    except telegram.error.TimedOut:
        print("TIMEOUT!!!")
Example #6
0
def main():
    # Setup logging
    logging.getLogger("pdfminer").setLevel(logging.WARNING)
    logging.getLogger("ocrmypdf").setLevel(logging.WARNING)
    redirect_logging()
    format_string = "{record.level_name}: {record.message}"
    StreamHandler(sys.stdout, format_string=format_string,
                  level="INFO").push_application()
    log = Logger()

    q = mq.MessageQueue(all_burst_limit=3, all_time_limit_ms=3000)
    request = Request(con_pool_size=8)
    pdf_bot = MQBot(TELE_TOKEN, request=request, mqueue=q)

    # Create the EventHandler and pass it your bot's token.
    updater = Updater(
        bot=pdf_bot,
        use_context=True,
        request_kwargs={
            "connect_timeout": TIMEOUT,
            "read_timeout": TIMEOUT
        },
    )

    def stop_and_restart():
        updater.stop()
        os.execl(sys.executable, sys.executable, *sys.argv)

    def restart(_):
        Thread(target=stop_and_restart).start()

    job_queue = updater.job_queue
    job_queue.run_repeating(restart, interval=dt.timedelta(minutes=30))

    # Get the dispatcher to register handlers
    dispatcher = updater.dispatcher

    # General commands handlers
    dispatcher.add_handler(CommandHandler("start", start_msg, run_async=True))
    dispatcher.add_handler(CommandHandler("help", help_msg, run_async=True))
    dispatcher.add_handler(CommandHandler("setlang", send_lang,
                                          run_async=True))
    dispatcher.add_handler(
        CommandHandler("support", send_support_options, run_async=True))
    dispatcher.add_handler(
        CommandHandler("send", send_msg, Filters.user(DEV_TELE_ID)))
    dispatcher.add_handler(
        CommandHandler("stats", get_stats, Filters.user(DEV_TELE_ID)))

    # Callback query handler
    dispatcher.add_handler(
        CallbackQueryHandler(process_callback_query, run_async=True))

    # Payment handlers
    dispatcher.add_handler(
        MessageHandler(Filters.reply & TEXT_FILTER,
                       receive_custom_amount,
                       run_async=True))
    dispatcher.add_handler(
        PreCheckoutQueryHandler(precheckout_check, run_async=True))
    dispatcher.add_handler(
        MessageHandler(Filters.successful_payment,
                       successful_payment,
                       run_async=True))

    # URL handler
    dispatcher.add_handler(
        MessageHandler(Filters.entity(MessageEntity.URL),
                       url_to_pdf,
                       run_async=True))

    # PDF commands handlers
    dispatcher.add_handler(compare_cov_handler())
    dispatcher.add_handler(merge_cov_handler())
    dispatcher.add_handler(photo_cov_handler())
    dispatcher.add_handler(text_cov_handler())
    dispatcher.add_handler(watermark_cov_handler())

    # PDF file handler
    dispatcher.add_handler(file_cov_handler())

    # Feedback handler
    dispatcher.add_handler(feedback_cov_handler())

    # Log all errors
    dispatcher.add_error_handler(error_callback)

    # Start the Bot
    if APP_URL is not None:
        updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TELE_TOKEN)
        updater.bot.set_webhook(APP_URL + TELE_TOKEN)
        log.notice("Bot started webhook")
    else:
        updater.start_polling()
        log.notice("Bot started polling")

    # Run the bot until the you presses Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()
Example #7
0
def main():
    mybot = Updater(settings.API_KEY)

    # Инициализируем MessageQueue
    mybot.bot._msg_queue = mq.MessageQueue()
    mybot.bot._is_messages_queued_default = True

    logging.info('Бот запускается')

    dp = mybot.dispatcher

    mybot.job_queue.run_repeating(send_updates, interval=5)

    anketa = ConversationHandler(entry_points=[
        RegexHandler('^(Заполнить анкету)$', anketa_start, pass_user_data=True)
    ],
                                 states={
                                     'name': [
                                         MessageHandler(Filters.text,
                                                        anketa_get_name,
                                                        pass_user_data=True)
                                     ],
                                     'rating': [
                                         RegexHandler(('^(1|2|3|4|5)$'),
                                                      anketa_rating,
                                                      pass_user_data=True)
                                     ],
                                     'comment': [
                                         MessageHandler(Filters.text,
                                                        anketa_comment,
                                                        pass_user_data=True),
                                         CommandHandler('skip',
                                                        anketa_skip_comment,
                                                        pass_user_data=True)
                                     ]
                                 },
                                 fallbacks=[
                                     MessageHandler(Filters.text,
                                                    dontknow,
                                                    pass_user_data=True)
                                 ])

    dp.add_handler(CommandHandler('start', greet_user, pass_user_data=True))
    dp.add_handler(anketa)

    dp.add_handler(CommandHandler('cat', send_cat_picture,
                                  pass_user_data=True))
    dp.add_handler(
        RegexHandler('^(Прислать котика)$',
                     send_cat_picture,
                     pass_user_data=True))
    dp.add_handler(
        RegexHandler('^(Сменить аватарку)$',
                     change_avatar,
                     pass_user_data=True))

    dp.add_handler(
        MessageHandler(Filters.contact, get_contact, pass_user_data=True))
    dp.add_handler(
        MessageHandler(Filters.location, get_location, pass_user_data=True))
    dp.add_handler(CommandHandler('subscribe', subscribe))
    dp.add_handler(CommandHandler('unsubscribe', unsubscribe))
    dp.add_handler(
        MessageHandler(Filters.photo, check_user_photo, pass_user_data=True))

    dp.add_handler(
        MessageHandler(Filters.text, talk_to_me, pass_user_data=True))

    mybot.start_polling()
    mybot.idle()
Example #8
0
def main():
    mybot = Updater(settings.API_KEY)
    mybot.bot._msg_queue = mq.MessageQueue()
    mybot.bot._is_messages_queued_default = True

    logging.info('БОТ ЗАПУСКАЕТСЯ')

    dp = mybot.dispatcher

    mybot.job_queue.run_repeating(send_updates, 5)

    anketa = ConversationHandler(
        entry_points=[
            RegexHandler('^(Заполнить анкету)$',
                         anketa_start,
                         pass_user_data=True)
        ],  #с чего стартует
        states={
            "name": [
                MessageHandler(Filters.text,
                               anketa_get_name,
                               pass_user_data=True)
            ],
            "rating": [
                RegexHandler('^(1|2|3|4|5)$',
                             anketa_rating,
                             pass_user_data=True)
            ],
            "comment": [
                MessageHandler(Filters.text,
                               anketa_comment,
                               pass_user_data=True),
                CommandHandler('skip',
                               anketa_skip_comment,
                               pass_user_data=True)
            ]
        },
        fallbacks=[
            MessageHandler(Filters.text, dontknow, pass_user_data=True)
        ])

    dp.add_handler(
        CommandHandler("start", greet_user,
                       pass_user_data=True))  # обрабатывает команду start
    dp.add_handler(anketa)
    dp.add_handler(CommandHandler("cat", send_cat_picture,
                                  pass_user_data=True))
    dp.add_handler(CommandHandler("wordcount", wordcount, pass_user_data=True))
    dp.add_handler(
        CommandHandler("planet", planets_constellation, pass_user_data=True))
    #    dp.add_handler(CommandHandler("cities", import_csv, pass_user_data=True))

    dp.add_handler(
        RegexHandler('^(Прислать котика)$',
                     send_cat_picture,
                     pass_user_data=True))
    dp.add_handler(
        RegexHandler('^(Сменить аватарку)$',
                     change_avatar,
                     pass_user_data=True))
    dp.add_handler(RegexHandler('^(moon)$', full_moon, pass_user_data=True))

    dp.add_handler(CallbackQueryHandler(inline_button_processed))

    dp.add_handler(
        MessageHandler(Filters.contact, get_contact, pass_user_data=True))
    dp.add_handler(
        MessageHandler(Filters.location, get_location, pass_user_data=True))
    dp.add_handler(
        MessageHandler(Filters.photo, check_user_photo, pass_user_data=True))
    dp.add_handler(CommandHandler("subscribe", subscribe))
    dp.add_handler(CommandHandler("unsubscribe", unsubscribe))

    dp.add_handler(
        CommandHandler('alarm', set_alarm, pass_args=True,
                       pass_job_queue=True))

    dp.add_handler(
        MessageHandler(
            Filters.text, talk_to_me,
            pass_user_data=True))  # обрабатывает любые текстовые сообщения

    mybot.start_polling()
    mybot.idle()
Example #9
0
        queued = True,
      )
    except Exception as e:
      text = list()
      text.append('#exception #notetelegram')
      text.append(u"Exception:\n%s" % (str(e)))
      self.send_message(
        chat_id = config.groups['admin']['debug'],
        text = '\n\n'.join(text),
        isgroup = True,
        queued = True,
      )
# for test purposes limit global throughput to 3 messages per 3 seconds
q = mq.MessageQueue(
  all_burst_limit = 3,
  all_time_limit_ms = 3000,
  exc_route = exception_callback,
)
# set connection pool size for bot 
request = Request(con_pool_size=8)
try:
  token = config.bots[os.environ['FLASK_ENV']]['token']
except:
  token = config.bots['matebot']['token']
testbot = MQBot(
  token,
  request = request,
  mqueue = q,
)
try:
  setattr(testbot, 'info', config.bots[os.environ['FLASK_ENV']]['info'])