예제 #1
0
def print_unsubscribe_button(chat_id):
    buttons = [InlineKeyboardButton(text="Unsubscribe", callback_data="_STOP")]
    custom_keyboard = [buttons]
    utils.get_bot().send_message(chat_id,
                                 'To unsubscribe click the button',
                                 reply_markup=InlineKeyboardMarkup(
                                     custom_keyboard, one_time_keyboard=True))
예제 #2
0
def notify_about_termins(chat_id, buro, termin, created_at):
    """
    Checks for available termins and prints them if any
    """

    department = Buro.get_buro_by_id(buro)

    if department is None:
        return

    bot = utils.get_bot()

    appointments = worker.get_available_appointments(department, termin, user_id=str(chat_id))

    if appointments is None:
        bot.send_message(chat_id=chat_id,
                         text=f'Seems like appointment title <{termin}> is not accepted by the buro <%s> any more\n'
                              'Please check of issues on Github and create one if not reported yet '
                              '(https://github.com/okainov/munich-scripts/issues/new)\n'
                              'In the meantime, we\'ve removed this subscription in order to prevent sending '
                              'more of such useless messages :( Please come back later'
                              % department.get_name())
        job_storage.remove_subscription(chat_id)

    if len(appointments) > 0:
        for caption, date, time in appointments:
            bot.send_message(chat_id=chat_id, text='The nearest appointments at %s are on %s:\n%s' % (
                caption, date, '\n'.join(time)))
        bot.send_message(chat_id=chat_id, text='Please book your appointment here: %s' % department.get_frame_url())
        print_unsubscribe_button(chat_id)
예제 #3
0
def setup_bot(**kwargs):

    global logger
    logger = telebot.logger
    telebot.logger.setLevel(logging.DEBUG)

    bot = utils.get_bot()

    @bot.message_handler(commands=['start'])
    def start(message):

        bot.send_message(message.chat.id, const.START_TEXT)

    @bot.message_handler(func=lambda message: True)
    def message_receiver(message):

        if message.text:
            info(message.text)

        chat_id = message.chat.id

        try:

            url, time_from, time_to = Parser(message.text).all()

            try:
                stream_url = youtube_lookup(url)
            except Exception as e:
                exception(e)
                raise exceptions.InputValidationException(
                    "There was something wrong with the link you sent.")

            redis_queue.enqueue(video.download, chat_id, stream_url, time_from,
                                time_to)

            _len = len(redis_queue.jobs)
            status_text = \
                f"Your video is currently in position #{_len} in queue." \
                if _len else "Your video will start processing immediately."

            bot.send_message(chat_id,
                             f"Thank you for your request! {status_text}")

        except (
                exceptions.InputValidationException,
                exceptions.ForbiddenUserOperation,
        ) as e:
            bot.send_message(chat_id, e)

        except Exception as e:
            bot.send_message(chat_id, 'Oops! Something went wrong.')
            raise e

    bot.remove_webhook()
    bot.set_webhook(url=f'{env("WEB_APP_DOMAIN")}/{env("TELEGRAM_BOT_TOKEN")}')

    def handle_update(update):
        bot.process_new_updates([update])

    return handle_update
예제 #4
0
def main():
    """Start the bot."""
    # 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(bot=utils.get_bot(), use_context=True)
    dp = updater.dispatcher

    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("end", end))
    dp.add_handler(MessageHandler(Filters.text, echo))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    DEBUG = True if os.getenv("DEBUG") else False
    BOT_TOKEN = os.getenv("TG_TOKEN")
    if DEBUG:
        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()
    else:
        logger.info('Starting bot in production webhook mode')
        HOST_URL = os.environ.get("HOST_URL")
        if HOST_URL is None:
            logger.critical('HOST URL is not set!')
            sys.exit(-1)
        updater.start_webhook(listen="0.0.0.0",
                              port='8443',
                              url_path=BOT_TOKEN)
        updater.bot.set_webhook("https://{}/{}".format(HOST_URL, BOT_TOKEN))
예제 #5
0
def notify_about_termins(chat_id, buro, termin, created_at):
    """
    Checks for available termins and prints them if any
    """

    department = Buro.get_buro_by_id(buro)

    if department is None:
        return

    bot = utils.get_bot()

    appointments = worker.get_available_appointments(department,
                                                     termin,
                                                     user_id=str(chat_id))

    if appointments is None:
        bot.send_message(
            chat_id=chat_id,
            text=
            f'Seems like appointment title <{termin}> is not accepted by the buro <%s> any more\n'
            'Please create issue on Github (https://github.com/okainov/munich-scripts/issues/new)'
            % department.get_name())

    if len(appointments) > 0:
        for caption, date, time in appointments:
            bot.send_message(
                chat_id=chat_id,
                text='The nearest appointments at %s are on %s:\n%s' %
                (caption, date, '\n'.join(time)))
        bot.send_message(chat_id=chat_id,
                         text='Please book your appointment here: %s' %
                         department.get_frame_url())
        print_unsubscribe_button(chat_id)
예제 #6
0
def remove_subscription(chat_id, automatic=False):
    if not scheduler.get_job(chat_id):
        return
    scheduler.remove_job(chat_id)
    if automatic:
        utils.get_logger().info(
            f'[{chat_id}] Subscription removed since it\'s expired',
            extra={'user': chat_id})
        utils.get_bot().send_message(
            chat_id=chat_id,
            text=
            'Subscription was removed since it was created more than a week ago'
        )
    else:
        utils.get_logger().info(f'[{chat_id}] Subscription removed by request',
                                extra={'user': chat_id})
        utils.get_bot().send_message(chat_id=chat_id,
                                     text='You were unsubscribed successfully')
예제 #7
0
def download(chat_id, stream_url, time_from, time_to):

    try:
        video_name = str(uuid4())

        download_stream(stream_url, time_from, time_to, video_name)

        get_bot().send_video(
            chat_id, open(f'{video_name}.mp4', 'rb'), supports_streaming=True,
        )

    except Exception as e:

        get_bot().send_message(
            chat_id, 'Sorry, something was wrong with your video.')
        raise e

    finally:

        silently_delete(video_name)
예제 #8
0
def get_logs_handler(update, context):
    chat = utils.get_chat(context, update)
    chat_id = chat.effective_chat.id
    bot = utils.get_bot(context, update)
    logger.info(f'get_logs_handler -> {chat_id}')
    if utils.is_admin(chat_id):
        try:
            f = open('deliver_bot.log', 'rb')
            bot.send_document(
                chat_id=chat_id,
                document=f
            )
        except Exception as ex:
            logger.warning(f'{ex}')
예제 #9
0
def main(player_x, player_y, max_turns, map_file, map_width, map_height, fps,
         box_density, chopp_density, laptop_density, room_width, room_height,
         room_box_density, room_chopp_density, room_laptop_density, rooms,
         drunk_factor, nerd_factor, dance_frames):
    if not map_file:
        map_ = build_map(map_width,
                         map_height,
                         room_width,
                         room_height,
                         box_density=box_density,
                         chopp_density=chopp_density,
                         laptop_density=laptop_density,
                         room_box_density=room_box_density,
                         room_chopp_density=room_chopp_density,
                         room_laptop_density=room_laptop_density,
                         rooms=rooms)

    add_things_randomly(
        map_,
        {
            PLAYER_X: 1,
            PLAYER_Y: 1,
        },
    )

    game = Game(
        players={
            PLAYER_X: get_bot(player_x, PLAYER_X, player_y, map_),
            PLAYER_Y: get_bot(player_y, PLAYER_Y, player_x, map_),
        },
        max_turns=max_turns,
        map_=map_,
        visualizer=MapVisualizer(map_, fps=fps, dance_frames=dance_frames),
        drunk_factor=drunk_factor,
        nerd_factor=nerd_factor,
    )
    game.play()
예제 #10
0
def get_db_handler(update, context):
    chat = utils.get_chat(context, update)
    chat_id = chat.effective_chat.id
    bot = utils.get_bot(context, update)
    logger.info(f'get_db_handler -> {chat_id}')
    if utils.is_admin(chat_id):
        try:
            f_path = os.path.join(os.path.dirname(__file__), 'admin/db.sqlite')
            f = open(f_path, 'rb')
            bot.send_document(
                chat_id=chat_id,
                document=f
            )
        except Exception:
            pass
예제 #11
0
def main():
    """Start the bot."""
    # 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(bot=get_bot(), use_context=True)
    dp = updater.dispatcher

    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', main_handler, pass_user_data=True),
                      CommandHandler('stats', stat_handler, pass_user_data=True)],

        states={
            MAIN: [CallbackQueryHandler(main_handler, pass_user_data=True)],
            SELECTING_TERMIN_TYPE: [CallbackQueryHandler(termin_type_handler, pass_user_data=True)],
            QUERING_TERMINS: [CallbackQueryHandler(quering_termins_handler, pass_user_data=True)],
            SCHEDULE_APPOINTMENT: [CallbackQueryHandler(interval_handler, pass_user_data=True)],
            SELECT_INTERVAL: [MessageHandler(Filters.text, interval_handler)],
        },

        fallbacks=[CommandHandler('start', main_handler)],
        allow_reentry=True
    )
    dp.add_handler(conv_handler)
    dp.add_error_handler(error)

    job_storage.init_scheduler()

    # Start the Bot
    if DEBUG:
        logger.info('Starting bot in debug polling mode')
        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()
    else:
        logger.info('Starting bot in production webhook mode')
        HOST_URL = os.environ.get("HOST_URL")
        if HOST_URL is None:
            logger.critical('HOST URL is not set!')
            sys.exit(-1)
        updater.start_webhook(listen="0.0.0.0",
                              port='8443',
                              url_path=BOT_TOKEN)
        updater.bot.set_webhook("https://{}/{}".format(HOST_URL, BOT_TOKEN))
예제 #12
0
def get_report_handler(update, context):
    chat = utils.get_chat(context, update)
    chat_id = chat.effective_chat.id
    bot = utils.get_bot(context, update)
    logger.info(f'get_report_handler -> {chat_id}')

    db.export_orders_to_file()

    if utils.is_admin(chat_id):
        try:
            f = open('orders.csv', 'rb')
            bot.send_document(
                chat_id=chat_id,
                document=f
            )
        except Exception as ex:
            logger.warning(f'{ex}')
            pass
예제 #13
0
def order_cancel_handler(update, context):
    message = utils.get_message(update, context)
    bot = utils.get_bot(update, context)

    bot.delete_message(
                chat_id=message.chat_id,
                message_id=message.message_id
                )
    message.reply_text('Ваш заказ отменен')
    utils.send_message_to_admin(
        context.bot,
        f"Заказ {context.user_data['order_id']} *отменен*")
    utils.update_order_status(
        context.user_data['order_id'],
        'cancelled'
    )
    context.user_data.clear()
    return CHOOSING_CATEGORY
예제 #14
0
def order_confirm_handler(update, context):
    message = utils.get_message(update, context)
    bot = utils.get_bot(update, context)

    bot.delete_message(
                chat_id=message.chat_id,
                message_id=message.message_id
                )
    message.reply_text(
        config.text['thank_you'],
        reply_markup=utils.get_start_kb()
        )
    utils.send_message_to_admin(
        context.bot,
        f"Заказ {context.user_data['order_id']} *подтвержден*")
    utils.update_order_status(
        context.user_data['order_id'],
        'confirmed'
    )
    context.user_data.clear()

    return CHOOSING_CATEGORY
예제 #15
0
    async def unfurl(cls, triggers: [str], msg: Message) -> [Embed]:
        discord_logo = "https://cdn3.iconfinder.com/data/icons/logos-and-brands-adobe/512/91_Discord-512.png"

        embed_list = []
        for trigger in triggers:
            (guild_id, channel_id, message_id) = trigger.split("/")

            # Cast id values to int
            guild_id = int(guild_id)
            channel_id = int(channel_id)
            message_id = int(message_id)

            # Find message
            bot = utils.get_bot()
            message_channel = bot.get_channel(channel_id)
            if message_channel is None:
                return
            linked_message = await message_channel.fetch_message(message_id)
            if linked_message is None:
                return

            """ Make the Embed """
            embed = Embed()
            embed.url = f"http://discord.com/channels/{guild_id}/{channel_id}/{message_id}"
            embed.colour = EMBED_COLORS['discord']

            # Count embeds/attachments
            if len(linked_message.embeds) > 0:
                embed.add_field(name="Embeds", value=f"{len(linked_message.embeds)}", inline=True)
            if len(linked_message.attachments) > 0:
                embed.add_field(name="Attachments", value=f"{len(linked_message.attachments)}", inline=True)

            # Set image from attachments or embeds
            for attach in linked_message.attachments:
                if attach.height:  # Non-null height attribute indicates attachment is an image
                    embed.set_image(url=attach.url)
                    break
            else:
                # If the attachments didn't work, try embeds
                for message_embed in linked_message.embeds:
                    if message_embed.type == "image":
                        embed.set_image(url=message_embed.url)
                        break

            # Set message text
            text = utils.trim_to_len(linked_message.content, 2048)
            if len(text) == 0:  # If message empty, check embeds
                if len(linked_message.embeds) > 0:
                    embed_as_text = utils.embed_to_str(linked_message.embeds[0])
                    text = utils.trim_to_len(f"**Message contained embed**\n```\n{embed_as_text}\n```", 2048)
                elif embed.image.url is Embed.Empty:  # Description doesn't need to be modified if an image is attached
                    text = "```(Message was empty)```"

            embed.description = text

            # Try and use author's nickname if author is a Member object
            if isinstance(linked_message.author, Member):
                embed.title = linked_message.author.name \
                    if linked_message.author.nick is None \
                    else linked_message.author.nick
            else:
                embed.title = linked_message.author.name

            if linked_message.author.avatar_url:
                embed.set_thumbnail(url=linked_message.author.avatar_url)

            # Collapse Reactions to a single list
            if linked_message.reactions:
                react_str = " ‍ ‍ ".join(
                    [f"{reaction.emoji} **{reaction.count}**" for reaction in linked_message.reactions])
                embed.add_field(name="Reactions", value=utils.trim_to_len(react_str, 1024))

            # Add timestamp to footer
            if linked_message.edited_at:
                timestamp = linked_message.edited_at
                verb = "Edited"
            else:
                timestamp = linked_message.created_at
                verb = "Sent"
            embed.set_footer(text=f"{verb} at {timestamp.strftime('%H:%M  %Y-%m-%d')}",
                             icon_url=discord_logo)
            embed_list.append(embed)
        return embed_list