def setup(webhook_url=None):
    """If webhook_url is not passed, run with long-polling."""
    logging.basicConfig(level=logging.WARNING)
    if webhook_url:
        bot = Bot(TOKEN)
        update_queue = Queue()
        dp = Dispatcher(bot, update_queue)
    else:
        updater = Updater(
            TOKEN)  # Create the EventHandler and pass it your bot's token.
        bot = updater.bot
        dp = updater.dispatcher  # Get the dispatcher to register handlers
        dp.add_handler(CommandHandler(
            "open", open))  # on /start command answer in Telegram
        dp.add_handler(CommandHandler(
            "bieber", bieber))  # on /help command answer in Telegram
        dp.add_handler(CallbackQueryHandler(button))

        # log all errors
        dp.add_error_handler(error)
    # Add your handlers here
    if webhook_url:
        bot.set_webhook(webhook_url=webhook_url)
        thread = Thread(target=dp.start, name='dispatcher')
        thread.start()
        return update_queue, bot
    else:
        bot.set_webhook()  # Delete webhook
        updater.start_polling()  # Start the Bot
        """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()
Пример #2
0
def run():
    from .Conversation import conv_handler, cancel

    # importing data from database
    bot_db_table = Bot_Table.objects.first()
    token = bot_db_table.token

    # initializing
    bot = Bot(token)
    update_queue = Queue()
    BotUpdateQueue().queue = update_queue
    dp = Dispatcher(bot, update_queue, use_context=True)

    if not Captain.objects.all():  # if db does not contain captains
        with open("captains.txt", "r",
                  encoding="utf-8") as in_file:  # cap1_name - cap1_id, ...
            entries = in_file.read().replace("\n", "").split(",")
        for entry in entries:
            anagraphic, id_str = entry.split(" - ")
            id = int(id_str)
            Captain.objects.create(id=id, anagraphic=anagraphic)

    dp.add_handler(CommandHandler("id", get_id))
    dp.add_handler(CallbackQueryHandler(cap_queue_callback))
    dp.add_handler(conv_handler)
    dp.add_handler(CommandHandler("stop", cancel))
    dp.add_error_handler(error)

    thread = threading.Thread(target=dp.start, name="dispatcher")
    thread.start()

    set_webhook(token)
Пример #3
0
def set_handlers(dispatcher: Dispatcher):
    start_handler = CommandHandler('start', start)
    dispatcher.add_handler(start_handler)

    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('get_menu', get_menu)],
        states={
            MENU: [MessageHandler(Filters.regex(
                '^({})$'.format('|'.join(get_places_name()))),
                button_menu)],
        },
        fallbacks=[CommandHandler('get_menu', get_menu)],
    )
    dispatcher.add_handler(conv_handler)

    caps_handler = CommandHandler('caps', caps)
    dispatcher.add_handler(caps_handler)

    inline_caps_handler = InlineQueryHandler(inline_query)
    dispatcher.add_handler(inline_caps_handler)

    collect_handler = CommandHandler('start_collect', start_collect)
    dispatcher.add_handler(collect_handler)

    stop_handler = CommandHandler('stop_collect', stop_collect)
    dispatcher.add_handler(stop_handler)

    # log all errors
    dispatcher.add_error_handler(error)

    # unknown message handler, must be the last
    unknown_handler = MessageHandler(Filters.command, unknown)
    dispatcher.add_handler(unknown_handler)
Пример #4
0
    def run(self, token, webhook_url=None):
        if webhook_url:
            bot = Bot(token)
            update_queue = Queue()
            job_queue = JobQueue(bot)
            dp = Dispatcher(bot, update_queue, job_queue=job_queue)
        else:
            updater = Updater(token)
            bot = updater.bot
            dp = updater.dispatcher

        for component in self.components.values():
            component.init(dp)

        dp.add_error_handler(self._error_handler)

        if webhook_url:
            bot.set_webhook(webhook_url=webhook_url)
            job_queue.start()
            thread = Thread(target=dp.start, name='dispatcher')
            thread.start()
            return update_queue, bot
        else:
            bot.set_webhook()
            updater.start_polling()
            updater.idle()
Пример #5
0
class BotComm(object):
    exposed = True

    def __init__(self, TOKEN, NAME):
        super(BotComm, self).__init__()
        self.TOKEN = TOKEN
        self.NAME=NAME
        self.bot = telegram.Bot(self.TOKEN)
        try:
            self.bot.setWebhook("https://{}.herokuapp.com/{}".format(self.NAME, self.TOKEN))
        except:
            raise RuntimeError("Failed to set the webhook")

        self.update_queue = Queue()
        self.dp = Dispatcher(self.bot, self.update_queue)

        self.dp.add_handler(CommandHandler("start", self._start))
        self.dp.add_handler(MessageHandler(Filters.text, self._echo))
        self.dp.add_error_handler(self._error)

    @cherrypy.tools.json_in()
    def POST(self, *args, **kwargs):
        update = cherrypy.request.json
        update = telegram.Update.de_json(update, self.bot)
        self.dp.process_update(update)

    def _error(self, error):
        cherrypy.log("Error occurred - {}".format(error))

    def _start(self, bot, update):
        update.effective_message.reply_text("Hi!")


    def _echo(self, bot, update):
        update.effective_message.reply_text(update.effective_message.text)
Пример #6
0
class Bot(BotCommand):
    def __init__(self, token=None):
        super().__init__()
        self.TOKEN = token or os.environ.get('TOKEN')
        self.telegram_bot = telegram.Bot(token=self.TOKEN)
        update_queue = Queue()
        self.dp = Dispatcher(self.telegram_bot, update_queue)

        self.dp = self.add_update_handlers(self.dp)

        # log all errors
        self.dp.add_error_handler(error)

    def add_update_handlers(self, dp):
        # Create the EventHandler and pass it your bot's token.
        # on different commands - answer in Telegram
        dp.add_handler(CommandHandler("start", self.start))
        dp.add_handler(RegexHandler('^(Понедельник|Вторник|Среда|Четверг|Пятница|Суббота)$',
                                    self.regular_choice))
        dp.add_handler(RegexHandler('^Скрыть$', self.done))
        dp.add_handler(CommandHandler("help", self.help_message))
        dp.add_handler(CommandHandler("set", self.set_group, pass_args=True))
        dp.add_handler(CommandHandler("week", self.lessons_week, pass_args=True))
        dp.add_handler(CommandHandler("nextweek", self.lessons_next_week, pass_args=True))
        dp.add_handler(CommandHandler("full", self.full_weeks, pass_args=True))
        dp.add_handler(CommandHandler("today", self.lessons_today, pass_args=True))
        dp.add_handler(CommandHandler("tomorrow", self.lessons_tomorrow, pass_args=True))
        dp.add_handler(CommandHandler(["timetable", "tt"], self.call_schedule))
        dp.add_handler(CommandHandler("weeknumber", self.week_number))
        dp.add_handler(CommandHandler("exams", self.exams, pass_args=True))
        dp.add_handler(CommandHandler('keyboard', self.keyboard_mode))

        return dp
Пример #7
0
def configure_bot(dispatcher: Dispatcher):
    dispatcher.add_handler(CommandHandler("start", start))
    dispatcher.add_handler(CommandHandler("help", help_command))

    create_listener_hand = ConversationHandler(
        entry_points=[CommandHandler('create_listener', create_listener)],
        states={
            ENTER_DESCRIPTION: [
                MessageHandler(Filters.text & ~Filters.command,
                               create_listener_get_description)
            ],
        },
        fallbacks=[CommandHandler('cancel', cancel)])
    dispatcher.add_handler(create_listener_hand)

    disable_listener_hand = ConversationHandler(
        entry_points=[CommandHandler('disable_listener', disable_listener)],
        states={
            DISABLE_LISTENER:
            [CallbackQueryHandler(disable_get_listener_name)],
        },
        fallbacks=[CommandHandler('cancel', cancel)])
    dispatcher.add_handler(disable_listener_hand)

    dispatcher.add_error_handler(error)
Пример #8
0
def reply_text(bot, update):
	intent, reply = get_reply(update.message.text, update.message.chat_id)
	if intent == "get_news":
		articles = fetch_news(reply)
		for articles in articles:
		bot.send_message(chat_id=update.message.chat_id, text=article)
	else:
		bot.send_message(chat_id=update.message.chat_id, text=reply)

def echo_sticker(bot, update):
	bot.send_sticker(chat_id=update.message.chat_id, sticker=update.message.sticker.file_id)

def error(bot, update):
	logger.error("Update '%s' caused error '%s'", update, update.error)

# def message_handler(update, context: CallbackContext):
#  	update.message.reply_text(text)

bot = Bot(TOKEN)
try:
	bot.set_webhook("https://48c9acd55480.ngrok.io/" + TOKEN)
except Exception as e:
	print(e)
	
dp = Dispatcher(bot, None)
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", _help))
dp.add_handler(CommandHandler("news", news))
dp.add_handler(MessageHandler(Filters.text, reply_text))
dp.add_handler(MessageHandler(Filters.sticker, echo_sticker))
dp.add_error_handler(error)

if __name__ == "__main__":
	app.run(port=8443)
def setup(webhook_url=None):
    """If webhook_url is not passed, run with long-polling."""
    logging.basicConfig(level=logging.WARNING)
    if webhook_url:
        bot = Bot(TOKEN)
        update_queue = Queue()
        dp = Dispatcher(bot, update_queue)
    else:
        updater = Updater(TOKEN)
        bot = updater.bot
        dp = updater.dispatcher
        dp.add_handler(CommandHandler("start", start))
        dp.add_handler(CommandHandler("help", help))

        # on noncommand i.e message - echo the message on Telegram
        dp.add_handler(MessageHandler(Filters.text, echo))

        # log all errors
        dp.add_error_handler(error)
    # Add your handlers here
    if webhook_url:
        bot.set_webhook(webhook_url=webhook_url)
        thread = Thread(target=dp.start, name='dispatcher')
        thread.start()
        return update_queue, bot
    else:
        bot.set_webhook()  # Delete webhook
        updater.start_polling()
        updater.idle()
Пример #10
0
def run(message):

    bot = Bot(config.bot_token)
    dp = Dispatcher(bot, None, workers=0)

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("ranking", ranking, pass_args=True))
    dp.add_handler(CommandHandler("players", players, pass_args=True))
    dp.add_handler(CommandHandler("player", player, pass_args=True))
    dp.add_handler(CommandHandler("matchday", matchday, pass_args=True))
    dp.add_handler(CommandHandler("scorers", scorers))
    dp.add_handler(CommandHandler("help", help))
    dp.add_handler(
        CommandHandler('info', info,
                       filters=Filters.user(username='******')))

    # on noncommand i.e message - echo the message on Telegram
    dp.add_handler(MessageHandler(Filters.text, echo))

    # log all errors
    dp.add_error_handler(error)

    # inline
    inline_handler = InlineQueryHandler(inline)
    dp.add_handler(inline_handler)

    # decode update and try to process it
    update = Update.de_json(message, bot)
    dp.process_update(update)
Пример #11
0
class BotComm(object):
    exposed = True

    def __init__(self, TOKEN, NAME):
        super(BotComm, self).__init__()
        self.TOKEN = TOKEN
        self.NAME = NAME
        self.bot = telegram.Bot(self.TOKEN)
        try:
            self.bot.setWebhook("https://{}.herokuapp.com/{}".format(
                self.NAME, self.TOKEN))
        except:
            raise RuntimeError("Failed to set the webhook")

        self.update_queue = Queue()
        self.dp = Dispatcher(self.bot, self.update_queue)

        self.dp.add_handler(CommandHandler("start", self._start))
        self.dp.add_handler(MessageHandler(Filters.text, self._handler))
        self.dp.add_error_handler(self._error)

    @cherrypy.tools.json_in()
    def POST(self, *args, **kwargs):
        update = cherrypy.request.json
        update = telegram.Update.de_json(update, self.bot)
        self.dp.process_update(update)

    def _error(self, error):
        cherrypy.log("Error occurred - {}".format(error))

    def _start(self, bot, update):
        update.effective_message.reply_text("Hi!")

    def _handler(self, bot, update):
        global TOPIC
        global TOPIC_STATUS
        print("MESSAGE", update.message.chat_id, update.message.text)
        if update.message.text == 'kb' or update.message.text == 'keyboard':
            send_KB_()
        elif text_ON in update.message.text and text_topic[
                0] in update.message.text:
            mqttc.publish(TOPIC[0], "ON", 0, True)
            TOPIC_CHANGES[0] = 1
        elif text_OFF in update.message.text and text_topic[
                0] in update.message.text:
            mqttc.publish(TOPIC[0], "OFF", 0, True)
            TOPIC_CHANGES[0] = 1
        elif text_ON in update.message.text and text_topic[
                1] in update.message.text:
            mqttc.publish(TOPIC[1], "ON", 0, True)
            TOPIC_CHANGES[1] = 1
        elif text_OFF in update.message.text and text_topic[
                1] in update.message.text:
            mqttc.publish(TOPIC[1], "OFF", 0, True)
            TOPIC_CHANGES[1] = 1
        else:
            update.message.reply_text(text=update.message.text)
Пример #12
0
def register_handlers(dp: Dispatcher):
    for command in text_handlers:
        dp.add_handler(
            MessageHandler(Filters.regex('^/{}$'.format(command)),
                           text_handlers[command]))

    dp.add_handler(MessageHandler(Filters.text, default_handler))

    # log all errors
    dp.add_error_handler(error_handler)
Пример #13
0
def add_handlers(dispatcher: Dispatcher):
    for cmd in ALL:
        log.debug('Register command `%s`', cmd.__name__)
        dispatcher.add_handler(getattr(cmd, 'handler'))

        error = getattr(cmd, 'error_handler', None)

        if error is not None:
            log.debug('Register error handler `%s`', error.__name__)
            dispatcher.add_error_handler(error)
Пример #14
0
class BotDispatcher:
    def __init__(self):
        self.dispatcher = Dispatcher(bot, None, workers=0)
        self.dispatcher.add_handler(CommandHandler('start', start))
        self.dispatcher.add_handler(CommandHandler('help', help))
        self.dispatcher.add_handler(CallbackQueryHandler(button))
        self.dispatcher.add_error_handler(error)

    def process_update(self, update):
        self.dispatcher.process_update(update)
Пример #15
0
def add_error_handlers(dispatcher: Dispatcher) -> bool:
    # Add error handlers
    try:
        dispatcher.add_error_handler(error)

        return True
    except Exception as e:
        logger.warning(f"Add error handlers error: {e}", exc_info=True)

    return False
Пример #16
0
def handle_request(bot, update):
    dispatcher = Dispatcher(bot, None)
    dispatcher.add_handler(CommandHandler('start', start))
    dispatcher.add_handler(CommandHandler('help', help))
    dispatcher.add_handler(CommandHandler('subscribe', subscribe))
    dispatcher.add_handler(CommandHandler('unsubscribe', unsubscribe))
    dispatcher.add_handler(CallbackQueryHandler(button))
    dispatcher.add_error_handler(error)
    dispatcher.add_handler(MessageHandler(Filters.command, unknown))
    dispatcher.process_update(update)
Пример #17
0
 def add_handlers(self, dispatcher: Dispatcher) -> None:
     """Adds all ValeVistaBot handlers to 'dispatcher'."""
     dispatcher.add_handler(CommandHandler("start", self.start))
     dispatcher.add_handler(CommandHandler("set", self.set_rut))
     dispatcher.add_handler(CommandHandler("get", self.get_rut))
     dispatcher.add_handler(CommandHandler("debug", self.debug))
     dispatcher.add_handler(CommandHandler("help", self.help))
     dispatcher.add_handler(CommandHandler("subscribe", self.subscribe))
     dispatcher.add_handler(CommandHandler("unsubscribe", self.unsubscribe))
     dispatcher.add_handler(MessageHandler(Filters.text, self.msg))
     dispatcher.add_error_handler(self.error)
Пример #18
0
def add_handlers(dp: Dispatcher):
    for list_of_handlers in list_of_list_of_handlers:
        for handler in list_of_handlers:
            if len(handler) == 1:
                dp.add_handler(handler[0])
            elif len(handler) == 2:
                if isinstance(handler[1], int):
                    dp.add_handler(handler[0], handler[1])
                elif isinstance(handler[1], str):
                    if handler[1] == 'error':
                        dp.add_error_handler(handler[0])
Пример #19
0
def add_handlers(dp:Dispatcher):
    dp.add_error_handler(hs.error_handler)
    dp.add_handler(CommandHandler("salambrat",hs.greeting_message_handler))
    dp.add_handler(CommandHandler("eledoyulyeti",hs.confirm_bro_handler))
    dp.add_handler(CommandHandler("meneoyret",hs.improve_confirm_bro_handler))
    dp.add_handler(CommandHandler("musuqu",hs.music_handler))
    dp.add_handler(CommandHandler("musuquoyret",hs.improve_music_handler))
    dp.add_handler(CommandHandler("meme",hs.random_meme_handler))
    dp.add_handler(CommandHandler("info",hs.info_handler))

    schedule.every(10).minutes.do(reset_all_spam_counts)
Пример #20
0
class BotComm:
    exposed = True

    def __init__(self, TOKEN, NAME):
        super(BotComm, self).__init__()
        self.TOKEN = TOKEN
        self.NAME = NAME
        self.bot = telegram.Bot(self.TOKEN)
        try:
            self.bot.setWebhook("https://{}.herokuapp.com/{}".format(
                self.NAME, self.TOKEN))
        except:
            raise RuntimeError("Failed to set the webhook")

        self.update_queue = Queue()
        self.dp = Dispatcher(self.bot, self.update_queue)

        self.dp.add_handler(CommandHandler("start", self._start))
        self.dp.add_handler(MessageHandler(Filters.text, self._process_update))
        self.dp.add_error_handler(self._error)

    @cherrypy.tools.json_in()
    def POST(self, *args, **kwargs):
        update = cherrypy.request.json
        update = telegram.Update.de_json(update, self.bot)
        self.dp.process_update(update)

    def _error(self, error):
        cherrypy.log("Error occurred - {}".format(error))

    def _start(self, bot, update):
        update.effective_message.reply_text(
            'Милые девушки. Этот бот создан специально для вас. Сделайте заказ, например, "латте без сахара" или "черный чай с одним кусочком сахара и печенькой". А мы обеспечим оперативную доставку вашего желания прямо на ваше рабочее место'
        )

    def _accept_order(self, bot, update):
        order_text = update.effective_message.text
        order_user = update.effective_message.from_user
        order_user_first_name = order_user.first_name
        order_user_last_name = order_user.last_name
        order_user_username = order_user.username
        text = "{first_name} {last_name} ({username}) " \
               "желает: {order}".format(first_name=order_user_first_name,
                                        last_name=order_user_last_name,
                                        username=order_user_username,
                                        order=order_text)
        self.bot.send_message(chat_id=CHAT_ID, text=text)
        update.effective_message.reply_text("Ваш заказ принят!")

    def _process_update(self, bot, update):
        chat_id = update.effective_message.chat.id
        if not chat_id == CHAT_ID:
            self._accept_order(bot, update)
Пример #21
0
def get_handler():
    bot = Bot(token=BOT_TOKEN)
    dp = Dispatcher(bot, None, workers=0)
    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))

    dp.add_handler(InlineQueryHandler(inlinequery))

    # log all errors
    dp.add_error_handler(error)

    return dp, bot
Пример #22
0
def setup():
    '''GAE DISPATCHER SETUP'''

    global dispatcher
    dispatcher = Dispatcher(bot=bot, update_queue=None, workers=0)

    # ---Register handlers here---
    dispatcher.add_handler(InlineQueryHandler(parseInlineQuery))

    dispatcher.add_error_handler(error)

    return dispatcher
Пример #23
0
def setup(webhook_url=None):
    """If webhook_url is not passed, run with long-polling."""
    logging.basicConfig(level=logging.WARNING)
    if webhook_url:
        bot = Bot(TOKEN)
        update_queue = Queue()
        dp = Dispatcher(bot, update_queue)
    else:
        updater = Updater(TOKEN)
        bot = updater.bot
        dp = updater.dispatcher
        dp.add_handler(CommandHandler("start", start))
        dp.add_handler(CommandHandler("help", help))
        dp.add_handler(CommandHandler("new_room", new_room, pass_args=True))
        dp.add_handler(CommandHandler("new_bet", new_bet))
        dp.add_handler(CommandHandler("remove_bet", remove_bet,
                                      pass_args=True))
        dp.add_handler(CommandHandler("join", join_room, pass_args=True))
        dp.add_handler(CommandHandler("bets", show_bets))
        dp.add_handler(CommandHandler("close_bet", close_bet, pass_args=True))
        dp.add_handler(CommandHandler("open_bet", open_bet, pass_args=True))
        dp.add_handler(
            CommandHandler("submit_result", submit_result, pass_args=True))
        dp.add_handler(CommandHandler("pred", modify_bet, pass_args=True))
        dp.add_handler(CommandHandler("refill", refill_bets))
        dp.add_handler(CommandHandler("show", show_predictions,
                                      pass_args=True))
        dp.add_handler(CommandHandler("score_board", score_board))
        dp.add_handler(CommandHandler("members", show_members))
        dp.add_handler(CommandHandler("description", set_desc))
        dp.add_handler(CommandHandler("delete_room", delete_room))
        dp.add_handler(CommandHandler("hack", hack, pass_args=True))
        dp.add_handler(CommandHandler("hack_score", hack_score,
                                      pass_args=True))
        dp.add_handler(CommandHandler("hack_start", hack_start,
                                      pass_args=True))
        # # on noncommand i.e message - echo the message on Telegram

        dp.add_handler(MessageHandler(Filters.text, echo))

        # log all errors
        dp.add_error_handler(error)
    # Add your handlers here
    if webhook_url:
        bot.set_webhook(webhook_url=webhook_url)
        thread = Thread(target=dp.start, name='dispatcher')
        thread.start()
        return update_queue, bot
    else:
        bot.set_webhook()  # Delete webhook
        updater.start_polling()
        updater.idle()
def setup():
    '''GAE DISPATCHER SETUP'''

    global dispatcher
    # Note that update_queue is setted to None and
    # 0 workers are allowed on Google app Engine (If not-->Problems with multithreading)
    dispatcher = Dispatcher(bot=bot, update_queue=None, workers=0)

    # ---Register handlers here---
    dispatcher.add_handler(CommandHandler("start", start))
    dispatcher.add_handler(CommandHandler("help", help))
    dispatcher.add_handler(MessageHandler([Filters.text], echo))
    dispatcher.add_error_handler(error)

    return dispatcher
Пример #25
0
class TelegramFlask:
    def __init__(self, app=None):
        self.app = app
        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        self.create_bot(app)
        app.extensions["telegram"] = self

    def create_bot(self, app):
        token = app.config.get("API_TOKEN")
        autodiscovery(app.config.get("APPS", []))
        self.bot = telegram.Bot(token=token)
        self.dispatcher = Dispatcher(self.bot, None, workers=0)
        for handler in get_handlers():
            self.dispatcher.add_handler(handler)
        # log all errors
        self.dispatcher.add_error_handler(self.error)

    def setup_webhook(self, app):
        domain = app.config.get("WEBHOOK_DOMAIN")
        path = app.config.get("WEBHOOK_PATH")
        webhook_url = f"https://{domain}/{path}"
        try:
            response = self.bot.get_webhook_info()
        except Exception:
            return False, "Unable to get telegram webhook"

        if response.url == webhook_url:
            return False, f"Keeping the same webhook url: {webhook_url}"

        try:
            success = self.bot.set_webhook(webhook_url)
        except Exception:
            return False, "Unable to set telegram webhook"

        if not success:
            return False, f"Unable to set telegram webhook, return: {success}"

        return True, f"Change webhook to the new url: {webhook_url}"

    @staticmethod
    def error(bot, update, error):
        """Log Errors caused by Updates."""
        logger.warning('Update "%s" caused error "%s"', update, error)
Пример #26
0
def init_handlers(dispatcher: Dispatcher) -> None:
    """
    Initializes all handlers for the bot.
    The handlers for the subscribe, unsubscribe and start command will be initialized in every case.
    The handlers for the survey and help command and for the end-survey-reminder callback will be only initialized,
    if the associated fields in the config are set to 'True'.
    If time-calculation is enabled the subscribe handler is an entry point in a conversation handler.
    This conversation handler handles the wakeup time query.

    :param dispatcher: The Dispatcher instance from the Updater
    :return: None
    """
    global conversation_handler
    subscribe_handler = CommandHandler("subscribe", subscribe)
    dispatcher.add_handler(CommandHandler("unsubscribe", unsubscribe))
    dispatcher.add_handler(CommandHandler("start", start))
    if config_handler.config.help.helpEnabled:
        dispatcher.add_handler(CommandHandler("help", send_help))
    if config_handler.config.surveyCommandEnabled:
        dispatcher.add_handler(CommandHandler("survey", send_survey))
    if config_handler.config.endSurveyReminderEnabled:
        dispatcher.add_handler(
            CallbackQueryHandler(handle_end_survey_reminder_callback))
    if config_handler.config.useTimeCalculation or config_handler.config.participantsEnterCondition:
        states: Dict[int, List[Handler]] = {}
        if config_handler.config.participantsEnterCondition:
            regex_str = "^[0-%d]$" % (config_handler.get_condition_count() - 1)
            regex_handler_condition = MessageHandler(Filters.regex(regex_str),
                                                     subscribe_condition)
            states[CONDITION_STATE] = [regex_handler_condition]
        if config_handler.config.useTimeCalculation:
            regex_handler_wakeup = MessageHandler(
                Filters.regex("^(0[0-9]|1[0-9]|2[0-3]|[0-9]):[0-5][0-9]$"),
                subscribe_wakeup_time)
            states[TIME_STATE] = [regex_handler_wakeup]
        conversation_handler = ConversationHandler(
            entry_points=[subscribe_handler],
            states=states,
            fallbacks=[
                MessageHandler(Filters.all, subscribe_wakeup_time_fallback)
            ])
        dispatcher.add_handler(conversation_handler)
    else:
        dispatcher.add_handler(subscribe_handler)
    dispatcher.add_error_handler(error)
Пример #27
0
 def setup(self, webhook_url=None):
     """If webhook_url is not passed, run with long-polling."""
     logging.basicConfig(level=logging.WARNING)
     if webhook_url:
         self.bot = Bot(self.bot_token)
         update_queue = Queue()
         dp = Dispatcher(self.bot, update_queue)
     else:
         updater = Updater(self.bot_token)
         self.bot = updater.bot
         dp = updater.dispatcher
         dp.add_handler(CommandHandler('help', self.help))
         dp.add_handler(CommandHandler('start', self.start))
         dp.add_handler(CommandHandler('ongoing', self.competitions.ongoing))
         dp.add_handler(CommandHandler('givememydb', self.admin.givememydb))
         dp.add_handler(CommandHandler('getcfjson', self.admin.getcfjson))
         dp.add_handler(CommandHandler('adminhandle', self.admin.adminhandle))
         dp.add_handler(CommandHandler('adminud', self.adminupdate))
         dp.add_handler(CommandHandler('adminuq', self.admqupd))
         dp.add_handler(self.cf.conv_handler10)
         dp.add_handler(self.cc.conv_handler)
         dp.add_handler(self.competitions.conv_handler)
         dp.add_handler(self.competitions.conv_handler1)
         dp.add_handler(self.register.conv_handler)
         dp.add_handler(self.compiler.conv_handler)
         dp.add_handler(self.unregister.conv_handler)
         dp.add_handler(self.ques_of_the_day.conv_handler)
         dp.add_handler(self.ques_of_the_day.conv_handler1)
         dp.add_handler(self.ranklist.conv_handler)
         dp.add_handler(self.update.conv_handler)
         dp.add_handler(self.geeks_for_geeks.conv_handler)
         dp.add_handler(self.admin.conv_handler1)
         dp.add_handler(self.admin.conv_handler2)
         dp.add_handler(self.conv_handler)
         # log all errors
         dp.add_error_handler(self.error_handler)
     if webhook_url:
         self.bot.set_webhook(webhook_url=webhook_url)
         thread = Thread(target=dp.start, name='dispatcher')
         thread.start()
         return update_queue, self.bot
     else:
         self.bot.set_webhook()  # Delete webhook
         updater.start_polling()
         updater.idle()
Пример #28
0
class MyBot:
    def __init__(self):
        self.bot = telegram.Bot(TOKEN)
        self.codes = dict()
        self.dispatcher = Dispatcher(self.bot, None, workers=0)
        self.add_handlers()
        self.set_webhook()

    def add_handlers(self):
        self.dispatcher.add_handler(CommandHandler("start", start, pass_args=True))
        self.dispatcher.add_handler(CommandHandler("help", help_))
        self.dispatcher.add_handler(CommandHandler("gettasks", tasks))
        self.dispatcher.add_handler(MessageHandler(Filters.text, echo))
        self.dispatcher.add_error_handler(error)

    def process_msg(self, msg):
        update = telegram.update.Update.de_json(msg, self.bot)
        self.dispatcher.process_update(update)

    def send_message(self, chat_id, text):
        self.bot.sendMessage(chat_id=chat_id, text=text, disable_web_page_preview=True)

    def send_mime_msg(self, chat_id, mime_msg):
        text_msg = repr_mime_msg(mime_msg)
        if len(text_msg) > 4096:
            text_msg = "TEXT IS TOO LONG\n\n" + text_msg
            log_line("Mime message was TOO LONG!")
            while len(text_msg) > 0:
                self.bot.sendMessage(chat_id=chat_id, text=text_msg[:4000],
                                     disable_web_page_preview=True, parse_mode=telegram.ParseMode.MARKDOWN)
                text_msg = text_msg[4000:]
        self.bot.sendMessage(chat_id=chat_id, text=text_msg,
                             disable_web_page_preview=True, parse_mode=telegram.ParseMode.MARKDOWN)
        log_line("Mime message was sent!")

    def set_webhook(self):
        if not bool(self.bot.get_webhook_info().url):
            try:
                self.bot.setWebhook("https://{}.herokuapp.com/{}".format(NAME, TOKEN))
                log_line("Webhook was set")
            except telegram.error.RetryAfter:
                log_line("telegram.error.RetryAfter WAS ENCOUNTERED :(")
                sleep(2)
                self.set_webhook()
Пример #29
0
def setup(token):
    # Create bot, update queue and dispatcher instances
    pp = PicklePersistence(filename='/tmp/conversationbot')

    bot = telegram.Bot(token=token)
    dispatcher = Dispatcher(bot,
                            None,
                            workers=0,
                            use_context=True,
                            persistence=pp)

    # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],
        allow_reentry=True,
        states={
            CHOOSING: [
                MessageHandler(
                    Filters.regex('^(Возраст|Любимый цвет|Имя|Фамилия)$'),
                    regular_choice),
                MessageHandler(Filters.regex('^Что то рандомное$'),
                               custom_choice)
            ],
            TYPING_CHOICE: [MessageHandler(Filters.text, regular_choice)],
            TYPING_REPLY: [
                MessageHandler(Filters.text, received_information),
            ],
        },
        fallbacks=[
            CommandHandler('cancel', cancel),
            MessageHandler(Filters.regex('^Все$'), done)
        ],
        name='my_conversation',
        persistent=True)

    dispatcher.add_handler(conv_handler)

    # log all errors
    dispatcher.add_error_handler(error)

    show_data_handler = CommandHandler('show_data', show_data)
    dispatcher.add_handler(show_data_handler)

    return dispatcher
Пример #30
0
def setup(webhook_url=None):
    """If webhook_url is not passed, run with long-polling."""
    logging.basicConfig(level=logging.WARNING)
    if webhook_url:
        bot = Bot(TOKEN)
        update_queue = Queue()
        dp = Dispatcher(bot, update_queue)
    else:
        updater = Updater(TOKEN)
        bot = updater.bot
        dp = updater.dispatcher
        # ADMIN CONVERSATION HANDLER TO BROADCAST MESSAGES
        conv_handler1 = ConversationHandler(
            entry_points=[CommandHandler('broadcast', broadcast)],
            allow_reentry=True,
            states={BDC: [MessageHandler(Filters.text, broadcast_message)]},
            fallbacks=[CommandHandler('cancel', cancel)])
        # CONVERSATION HANDLER FOR REPLACING SQLITE DATABASE
        conv_handler2 = ConversationHandler(
            entry_points=[CommandHandler('senddb', getDb)],
            allow_reentry=True,
            states={DB: [MessageHandler(Filters.document, db)]},
            fallbacks=[CommandHandler('cancel', cancel)])
        dp.add_handler(conv_handler1)
        dp.add_handler(conv_handler2)
        dp.add_handler(CommandHandler('new', new20))
        dp.add_handler(CommandHandler('subscribe', subscribe))
        dp.add_handler(CommandHandler('unsubscribe', unsubscribe))
        dp.add_handler(CommandHandler('givememydb', givememydb))
        dp.add_handler(CommandHandler('start', start))
        dp.add_handler(CommandHandler('help', help))

        # log all errors
        dp.add_error_handler(error)
    # Add your handlers here
    if webhook_url:
        bot.set_webhook(webhook_url=webhook_url)
        thread = Thread(target=dp.start, name='dispatcher')
        thread.start()
        return update_queue, bot
    else:
        bot.set_webhook()  # Delete webhook
        updater.start_polling()
        updater.idle()