Ejemplo n.º 1
0
def message_handler(update: Update, context: CallbackContext):
    intent, reply = get_reply(update.to_dict()['message']['text'], update.to_dict()[
        'message']['chat']['id'])

    if intent == "get_news":
        articles = fetch_news(reply)
        for article in articles:
            update.message.reply_text(article['link'])
    else:
        update.message.reply_text(reply)
Ejemplo n.º 2
0
def reply(update: telegram.Update, context: telegram.ext.CallbackContext):
    print(update.to_dict())
    msg = update.effective_message
    from_user, rpl_user = get_users(msg)
    command = parse_command(context.match)

    if from_user == rpl_user:
        mention_match = mentionParser.search(command['predicate'])
        if mention_match:
            mention = mentionParser.search(msg.text).group(1)
            rpl_user = User(username=mention)
            command['predicate'] = command['predicate'][:mention_match.start()]
        else:
            mention_match = mentionParser.search(command['complement'])
            if mention_match:
                mention = mentionParser.search(msg.text).group(1)
                rpl_user = User(username=mention)
                complement = command['complement']
                complement = complement[:mention_match.start()] + complement[mention_match.end():]
                command['complement'] = complement.strip()

    if command['swap'] and (not from_user == rpl_user):
        (from_user, rpl_user) = (rpl_user, from_user)

    text = get_text(from_user, rpl_user, command)
    print(text, end='\n\n')

    update.effective_message.reply_text(text, parse_mode='HTML')
Ejemplo n.º 3
0
def error_handler(update: Update, context: CallbackContext):
    """Log the error and send a telegram message to notify the developer."""
    # Log the error before we do anything else, so we can see it even if something breaks.
    logger.error(msg="Exception while handling an update:",
                 exc_info=context.error)

    # traceback.format_exception returns the usual python message about an exception, but as a
    # list of strings rather than a single string, so we have to join them together.
    tb_list = traceback.format_exception(None, context.error,
                                         context.error.__traceback__)
    tb = ''.join(tb_list)

    message = ('An exception was raised while handling an update\n'
               '<pre>update = {}</pre>\n\n'
               '<pre>context.chat_data = {}</pre>\n\n'
               '<pre>context.user_data = {}</pre>\n\n'
               '<pre>{}</pre>').format(
                   html.escape(
                       json.dumps(update.to_dict(),
                                  indent=2,
                                  ensure_ascii=False)),
                   html.escape(str(context.chat_data)),
                   html.escape(str(context.user_data)),
                   html.escape(tb),
               )

    # Finally, send the message
    context.bot.send_message(chat_id=config["Texte"]["Developer"],
                             text=message,
                             parse_mode=ParseMode.HTML)
Ejemplo n.º 4
0
def process_comment_reply(update: Update):
    if not update.message.reply_to_message:
        return

    user = get_bot_user(update)
    if not user:
        return

    comment_url_entity = [
        entity["url"] for entity in update.message.reply_to_message.entities if
        entity["type"] == "text_link" and COMMENT_URL_RE.match(entity["url"])
    ]
    if not comment_url_entity:
        log.info(
            f"Comment url not found in: {update.message.reply_to_message.entities}"
        )
        return

    comment_id = COMMENT_URL_RE.match(comment_url_entity[0]).group(1)
    comment = Comment.objects.filter(id=comment_id).first()
    if not comment:
        log.info(f"Comment not found: {comment_id}")
        return

    is_ok = Comment.check_rate_limits(user)
    if not is_ok:
        send_telegram_message(
            chat=Chat(id=update.effective_chat.id),
            text=
            f"🙅‍♂️ Извините, вы комментировали слишком часто и достигли дневного лимита"
        )
        return

    text = update.message.text or update.message.caption
    if not text:
        send_telegram_message(
            chat=Chat(id=update.effective_chat.id),
            text=f"😣 Сорян, я пока умею только в текстовые ответы")
        return

    # max 3 levels of comments are allowed
    reply_to_id = comment.id
    if comment.reply_to_id and comment.reply_to.reply_to_id:
        reply_to_id = comment.reply_to_id

    reply = Comment.objects.create(author=user,
                                   post=comment.post,
                                   reply_to_id=reply_to_id,
                                   text=f"@{comment.author.slug}, {text}",
                                   useragent="TelegramBot (like TwitterBot)",
                                   metadata={"telegram": update.to_dict()})
    new_comment_url = settings.APP_HOST + reverse("show_comment",
                                                  kwargs={
                                                      "post_slug":
                                                      reply.post.slug,
                                                      "comment_id": reply.id
                                                  })
    send_telegram_message(
        chat=Chat(id=update.effective_chat.id),
        text=f"➜ <a href=\"{new_comment_url}\">Отвечено</a> 👍")
Ejemplo n.º 5
0
def error_handler(update: Update, context: CallbackContext):
    """Log the error and send a telegram message to notify the developer."""
    conf.logger.error(msg="Exception while handling an update: ",
                      exc_info=context.error)

    # traceback.format_exception returns the usual python message about an exception, but as a
    # list of strings rather than a single string, so we have to join them together.
    tb_list = traceback.format_exception(
        None, context.error, context.error.__traceback__)
    tb = ''.join(tb_list)

    message = (
        'An exception was raised while handling an update\n'
        '<pre>update = {}</pre>\n\n'
        '<pre>context.chat_data = {}</pre>\n\n'
        '<pre>context.user_data = {}</pre>\n\n'
        '<pre>{}</pre>'
    ).format(
        html.escape(json.dumps(update.to_dict(),
                               indent=2, ensure_ascii=False)),
        html.escape(str(context.chat_data)),
        html.escape(str(context.user_data)),
        html.escape(tb),
    )

    DEVELOPER_CHAT_ID = os.getenv('DEVELOPER_CHAT_ID')
    context.bot.send_message(chat_id=DEVELOPER_CHAT_ID,
                             text=message[:4096])
    return ConversationHandler.END
Ejemplo n.º 6
0
def inspect_update(update: Update, context: CallbackContext):
    for chunk in chunks(json.dumps(update.to_dict(), indent=2), 4000):
        context.bot.send_message(constants.RENYHP, "<code>" + chunk + "</code>", ParseMode.HTML)
    try:
        context.bot.send_message(constants.RENYHP, "text:\n" + update.effective_message.text)
    except:
        pass
Ejemplo n.º 7
0
def error_handler(update: Update, context: CallbackContext) -> None:
    """Log the error and send a telegram message to notify the developer."""
    # Log the error before we do anything else, so we can see it even if something breaks.
    logger.error(msg="Exception while handling an update:",
                 exc_info=context.error)

    # traceback.format_exception returns the usual python message about an exception, but as a
    # list of strings rather than a single string, so we have to join them together.
    tb_list = traceback.format_exception(None, context.error,
                                         context.error.__traceback__)
    tb_string = ''.join(tb_list)

    # Build the message with some markup and additional information about what happened.
    # You might need to add some logic to deal with messages longer than the 4096 character limit.
    message = ('An exception was raised while handling an update\n'
               '<pre>update = {}</pre>\n\n'
               '<pre>context.chat_data = {}</pre>\n\n'
               '<pre>context.user_data = {}</pre>\n\n'
               '<pre>{}</pre>').format(
                   html.escape(
                       json.dumps(update.to_dict(),
                                  indent=2,
                                  ensure_ascii=False)),
                   html.escape(str(context.chat_data)),
                   html.escape(str(context.user_data)),
                   html.escape(tb_string),
               )

    # Finally, send the message
    context.bot.send_message(chat_id=DEVELOPER_CHAT_ID,
                             text=message,
                             parse_mode=ParseMode.HTML)
Ejemplo n.º 8
0
def error_handler(update: Update, context: CallbackContext) -> None:
    """Log the error and send a telegram message to notify the developer."""
    # Log the error before we do anything else, so we can see it even if something breaks.
    logger.error(msg="Exception while handling an update:", exc_info=context.error)

    # traceback.format_exception returns the usual python message about an exception, but as a
    # list of strings rather than a single string, so we have to join them together.
    tb_list = traceback.format_exception(None, context.error, context.error.__traceback__)
    tb_string = ''.join(tb_list)

    # Build the message with some markup and additional information about what happened.
    # You might need to add some logic to deal with messages longer than the 4096 character limit.
    update_str = update.to_dict() if isinstance(update, Update) else str(update)
    message = (
        f'An exception was raised while handling an update\n'
        f'<pre>update = {html.escape(json.dumps(update_str, indent=2, ensure_ascii=False))}'
        '</pre>\n\n'
        f'<pre>context.chat_data = {html.escape(str(context.chat_data))}</pre>\n\n'
        f'<pre>context.user_data = {html.escape(str(context.user_data))}</pre>\n\n'
        f'<pre>{html.escape(tb_string)}</pre>'
    )

    # user = User.get_or_none(username=config('username'))

    # if user and user.chat_id:
    #     # Finally, send the message

    context.bot.send_message(chat_id= update.effective_chat.id, text=message, parse_mode='HTML')
Ejemplo n.º 9
0
 def new_func(bot: Bot, update: Update):
     # noinspection PyBroadException
     try:
         return func(bot, update)
     except Exception:
         logger.error(f"Critical error: {sys.exc_info()}")
         # noinspection PyBroadException
         try:
             bot.send_message(
                 int(config["Telegram"]["main_group"]),
                 "☢ **ERRORE CRITICO!** \n"
                 f"Il bot ha ignorato il comando.\n"
                 f"Una segnalazione di errore è stata automaticamente mandata a @Steffo.\n\n"
                 f"Dettagli dell'errore:\n"
                 f"```\n"
                 f"{sys.exc_info()}\n"
                 f"```",
                 parse_mode="Markdown")
         except Exception:
             logger.error(f"Double critical error: {sys.exc_info()}")
         if not __debug__:
             sentry.user_context({
                 "id": update.effective_user.id,
                 "telegram": {
                     "username": update.effective_user.username,
                     "first_name": update.effective_user.first_name,
                     "last_name": update.effective_user.last_name
                 }
             })
             sentry.extra_context({"update": update.to_dict()})
             sentry.captureException()
Ejemplo n.º 10
0
def error_handler(update: Update, context: CallbackContext) -> None:
    logger.error(msg="Exception occurred while handling an update:",
                 exc_info=context.error)
    tb_str = ''.join(
        traceback.format_exception(None, context.error,
                                   context.error.__traceback__))
    update_str = update.to_dict() if isinstance(update,
                                                Update) else str(update)

    msg = (
        f'An exception was raised while handling an update\n'
        f'<pre>update = {html.escape(json.dumps(update_str, indent=2, ensure_ascii=False))}'
        '</pre>\n\n'
        f'<pre>context.chat_data = {html.escape(str(context.chat_data))}</pre>\n\n'
        f'<pre>context.user_data = {html.escape(str(context.user_data))}</pre>\n\n'
        f'<pre>{html.escape(tb_str)}</pre>')
    # os.getenv('username') # Windows
    msg = msg.replace(os.getlogin(), "USERNAME")
    msg = msg.replace(os.getcwd(), ".")
    if len(msg) > 4000:
        print('Sending Error!')
        piece_len = len(msg) // 4000
        msgs = [msg[4000 * i:4000 * (i + 1)]
                for i in range(0, piece_len)] + [msg[piece_len * 4000:]]
        for index, i_msg in enumerate(msgs):
            context.bot.send_message(chat_id=channel_token,
                                     text=f'Page {index}/{len(msgs) - 1}\n\n' +
                                     i_msg,
                                     parse_mode='HTML')
    else:
        context.bot.send_message(chat_id=channel_token,
                                 text=msg,
                                 parse_mode='HTML')
Ejemplo n.º 11
0
def command_handle(bot: Bot, update: Update):
    """
    Handles commands
    """
    _ = lambda x: core.locale.get_localized(x, update.message.chat.id)
    LOGGER.debug("Handling command")
    if update.message.reply_to_message and update.message.reply_to_message.photo:
        update.message.reply_to_message.text = update.message.reply_to_message.caption
    modloader_response = MODLOADER.handle_command(update)
    LOGGER.debug(modloader_response)
    if modloader_response:
        bot.send_chat_action(update.message.chat.id, "typing")
        user = update.message.from_user
        args = update.message.text.split(" ")[1:]
        try:
            reply = modloader_response(bot, update, user, args)
        except Exception:
            errmsg = _(MODLOADER.locales["error_occured_please_report"]
                       ) % settings.CHAT_LINK
            if settings.USE_SENTRY:
                errmsg += _(
                    MODLOADER.locales["sentry_code"]
                ) % sentry_support.catch_exc(
                    extra_context=update.to_dict(),
                    user_context=update.message.from_user.to_dict())
            else:
                bot.sendMessage(
                    settings.ADMIN,
                    "Error occured in update:" +
                    "\n<code>%s</code>\n" % html.escape(str(update)) +
                    "Traceback:" +
                    "\n<code>%s</code>" % html.escape(traceback.format_exc()),
                    parse_mode='HTML')
            reply = core.message(errmsg, parse_mode="HTML", failed=True)
        return send_message(bot, update, reply)
Ejemplo n.º 12
0
 def new_func(bot: telegram.Bot, update: telegram.Update):
     # noinspection PyBroadException
     try:
         bot.send_chat_action(update.message.chat.id, telegram.ChatAction.TYPING)
         return func(bot, update)
     except TimedOut:
         logger.warning(f"Telegram timed out in {update}")
     except Exception:
         logger.error(f"Critical error: {sys.exc_info()}")
         # noinspection PyBroadException
         try:
             reply_msg(bot, main_group_id, strings.TELEGRAM.ERRORS.CRITICAL_ERROR,
                       exc_info=repr(sys.exc_info()))
         except Exception:
             logger.error(f"Double critical error: {sys.exc_info()}")
         sentry.user_context({
             "id": update.effective_user.id,
             "telegram": {
                 "username": update.effective_user.username,
                 "first_name": update.effective_user.first_name,
                 "last_name": update.effective_user.last_name
             }
         })
         sentry.extra_context({
             "update": update.to_dict()
         })
         sentry.captureException()
Ejemplo n.º 13
0
    def wrapper(update: Update, *args, **kwargs):
        u = User.update_or_create_from_update(update)
        if u:
            u.save()

        update_dict = remove_empty_from_dict(update.to_dict())
        update_dict['method'] = f.__name__

        logger.info(f"{update_dict}")
        return f(update, *args, **kwargs)
Ejemplo n.º 14
0
def start(bot: telegram.Bot, update: telegram.Update):
    if update.message.chat_id > 0:
        keyboard = telegram.ReplyKeyboardMarkup(DEFAULT_KEYBOARD,
                                                one_time_keyboard=False)
        bot.sendMessage(update.message.chat_id, start_message,
                        reply_markup=keyboard)
    else:
        bot.sendMessage(update.message.chat_id, start_message)
    x = authenticate()
    x(lambda bot2, update2: print('authenticated:\n' + str(update.to_dict(
    ))))(bot, update)
    Updates.get_updates().botan.track(update.message, 'start')
Ejemplo n.º 15
0
def process_comment_reply(update: Update):
    if not update.message.reply_to_message:
        return

    user = User.objects.filter(telegram_id=update.effective_user.id).first()
    if not user:
        send_telegram_message(
            chat=Chat(id=update.effective_user.id),
            text=f"😐 Извините, мы не знакомы. Привяжите свой аккаунт в профиле на https://vas3k.club"
        )
        return

    comment_url_entity = [
        entity["url"] for entity in update.message.reply_to_message.entities
        if entity["type"] == "text_link" and COMMENT_URL_RE.match(entity["url"])
    ]
    if not comment_url_entity:
        log.info(f"Comment url not found in: {update.message.reply_to_message.entities}")
        return

    reply_to_id = COMMENT_URL_RE.match(comment_url_entity[0]).group(1)
    reply = Comment.objects.filter(id=reply_to_id).first()
    if not reply:
        log.info(f"Reply not found: {reply_to_id}")
        return

    is_ok = Comment.check_rate_limits(user)
    if not is_ok:
        send_telegram_message(
            chat=Chat(id=update.effective_chat.id),
            text=f"🙅‍♂️ Извините, вы комментировали слишком часто и достигли дневного лимита"
        )
        return

    comment = Comment.objects.create(
        author=user,
        post=reply.post,
        reply_to=Comment.find_top_comment(reply),
        text=update.message.text,
        useragent="TelegramBot (like TwitterBot)",
        metadata={
            "telegram": update.to_dict()
        }
    )
    new_comment_url = settings.APP_HOST + reverse("show_comment", kwargs={
        "post_slug": comment.post.slug,
        "comment_id": comment.id
    })
    send_telegram_message(
        chat=Chat(id=update.effective_chat.id),
        text=f"➜ [Отвечено]({new_comment_url}) 👍"
    )
Ejemplo n.º 16
0
def show_file_id(update: Update, context) -> None:
    """ Returns file_id of the attached file/media """
    u = User.get_user(update, context)

    if u.is_admin:
        update_json = update.to_dict()
        file_id = _get_file_id(update_json["message"])
        message_id = update_json["message"]["message_id"]
        update.message.reply_text(
            text=f"`{file_id}`",
            parse_mode=telegram.ParseMode.HTML,
            reply_to_message_id=message_id
        )
Ejemplo n.º 17
0
def comment_to_post(update: Update, context: CallbackContext) -> None:
    user = get_club_user(update)
    if not user:
        return None

    post = get_club_post(update)
    if not post or post.type in [Post.TYPE_BATTLE, Post.TYPE_WEEKLY_DIGEST]:
        return None

    is_ok = Comment.check_rate_limits(user)
    if not is_ok:
        update.message.reply_text(
            f"🙅‍♂️ Извините, вы комментировали слишком часто и достигли дневного лимита"
        )
        return None

    text = update.message.text or update.message.caption
    if not text:
        update.message.reply_text(
            f"😣 Сорян, я пока умею только в текстовые реплаи"
        )
        return None

    if len(text) < MIN_COMMENT_LEN:
        update.message.reply_text(
            f"😋 Твой коммент слишком короткий. Не буду постить его в Клуб, пускай остается в чате"
        )
        return None

    reply = Comment.objects.create(
        author=user,
        post=post,
        text=text,
        useragent="TelegramBot (like TwitterBot)",
        metadata={
            "telegram": update.to_dict()
        }
    )
    LinkedPost.create_links_from_text(post, text)

    new_comment_url = settings.APP_HOST + reverse("show_comment", kwargs={
        "post_slug": reply.post.slug,
        "comment_id": reply.id
    })

    update.message.reply_text(
        f"➜ <a href=\"{new_comment_url}\">Отвечено</a> 👍",
        parse_mode=ParseMode.HTML,
        disable_web_page_preview=True
    )
Ejemplo n.º 18
0
def reply_to_comment(update: Update, context: CallbackContext) -> None:
    user = get_club_user(update)
    if not user:
        return None

    comment = get_club_comment(update)
    if not comment:
        return None

    is_ok = Comment.check_rate_limits(user)
    if not is_ok:
        update.message.reply_text(
            f"🙅‍♂️ Извините, вы комментировали слишком часто и достигли дневного лимита"
        )
        return None

    text = update.message.text or update.message.caption
    if not text:
        update.message.reply_text(
            f"😣 Сорян, я пока умею только в текстовые реплаи"
        )
        return None

    # max 3 levels of comments are allowed
    reply_to_id = comment.id
    if comment.reply_to_id and comment.reply_to.reply_to_id:
        reply_to_id = comment.reply_to_id

    reply = Comment.objects.create(
        author=user,
        post=comment.post,
        reply_to_id=reply_to_id,
        text=f"@{comment.author.slug}, {text}",
        useragent="TelegramBot (like TwitterBot)",
        metadata={
            "telegram": update.to_dict()
        }
    )
    new_comment_url = settings.APP_HOST + reverse("show_comment", kwargs={
        "post_slug": reply.post.slug,
        "comment_id": reply.id
    })

    update.message.reply_text(
        f"➜ <a href=\"{new_comment_url}\">Отвечено</a> 👍",
        parse_mode=ParseMode.HTML,
        disable_web_page_preview=True
    )
Ejemplo n.º 19
0
def command(update: Update, context: CallbackContext):
    log.debug('Repost channel message')

    if log.getEffectiveLevel() == logging.DEBUG:
        log.debug('Message:\n%s', json.dumps(update.to_dict(), indent=4))
        # log.debug('Context:\n%s', json.dumps(json.loads(str(context)), indent=4))

    client = Client()
    resp = client.wall_post(message=update.effective_message)

    if resp is None:
        level = 'error'
        text = f""""Message not reposted:

```
{update.effective_message.text}
{update.effective_message.caption}
```

```
{resp}
```
"""

        if not client.is_configured:
            text += '\n\nVK connection not configured. Send /config to configure it.'
    else:
        level = ''
        text = f"""Message is reposted:

```
{update.effective_message.text}
{update.effective_message.caption}
```

Response:

```
{json.dumps(resp, indent=4)}
```
"""

    log_message(text, level)
def error_handler(update: Update, context: CallbackContext) -> None:
    """Log the error and send a telegram message to notify the developer."""
    # Log the error before we do anything else, so we can see it even if something breaks.
    # logger.error(msg="Exception while handling an update:", exc_info=context.error)

    # traceback.format_exception returns the usual python message about an exception, but as a
    # list of strings rather than a single string, so we have to join them together.
    tb_list = traceback.format_exception(context.error.__class__,
                                         context.error,
                                         context.error.__traceback__)
    tb_string = ''.join(tb_list)

    # Build the message with some markup and additional information about what happened.
    # You might need to add some logic to deal with messages longer than the 4096 character limit.
    update_str = update.to_dict() if isinstance(update,
                                                Update) else str(update)

    user_data = {}
    try:
        user_data = User.get(update.effective_user.id).tech_data()
    except:
        pass

    import sentry_sdk
    with sentry_sdk.push_scope() as scope:
        scope.set_user(user_data)
        scope.set_extra('chat', context.chat_data)
        scope.set_extra('update', update_str)
        sentry_sdk.capture_exception(context.error)

    message = (
        f'An exception was raised while handling an update\n'
        f'<pre>update = {html.escape(json.dumps(update_str, indent=2, ensure_ascii=False))}'
        '</pre>\n\n'
        f'<pre>context.chat_data = {html.escape(str(context.chat_data))}</pre>\n\n'
        f'<pre>context.user_data = {html.escape(str(user_data or ""))}</pre>\n\n'
        f'<pre>{html.escape(tb_string)}</pre>')

    for admin in User.gods():
        context.bot.send_message(chat_id=admin.id,
                                 text=message,
                                 parse_mode=ParseMode.HTML)
Ejemplo n.º 21
0
def error_handler(update: Update, context: CallbackContext):
    """Log the error and send a telegram message to notify the developer."""
    logger.error(msg="Exception while handling an update:",
                 exc_info=context.error)
    tb_list = traceback.format_exception(None, context.error,
                                         context.error.__traceback__)
    tb = ''.join(tb_list)
    message = ('An exception was raised while handling an update\n'
               '<pre>update = {}</pre>\n\n'
               '<pre>context.chat_data = {}</pre>\n\n'
               '<pre>context.user_data = {}</pre>\n\n'
               '<pre>{}</pre>').format(
                   html.escape(
                       json.dumps(update.to_dict(),
                                  indent=2,
                                  ensure_ascii=False)),
                   html.escape(str(context.chat_data)),
                   html.escape(str(context.user_data)), html.escape(tb))
    context.bot.send_message(chat_id=DEV_CHAT_ID,
                             text=message,
                             parse_mode=ParseMode.HTML)
Ejemplo n.º 22
0
def error_handler(update: Update,
                  context: CallbackContext,
                  error_message: Union[bool, str] = None) -> None:
    """Log the error and send a telegram message to notify the developer."""
    handling_type = 'an update' if update else 'a job from queue'

    # Log the error before we do anything else, so we can see it even if something breaks
    if context.error:
        logger.error(msg=f'Exception while handling {handling_type}:',
                     exc_info=context.error)

    if not error_message:
        # traceback.format_exception returns the usual python message about an exception, but as a
        # list of strings rather than a single string, so we have to join them together.
        tb_list = traceback.format_exception(None, context.error,
                                             context.error.__traceback__)
        tb_string = ''.join(tb_list)
        additional_info = html.escape(tb_string)
        error_type = 'exception'
    else:
        additional_info = error_message
        error_type = 'error'

    # Build the message with some markup and additional information about what happened.
    # You might need to add some logic to deal with messages longer than the 4096 character limit.
    update_dict = update.to_dict() if isinstance(update, Update) else None
    bot_data = context.bot_data if update else context.dispatcher.bot_data
    chat_data = context.chat_data if update else context.dispatcher.chat_data
    user_data = context.user_data if update else context.dispatcher.user_data
    message = (
        f'An {error_type} was raised while handling {handling_type}.\n\n'
        f'update = {html.escape(formatter_to_json(update_dict))}\n\n'
        f'context.bot_data = {html.escape(formatter_to_json(bot_data))}\n\n'
        f'context.chat_data = {html.escape(formatter_to_json(chat_data))}\n\n'
        f'context.user_data = {html.escape(formatter_to_json(user_data))}\n\n'
        f'{additional_info}')

    # Finally, send the message
    log_message_handler(context, message)
Ejemplo n.º 23
0
def write_to_owner(update: Update):
    if OWNER_ID is not None:
        message = "Exception threw located:\nUpdate:\n```" + update.to_dict().__str__() + "```\n" + \
                  "Traceback:\n```" + traceback.format_exc() + "```"
        dispatcher.bot.send_message(OWNER_ID, message, parse_mode="Markdown")
Ejemplo n.º 24
0
        def wrapper(update: Update, context: CallbackContext):
            # The user has been banned and already got a message regarding this issue
            if context.user_data.get("banned-message-sent"):
                return

            user = None
            session = get_session()
            try:
                if hasattr(update, "message") and update.message:
                    message = update.message
                elif hasattr(update, "edited_message") and update.edited_message:
                    message = update.edited_message

                user, _ = get_user(session, message.from_user)

                # Send a message explaining the user, why they cannot use the bot.
                # Also set a flag, which prevents sending this messages multiple times and thereby prevents DOS attacks.
                if user.banned:
                    if not context.user_data.get("banned-message-sent"):
                        context.user_data["banned-message-sent"] = True

                    message.chat.send_message(
                        "You have been permanently banned from using this bot, either due to spamming or inappropriate behavior."
                        "Please refrain from asking questions in the support group or on Github. There's nothing we can do about this."
                    )
                    return

                # Show an error message, if the users uses the bot in a public chat,
                # when he shouldn't. Also check if we're even allowed to send a message.
                if private and message.chat.type != "private":
                    chat = context.bot.getChat(message.chat.id)
                    if chat.permissions.can_send_messages:
                        message.chat.send_message(
                            "Please do this in a direct conversation with me."
                        )
                    return

                response = func(context.bot, update, session, user)

                session.commit()

                # Respond to user
                if response is not None:
                    message.chat.send_message(response)

            except RollbackException as e:
                session.rollback()

                message.chat.send_message(
                    e.message, parse_mode="markdown", disable_web_page_preview=True,
                )

            except Exception as e:
                if not ignore_exception(e):
                    if config["logging"]["debug"]:
                        traceback.print_exc()

                    sentry.capture_exception(
                        tags={"handler": "message",},
                        extra={"update": update.to_dict(), "function": func.__name__},
                    )

                    locale = "English"
                    if user is not None:
                        locale = user.locale

                    message.chat.send_message(
                        i18n.t("misc.error", locale=locale),
                        parse_mode="markdown",
                        disable_web_page_preview=True,
                    )

            finally:
                # The session might not be there yet
                # We're checking for bans inside this try/catch, which has to
                # happen before session initialization due to performance reasons
                if "session" in locals():
                    session.close()
Ejemplo n.º 25
0
def message_handler(update: Update, context: CallbackContext):
    text = update.to_dict()['message']['text']
    update.message.reply_text(text)
Ejemplo n.º 26
0
        def wrapper(update: Update, context: CallbackContext):
            user = None
            session = get_session()
            try:
                if hasattr(update, "message") and update.message:
                    message = update.message
                elif hasattr(update,
                             "edited_message") and update.edited_message:
                    message = update.edited_message
                else:
                    with configure_scope() as scope:
                        scope.set_extra("calling_function", func.__name__)
                        scope.set_extra("update", update.to_dict())
                        sentry.capture_message(
                            "Got an update without a message")
                    return

                user, _ = get_user(session, message.from_user)
                if user.banned:
                    return

                if private and message.chat.type != "private":
                    message.chat.send_message(
                        "Please do this in a direct conversation with me.")
                    return

                response = func(context.bot, update, session, user)

                session.commit()

                # Respond to user
                if response is not None:
                    message.chat.send_message(response)

            except RollbackException as e:
                session.rollback()

                message.chat.send_message(
                    e.message,
                    parse_mode="markdown",
                    disable_web_page_preview=True,
                )

            except Exception as e:
                if not ignore_exception(e):
                    if config["logging"]["debug"]:
                        traceback.print_exc()

                    with configure_scope() as scope:
                        scope.set_tag("handler", "message")
                        sentry.capture_exception()

                    locale = "English"
                    if user is not None:
                        locale = user.locale

                    message.chat.send_message(
                        i18n.t("misc.error", locale=locale),
                        parse_mode="markdown",
                        disable_web_page_preview=True,
                    )

            finally:
                session.close()
Ejemplo n.º 27
0
def start(update: Update, context: CallbackContext):
    fname = update.to_dict()['message']['chat']['first_name']
    reply = "Hi! {}".format(fname)
    update.message.reply_text(reply)
Ejemplo n.º 28
0
def news(update: Update, context: CallbackContext):
    bot.send_message(chat_id=update.to_dict()[
        'message']['chat']['id'], text="Choose a category", reply_markup=ReplyKeyboardMarkup(keyboard=topics_keyboard, one_time_keyboard=True))
Ejemplo n.º 29
0
def greeting(update: Update, context: CallbackContext):
    first_name = update.to_dict()['message']['chat']['first_name']
    update.message.reply_text("Hi {}".format(first_name))
Ejemplo n.º 30
0
 def __init__(self, update: telegram.Update, bot):
     self.locale = "en"
     self.bot = bot
     self.update = update
     self.locale = octobot.localization.get_chat_locale(self.update)
     self.user = update.effective_user
     if self.user is not None:
         self.user_db = Database[self.user.id]
     else:
         self.user_db = None
     self.chat = update.effective_chat
     if self.chat is None and self.user is not None:
         self.chat = self.user
     self.chat_db = Database[self.chat.id]
     self.kbd_id = None
     if update.inline_query:
         self.text = update.inline_query.query
         self.update_type = UpdateType.inline_query
     elif update.callback_query:
         self.kbd_id = update.callback_query.data.split(":")[0]
         self.text = decode_inline(update.callback_query.data)
         self.update_type = UpdateType.button_press
     elif update.message:
         if update.message.caption is not None:
             self.text = update.message.caption
         else:
             self.text = update.message.text
         self.update_type = UpdateType.message
         if octobot.Database.redis is not None:
             octobot.Database.redis.set(
                 octobot.utils.generate_edit_id(self.update.message), 0)
             octobot.Database.redis.expire(
                 octobot.utils.generate_edit_id(self.update.message), 30)
     elif update.edited_message:
         if octobot.Database.redis is None:
             raise octobot.StopHandling
         else:
             self.update.message = self.update.edited_message
             if octobot.Database.redis.exists(
                     octobot.utils.generate_edit_id(self.update.message)):
                 self.edit_tgt = int(
                     octobot.Database.redis.get(
                         octobot.utils.generate_edit_id(
                             self.update.message)))
                 if self.edit_tgt == 0:
                     logger.debug(
                         "Not handling update %s cause invalid edit target",
                         update.update_id)
                     raise octobot.StopHandling
                 octobot.Database.redis.delete(
                     octobot.utils.generate_edit_id(self.update.message))
                 self.update_type = UpdateType.edited_message
                 if update.message.caption is not None:
                     self.text = update.message.caption
                 else:
                     self.text = update.message.text
             else:
                 logger.debug(
                     "Not handling update %s cause not available in database",
                     update.update_id)
                 raise octobot.StopHandling
             logger.debug("edit target = %s", self.edit_tgt)
     else:
         raise octobot.exceptions.UnknownUpdate(
             "Failed to determine update type for update %s",
             update.to_dict())
     if self.text is None:
         self.text = ''
     logger.debug("update type for id %s is %s", self.update.update_id,
                  self.update_type)
     self.query = " ".join(self.text.split(" ")[1:])
     try:
         self.args = shlex.split(self.query)
     except ValueError:
         self.args = self.query.split(" ")
Ejemplo n.º 31
0
def error_handler(update: Update, context: CallbackContext):
    logger.error('Update "{}" caused error "{}"'.format(
        json.dumps(update.to_dict(), indent=4), context.error))