예제 #1
0
 def confirm(self, text):
     while True:
         send_message(
             text,
             reply_markup=ReplyKeyboardMarkup(
                 [[KeyboardButton("Yes"),
                   KeyboardButton("No")]]),
         )
         reply = get_next_message()
         if Filters.text("Yes").filter(reply):
             return True
         if Filters.text("No").filter(reply):
             return False
예제 #2
0
def main():
    bot_token = os.getenv("BOT_TOKEN")
    admins = os.getenv("ADMINS").split(",")

    bot = Updater(bot_token)
    # automated message forwarding
    bot.dispatcher.add_handler(
        handlers.auto_forward_messages(
            contrib_filters.text,
            contrib_filters.update.message,
            ~contrib_filters.command,
            filters.contains_job_hashtag,
            filters.contains_django_mention,
        ))
    # manual admin commands
    bot.dispatcher.add_handler(
        handlers.reply_warning_to_messages(
            contrib_filters.reply,
            contrib_filters.command,
            contrib_filters.user(username=admins),
        ))
    bot.dispatcher.add_handler(
        handlers.manual_forward_messages(
            contrib_filters.reply,
            contrib_filters.command,
            contrib_filters.user(username=admins),
            filters.forwarded_message_contains_job_hashtag,
            filters.forwarded_message_contains_django_mention,
        ))
    bot.dispatcher.add_handler(
        handlers.put_in_readonly_for_message(
            contrib_filters.reply,
            contrib_filters.command,
            contrib_filters.user(username=admins),
        ))
    # error handling
    bot.dispatcher.add_error_handler(handlers.log_errors)

    if in_heroku():
        app_name = os.getenv("HEROKU_APP_NAME")
        init_sentry()
        bot.start_webhook(
            listen="0.0.0.0",
            port=int(os.getenv("PORT")),
            url_path=bot_token,
            webhook_url=f"https://{app_name}.herokuapp.com/" + bot_token,
        )
        bot.idle()
    else:
        bot.start_polling()
예제 #3
0
    def add_task(self):
        send_message(
            "Send description for new task.",
            reply_markup=ReplyKeyboardMarkup(
                [[KeyboardButton("# CANCEL OPERATION")]]),
        )
        reply = get_next_message()
        if Filters.text("# CANCEL OPERATION").filter(reply):
            send_message("Operation cancelled.")
        else:
            new_task = Task(_tw, description=reply.text)
            send_message(task2message(new_task), parse_mode=ParseMode.HTML)
            if self.confirm("Do you want to create above task?"):
                # Dirty hack for saving
                keys = []
                for attr in new_task.__dict__['_data']:
                    if attr != 'description':
                        keys.append(attr)
                for key in keys:
                    new_task.__dict__['_data'].pop(key)

                new_task.save()
                send_message("Task saved.")
            else:
                send_message("Operation cancelled.")
예제 #4
0
    def listen(self):
        while True:
            commands = {
                "List all tasks": lambda: self.list_task(self.edit_task),
                "Add a new task": self.add_task,
            }
            keyboard = [[KeyboardButton(c) for c in commands]]
            send_message("I'm listening.",
                         reply_markup=ReplyKeyboardMarkup(keyboard))
            message = get_next_message()

            _tw_lock.acquire()
            _tw.sync()
            if (message.entities
                    and message.entities[0].type == MessageEntity.BOT_COMMAND
                    and message.entities[0].offset == 0):
                args = message.text.split()[1:]
                command = message.text[1:message.entities[0].length].split(
                    '@')[0]
                self.handle_command(command, args)
            else:
                for c in commands:
                    if Filters.text(c).filter(message):
                        commands[c]()
                        break
            _tw.sync()
            _tw_lock.release()
예제 #5
0
def main():
    """Run bot."""

    parser = arg_parser()
    storage = vars(parser.parse_args())

    updater = Updater(storage['token'])
    dispatcher = updater.dispatcher

    if storage['folder'] is None:
        imap_trace(select_email_folder, storage)()
    logging.info('Cmd line args storage: {0}'.format(storage))

    ChatFilter = Filters.chat(storage['chat'])

    dispatcher.add_handler(CommandHandler("start", start, ChatFilter))
    dispatcher.add_handler(CommandHandler("help", start, ChatFilter))
    dispatcher.add_handler(
        CommandHandler("set",
                       partial(set_timer, imap_trace(scan_email, storage)),
                       ChatFilter))
    dispatcher.add_handler(CommandHandler("unset", unset, ChatFilter))

    updater.start_polling()
    updater.idle()
예제 #6
0
    def decorator(func):
        arg: Any

        if not BotMemory.updater:
            create_bot()

        if issubclass(cls, MessageHandler) and isinstance(command, str):
            filters = kwargs.pop("filters", None)
            arg = Filters.regex(command)
            if filters:
                arg = arg & filters
            if not allow_updates:
                arg = arg & ~Filters.update.edited_message
        else:
            arg = command or func.__name__

        if not allow_updates and not issubclass(cls, MessageHandler):
            filters = kwargs.pop("filters", None)

            if filters:
                filters = filters & ~Filters.update.edited_message
            else:
                filters = ~Filters.update.edited_message
            kwargs["filters"] = filters

        BotMemory.updater.dispatcher.add_handler(cls(arg, func, **kwargs))
        return func
예제 #7
0
def add_handlers(dispatcher: tg.ext.Dispatcher):
    start_handler = tge.CommandHandler('start', start_callback)
    dispatcher.add_handler(start_handler)

    tree_handler = tge.CommandHandler('tree', tree_callback)
    dispatcher.add_handler(tree_handler)

    callback_handler = tge.CallbackQueryHandler(query_callback)
    dispatcher.add_handler(callback_handler)

    link_handler = tge.MessageHandler(
        filters=tgFilters.text &
        (tgFilters.entity(tg.MessageEntity.URL)
         | tgFilters.entity(tg.MessageEntity.TEXT_LINK)),
        callback=link_callback)
    dispatcher.add_handler(link_handler)
예제 #8
0
 def _add_handlers(self):
     self.dp.add_handler(
         CommandHandler(
             "start", self._start_chat_handler_secure, Filters.regex(self.secure_key)
         )
     )
     self.dp.add_handler(CommandHandler("start", self._start_chat_handler))
     super()._add_handlers()
예제 #9
0
def add_roll(upd: Updater, handlers_group: int):
    logger.info("registering roll handlers")
    dp = upd.dispatcher
    dp.add_handler(MessageHandler(Filters.dice, roll), handlers_group)
    dp.add_handler(
        MessageHandler(Filters.regex(MEME_REGEX), roll, run_async=True), handlers_group
    )
    dp.add_handler(
        CommandHandler(
            "gdpr_me",
            satisfy_GDPR,
            filters=Filters.chat(username=get_group_chat_id().strip("@")),
            run_async=True,
        ),
        handlers_group,
    )
    dp.add_handler(
        CommandHandler(
            "hussars",
            show_hussars,
            filters=~Filters.chat(username=get_group_chat_id().strip("@"))
            | admin_filter,
            run_async=True,
        ),
        handlers_group,
    )
    dp.add_handler(
        CommandHandler(
            "htop",
            show_active_hussars,
            filters=admin_filter
            & Filters.chat(username=get_group_chat_id().strip("@")),
            run_async=True,
        ),
        handlers_group,
    )
    dp.add_handler(
        CommandHandler(
            "wipe_hussars",
            wipe_hussars,
            filters=admin_filter
            & Filters.chat(username=get_group_chat_id().strip("@")),
            run_async=True,
        ),
        handlers_group,
    )
예제 #10
0
    def add_handlers(self):
        start_handler = CommandHandler('start', self.start)
        self.dispatcher.add_handler(start_handler)

        admin_list_users_handler = MessageHandler(Filters.regex('^LIST$'),
                                                  self.admin_list_users)
        self.dispatcher.add_handler(admin_list_users_handler)

        admin_add_user_handler = MessageHandler(Filters.regex('^ADD \d+$'),
                                                self.admin_add_user)
        self.dispatcher.add_handler(admin_add_user_handler)

        admin_delete_user_handler = MessageHandler(Filters.regex('^DEL \d+$'),
                                                   self.admin_delete_user)
        self.dispatcher.add_handler(admin_delete_user_handler)

        admin_sendtoall_handler = MessageHandler(Filters.regex('^SENDTOALL'),
                                                 self.admin_sendtoall)
        self.dispatcher.add_handler(admin_sendtoall_handler)

        mainmenu_handler = MessageHandler(Filters.regex('^main menu$'),
                                          self.start)
        self.dispatcher.add_handler(mainmenu_handler)

        openconnect_handler = MessageHandler(Filters.regex('^openconnect$'),
                                             self.openconnect)
        self.dispatcher.add_handler(openconnect_handler)

        mtproto_handler = MessageHandler(Filters.regex('^mtproto$'),
                                         self.mtproto)
        self.dispatcher.add_handler(mtproto_handler)

        openconnect_show_data_handler = \
            MessageHandler(Filters.regex('^show openconnect data$'),
                    self.openconnect_show_data)
        self.dispatcher.add_handler(openconnect_show_data_handler)

        openconnect_add_data_handler = \
            MessageHandler(Filters.regex('^add openconnect data$'),
                    self.openconnect_add_data)
        self.dispatcher.add_handler(openconnect_add_data_handler)

        user_input_handler = MessageHandler(Filters.regex('.*'),
                                            self.user_input)
        self.dispatcher.add_handler(user_input_handler)
예제 #11
0
def sendTelegramMessage():
    updater = Updater(config.TOKEN)
    # Get the dispatcher to register handlers
    dispatcher = updater.dispatcher

    # on different commands - answer in Telegram
    dispatcher.add_handler(
        CommandHandler("start", start, Filters.user(username="******")))
    dispatcher.add_handler(
        CommandHandler("stop", stop, Filters.user(username="******")))
    dispatcher.add_handler(
        CommandHandler("update", update, Filters.user(username="******")))

    # Start the Bot
    updater.start_polling()

    # Block 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()
예제 #12
0
def main():
    updater = Updater(TOKEN)
    updater.dispatcher.add_handler(CommandHandler("start", start))
    updater.dispatcher.add_handler(CommandHandler("meme", meme))
    updater.dispatcher.add_handler(CommandHandler("help", help))
    updater.dispatcher.add_handler(
        MessageHandler(Filters.chat(chat_id=chat_id_of_channel),
                       channel_message))
    updater.dispatcher.add_handler(MessageHandler(Filters.text, reply_msg))
    updater.start_polling()
    updater.idle()
예제 #13
0
 def __init__(self, dispatcher, chat_id):
     self.chat_id = chat_id
     if self.chat_id != None:
         dispatcher.add_handler(
             MessageHandler(
                 Filters.chat(self.chat_id)
                 & Filters.status_update.new_chat_members, self.new_member))
     else:
         dispatcher.add_handler(
             CommandHandler('get_chat_id', self.get_chat_id))
     dispatcher.add_error_handler(self.error)
예제 #14
0
def main():
    import json

    with open('config.json') as json_config_file:
        json_config = json.load(json_config_file)
    TELEGRAM_TOKEN = json_config['TELEGRAM_TOKEN']
    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    updater = Updater(TELEGRAM_TOKEN, use_context=True)

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

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))
    dp.add_handler(CommandHandler("get_download_history",
                                  get_download_history))
    dp.add_handler(
        MessageHandler(
            Filters.text
            & (Filters.entity(MessageEntity.URL)
               | Filters.entity(MessageEntity.TEXT_LINK)),
            get_link,
        ))
    dp.add_handler(MessageHandler(Filters.text, get_message))

    # on noncommand i.e message - echo the message on Telegram
    dp.add_handler(InlineQueryHandler(inlinequery))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Block until the user 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()
예제 #15
0
def start():
    random.seed()

    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    updater = Updater(token=config.BOT_TOKEN)
    dispatcher = updater.dispatcher
    dispatcher.add_handler(
        MessageHandler(Filters.regex("(?i).*да[^\w]*$"), message_handler))
    updater.start_polling()
예제 #16
0
def main() -> None:
	updater = Updater(token=config.TOKEN, use_context=True)
	dispatcher = updater.dispatcher
	down_handler = ConversationHandler(
		entry_points=[CommandHandler('download', download)],
		states = {
			TYPE: [MessageHandler(Filters.regex('^('+'|'.join([i for i in config.ALLOWED_TYPES])+')$'), type)],
			MAGNET: [MessageHandler(Filters.regex('^magnet*'), magnet)],
			CONFIRM: [MessageHandler(Filters.regex('^OK$'), confirm)],
		},
		fallbacks=[CommandHandler('cancel', cancel),],
	)
	dispatcher.add_handler(down_handler)
	dispatcher.add_handler(CommandHandler('start', start))
	dispatcher.add_handler(CommandHandler('status', status))
	dispatcher.add_handler(CommandHandler('clear', clear))
	dispatcher.add_handler(CommandHandler('help', help))
	dispatcher.add_handler(MessageHandler(Filters.command, unknown))

	updater.start_polling()
	updater.idle()
예제 #17
0
def add_length(upd: Updater, handlers_group: int):
    logger.info("registering length handlers")
    dp = upd.dispatcher
    dp.add_handler(
        CommandHandler(
            "length",
            _length,
            filters=Filters.chat(username=get_group_chat_id().strip("@")),
            run_async=True,
        ),
        handlers_group,
    )

    dp.add_handler(
        CommandHandler(
            "longest",
            _longest,
            filters=Filters.chat(username=get_group_chat_id().strip("@")),
            run_async=True,
        ),
        handlers_group,
    )
예제 #18
0
def main():
    dotenv.load_dotenv()
    TOKEN = os.environ["BOT_TOKEN"]
    updater = Updater(TOKEN)

    conv_handler = ConversationHandler(
        entry_points=[
            MessageHandler(
                Filters.text(Config.TELEGRAM_PRODUCT_BUTTONS +
                             Config.INSTAGRAM_PRODUCT_BUTTONS),
                product_choose_handler)
        ],
        states={
            Steps.PRODUCT_COUNT_STEP:
            [MessageHandler(Filters.text, order_confirm_handler)],
            # Steps.ORDER_CONFIRM_STEP: [MessageHandler(
            #     Filters.text,

            # )]
        },
        fallbacks=[CommandHandler('start', start_handler)])

    updater.dispatcher.add_handler(conv_handler)
    updater.dispatcher.add_handler(CommandHandler('start', start_handler))
    updater.dispatcher.add_handler(CommandHandler('cancel', start_handler))
    updater.dispatcher.add_handler(CommandHandler('help', help_command))
    updater.dispatcher.add_handler(
        MessageHandler(Filters.text(Config.MAIN_MENU_BUTTONS), button))

    updater.dispatcher.add_handler(
        MessageHandler(Filters.text(Config.PRODUCT_BUTTONS),
                       product_button_handler))

    updater.dispatcher.add_handler(
        MessageHandler(Filters.text("بازگشت به منوی اصلی ◀️"), start_handler))
    updater.dispatcher.add_handler(MessageHandler(Filters.all, help_command))
    updater.start_polling()
    updater.idle()
예제 #19
0
def _init_updater(api_token):
    # Create the Updater and pass it your bot's token.
    updater = Updater(api_token, use_context=True)

    updater.dispatcher.add_handler(
        CommandHandler('start', _start_command_handler))
    updater.dispatcher.add_handler(
        CommandHandler('help', _help_command_handler))

    updater.dispatcher.add_handler(
        MessageHandler(Filters.regex(TODO_LIST_START_REGEX),
                       _todo_list_message_handler))
    updater.dispatcher.add_handler(
        CallbackQueryHandler(_keyboard_click_handler))

    updater.dispatcher.add_error_handler(_error_handler)

    return updater
예제 #20
0
class VoteHandler(Handler):
    filter = Filters.chat(chat_id=cfg.moderation_chat)

    def handle(self, bot: Bot, update: Update, user_data, chat_data):
        data = json.loads(update.callback_query.data)
        moderator = ...
        if Moderator.select().where(Moderator.user_id == update.callback_query.
                                    from_user.id).exists():
            moderator = Moderator.select().where(
                Moderator.user_id == update.callback_query.from_user.id).peek(
                    1)
        else:
            moderator = Moderator(
                user_id=update.callback_query.from_user.id,
                username=update.callback_query.from_user.username
                or update.callback_query.from_user.first_name)
            moderator.save()
        if Vote.select().where(
                Vote.moderator == moderator,
                Vote.publication_id == data.get('publication_id'),
                Vote.points > 0).exists():
            bot.answer_callback_query(
                callback_query_id=update.callback_query.id,
                text='Вы уже голосовали',
                show_alert=False)
        else:
            vote = Vote(
                publication_id=data.get('publication_id'),
                moderator=moderator,
                date=datetime.datetime.now(),
                points=data.get('points'),
            )
            vote.save()
            bot.answer_callback_query(
                callback_query_id=update.callback_query.id,
                text='Ваш голос принят',
                show_alert=False)

    def get_handler(self):
        return CallbackQueryHandler(callback=self.handle,
                                    pass_chat_data=True,
                                    pass_groupdict=True,
                                    pass_user_data=True)
예제 #21
0
    def textHandler(self, update: Update, context: CallbackContext) -> bool:
        if update.message.migrate_to_chat_id is not None:
            self.chatmigrate(
                getchatid(update), update.message.migrate_to_chat_id)
            return True

        if Filters.status_update(update):
            return True

        self.renewStatus(update)
        if any(x in self.blacklist for x in (self.lastuser, self.lastchat)):
            return self.errorInfo("你在黑名单中,无法使用任何功能")

        for cls in self.__class__.__bases__:
            status: handleStatus = cls.textHandler(self, update, context)
            if status.blocked():
                return status.normal

        return False
예제 #22
0
def main():
    logger = Logger('finance_telebot.log', os.getenv('DEBUG') == 'true')
    logger.info('Starting Finance Bot')
    token = os.getenv('TELEGRAM_BOT_TOKEN')
    updater = Updater(token=os.getenv('TELEGRAM_BOT_TOKEN'), use_context=True)
    dispatcher = updater.dispatcher
    _init_commands(dispatcher, logger)
    _init_callbacks(dispatcher, logger)
    dispatcher.add_handler(
        MessageHandler(Filters.regex(r'^(\d+)$'), number_handler))
    dispatcher.add_handler(MessageHandler(Filters.text, text_handler))

    # register_dispatcher(dispatcher)
    # jq = updater.job_queue
    # jq.run_repeating(command.job_save_mem, 3 * 3600, 3600)
    run(updater, token)
    updater.idle()
    logger.info('Stopping Finance Bot')
    updater.stop()
예제 #23
0
def main():
    updater = Updater(token=TOKEN, use_context=True)
    dispatcher = updater.dispatcher

    # Register callback functions
    start_handler = CommandHandler('start', start)
    dispatcher.add_handler(start_handler)

    join_handler = CommandHandler('join', join)
    dispatcher.add_handler(join_handler)

    status_handler = CommandHandler('status', status)
    dispatcher.add_handler(status_handler)

    help_handler = CommandHandler('help', help)
    dispatcher.add_handler(help_handler)

    move_handler = MessageHandler(Filters.text([SCISSORS, PAPER, STONE]),
                                  handle_move)
    dispatcher.add_handler(move_handler)

    # Set up webhook/poll, depending on dev or prod mode
    if MODE == 'dev':
        # Use polling (i.e. getUpdates API method) if in development mode:
        # Periodically connects to Telegram's servers to check for new update
        LOGGER.info("Starting bot in development mode...")
        updater.start_polling()
    elif MODE == 'prod':
        # Use webhooks if in production mode:
        # Whenever a new update for our bot arrives, Telegram sends that update to a specified URL.
        LOGGER.info("Starting bot in production mode...")
        updater.start_webhook(listen='0.0.0.0', port=PORT, url_path=TOKEN)
        updater.bot.set_webhook('https://{}.herokuapp.com/{}'.format(
            HEROKU_APP_NAME, TOKEN))
        LOGGER.info("Webhook set at https://{}.herokuapp.com/<token>".format(
            HEROKU_APP_NAME))
        updater.idle()
    else:
        LOGGER.error(
            "Invalid TELEGRAM_SPS_BOT_MODE value! Should be 'dev' or 'prod'.")
        sys.exit(1)
예제 #24
0
def main(token):
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        level=logging.DEBUG)

    updater = Updater(token=read_token(token), use_context=True)
    dispatcher = updater.dispatcher

    dispatcher.add_handler(CommandHandler(['start', 'help'], help))
    dispatcher.add_handler(CommandHandler('new', new_game))
    dispatcher.add_handler(CommandHandler('go', start_game))
    dispatcher.add_handler(CommandHandler('reg', register))
    dispatcher.add_handler(
        MessageHandler(
            Filters.text([
                START_BUTTON_TEXT, WORD_EXPLAINED_BUTTON_TEXT,
                WORD_SKIPPED_BUTTON_TEXT
            ]), explain_cb))

    updater.start_polling()
    updater.idle()
예제 #25
0
class QueueLength(Handler):
    filter = Filters.chat(chat_id=cfg.moderation_chat) & Filters.command

    def handle(self, bot: Bot, update: Update):
        queue_length = publication_service.get_queue_length()
        if queue_length:
            in_hours = datetime.timedelta(
                hours=(queue_length * cfg.publication_interval / 60))
            bot.send_message(
                chat_id=update.effective_chat.id,
                reply_to_message_id=update.effective_message.message_id,
                text=
                f'Колличество постов в очереди {queue_length}\nРазмер очереди в часаx {in_hours}'
            )
        else:
            bot.send_message(
                chat_id=update.effective_chat.id,
                reply_to_message_id=update.effective_message.message_id,
                text=f'Очередь пуста, милорд :(')

    def get_handler(self):
        return CommandHandler('queue', self.handle, filters=self.filter)
예제 #26
0
def register_command(dispatcher: Dispatcher, command_name: str,
                     command_class: Type[Command], **kwargs) -> None:
    """Registers a new command.

    Args:
        dispatcher : telegram.ext.Dispatcher
            Telegram dispatcher.
        command_name : str
            Command name.
        command_class : type
            Class where the command is implemented.
        defaults : Dict[str, Any]
            Defaults arguments to be passed to the instances of that command.
        authorized_users : List[int]
            List of users authorized to call this command; if none provided, all
            users are authorized
    """
    from telecom.cmd_help import Help

    def factory(*args, **kwargs):
        cmd = command_class()
        cmd(*args, **kwargs)

    logging.debug("Registering command %s", command_name)

    Command.COMMANDS[command_name] = command_class
    Help.HELP_DICT[command_name] = command_class.__HELP__

    authorized_users = kwargs.get("authorized_users", [])
    command_filters = Filters.command
    if authorized_users:
        command_filters &= Filters.user(authorized_users)

    dispatcher.add_handler(
        CommandHandler(command_name,
                       functools.partial(factory,
                                         **(kwargs.get("defaults", {}))),
                       pass_args=True,
                       filters=command_filters))
예제 #27
0
def init():
    global tg_updater
    global tg_dispatcher
    
    timer_thread = threading.Thread(target=main_loop)
    timer_thread.start()
    
    cmd_thread = threading.Thread(target=cmd_loop)
    cmd_thread.start()
    
    start_handler = CommandHandler('start', start)
    tg_dispatcher.add_handler(start_handler)

    help_handler = CommandHandler('help', printHelp)
    tg_dispatcher.add_handler(help_handler)

    stop_handler = CommandHandler('stop', stopNotice)
    tg_dispatcher.add_handler(stop_handler)

    resume_handler = CommandHandler('resume', resumeNotice)
    tg_dispatcher.add_handler(resume_handler)

    inm_handler = CommandHandler('114514', RedTeaOnly)
    tg_dispatcher.add_handler(inm_handler)

    set_timezone_handler = ConversationHandler(
        entry_points=[CommandHandler('settimezone', set_timezone)],
        states={
            SETTING_TZ: [MessageHandler(Filters.regex('^[+-][0-9]{1,2}:00.*'), set_timezone_done), MessageHandler(~Filters.command, set_timezone_wrong_format)],
            SETTING_TZ_RETRY: [MessageHandler(~Filters.command, set_timezone)]
        },
        fallbacks=[CommandHandler('cancel', cancel_set_timezone)]
    )
    tg_dispatcher.add_handler(set_timezone_handler)
    tg_updater.start_polling()
    #tg_updater.idle()
    pass
예제 #28
0
def send_admin_msg(users, bot, update):
    if Filters.text(update.message):
        for user in users:
            bot.send_message(chat_id=user.id,
                             text=update.message.text,
                             parse_mode=ParseMode.HTML)
            sleep(1)
    elif Filters.sticker(update.message):
        for user in users:
            bot.send_sticker(chat_id=user.id,
                             sticker=update.message.sticker.file_id)
            sleep(1)
    elif Filters.photo(update.message):
        for photo in update.message.photo:
            for user in users:
                bot.send_photo(chat_id=user.id,
                               photo=photo.file_id,
                               caption=update.message.caption)
                sleep(1)
    elif Filters.video(update.message):
        for user in users:
            bot.send_video(chat_id=user.id,
                           video=update.message.video.file_id,
                           caption=update.message.caption)
            sleep(1)
    elif Filters.audio(update.message):
        for user in users:
            bot.send_audio(chat_id=user.id,
                           audio=update.message.audio.file_id,
                           caption=update.message.caption)
            sleep(SEND_SLEEP)
    elif Filters.document(update.message):
        for user in users:
            bot.send_document(chat_id=user.id,
                              document=update.message.document.file_id,
                              caption=update.message.caption)
            sleep(1)
    else:
        return
예제 #29
0
파일: app.py 프로젝트: 5l1v3r1/selfmailbot

class NonConfirmedUserFilter(BaseFilter):
    def filter(self, message: Message):
        user = get_user_instance(message.from_user, message.chat_id)
        return user.email is not None and user.is_confirmed is False


updater = Updater(token=env('BOT_TOKEN'))
dispatcher = updater.dispatcher

dispatcher.add_handler(CommandHandler('start', start))
dispatcher.add_handler(CommandHandler('reset', reset_email))
dispatcher.add_handler(
    MessageHandler(
        UserWithoutEmailFilter() & Filters.text & Filters.regex('@'),
        send_confirmation))  # looks like email, so send confirmation to it
dispatcher.add_handler(
    MessageHandler(
        NonConfirmedUserFilter() & Filters.text
        & Filters.regex('Resend confirmation email'),
        resend))  # resend confirmation email
dispatcher.add_handler(
    MessageHandler(
        NonConfirmedUserFilter() & Filters.text
        & Filters.regex('Change email'), reset_email))  # change email
dispatcher.add_handler(
    MessageHandler(
        NonConfirmedUserFilter() & Filters.text
        & Filters.regex('\w{8}\-\w{4}\-\w{4}\-\w{4}\-\w{12}'),
        confirm_email))  # confirm email
예제 #30
0
    user = user_crud.get_or_create(update.effective_user.id)
    update.message.reply_text(f'We are talking about {user.current_topic!r}')
    log.debug(f'User {update.effective_user.first_name!r} got current topic.')


def download_nltk_resources():
    nltk.download('punkt')
    nltk.download('wordnet')


updater = Updater(TOKEN)

conv_handler = ConversationHandler(
    entry_points=[
        CommandHandler('change_topic', start_change_topic),
        MessageHandler(Filters.regex(ButtonPattern.CHANGE.value),
                       start_change_topic)
    ],
    states={
        CHANGE_TOPIC: [
            CommandHandler('cancel', cancel),
            MessageHandler(Filters.regex(ButtonPattern.CANCEL.value), cancel),
            MessageHandler(Filters.text, change_topic),
        ]
    },
    fallbacks=[
        CommandHandler('cancel', cancel),
        MessageHandler(Filters.regex(ButtonPattern.CANCEL.value), cancel),
    ])

updater.dispatcher.add_handler(CommandHandler('hello', hello))