Пример #1
0
 def test_html_message(self):
     m = HTMLMessage(self._TEXT, self._RECEIVER)
     with self.subTest():
         self._test_message_basics(m)
     # end with
     m.send(self.s, "RECEIVER", None)
     self.assertTupleEqual(self.s.args, ('@username', 'test text'), "args")
     self.assertDictEqual(self.s.kwargs, {'parse_mode': 'html', 'disable_notification': False, 'reply_to_message_id': None, 'reply_markup': None, 'disable_web_page_preview': True}, "args")
Пример #2
0
 def test_html_message(self):
     m = HTMLMessage(self._TEXT, self._RECEIVER)
     with self.subTest():
         self._test_message_basics(m)
     # end with
     m.send(self.s, "RECEIVER", None)
     self.assertTupleEqual(self.s.args, ('@username', 'test text'), "args")
     self.assertDictEqual(
         self.s.kwargs, {
             'parse_mode': 'html',
             'disable_notification': False,
             'reply_to_message_id': None,
             'reply_markup': None,
             'disable_web_page_preview': True
         }, "args")
Пример #3
0
def on_msg(update, msg):
    """
    :type  msg: Message
    """
    ln = l(update.message)
    return HTMLMessage(
        ln.lang_response.format(lang=msg.from_peer.language_code))
Пример #4
0
def cmd_do(update, text):
    options = [[KeyboardButton(txt) for txt in features.keys()]]
    return HTMLMessage(
        Lang.here_are_some_options,
        reply_markup=ReplyKeyboardMarkup(
            options,
            resize_keyboard=True,
            one_time_keyboard=True,
            selective=True
        ),
    )
def on_join(update, message):
    assert_type_or_raise(message.new_chat_members, list)
    if bot.user_id not in [
            user.id for user in message.new_chat_members
            if isinstance(user, User)
    ]:
        # not we were added
        return
    # end if
    return HTMLMessage(
        LangEN.join_message.format(bot=bot.username, chat_id=message.chat.id) +
        (LangEN.unstable_text if bot.username == "hey_admin_bot" else ""))
def format_api_result(obj: TgBotApiObject):
    string = 'null'
    if isinstance(obj, TgBotApiObject):
        if obj._raw:
            string = json.dumps(obj._raw, indent=4, sort_keys=True, ensure_ascii=False)
        else:
            string = json.dumps(obj.to_array(), indent=4, sort_keys=True, ensure_ascii=False)
        # end if
    # end def
    return HTMLMessage(
        "Type <code>{type}</code>:\n<pre>{msg}</pre>".format(type=escape(obj.__class__.__name__), msg=escape(string)),
    )
def income(update):
    assert isinstance(update, Update)
    reply_chat_id, reply_message_id = msg_get_reply_params(update)
    if reply_chat_id is None:
        logger.error("could not find chat:\n{}".format(update))
        reply_chat_id = EVENT_CHANNEL
    # end if
    if update._raw:
        string = json.dumps(update._raw, indent=4, sort_keys=True, ensure_ascii=False)
    else:
        string = json.dumps(update.to_array(), indent=4, sort_keys=True, ensure_ascii=False)
    # end if
    return HTMLMessage(
        "<pre>{}</pre>".format(escape(string)),
        receiver=reply_chat_id, reply_id=reply_message_id
    )
Пример #8
0
def cmd_example(update, text):
    return HTMLMessage(
        'This is an <a href="https://github.com/luckydonald/teleflask">flask</a> based <a href="https://github.com/luckydonald/docker-telegram-bot/">dockerized</a> example bot.'
    )
Пример #9
0
def cmd_start(update, text):
    return HTMLMessage(
        '<b>Hello world</b> from your flask based <a href="https://github.com/luckydonald/docker-telegram-bot/">telegram bot docker container</a>.\n'
        'You can also click the <code>/help</code> <i>bot command</i>: /help')
def update_call_admins(message):
    """
    :param message: The message from inside the update.
    :type  message: Message
    :rtype: None
    """
    assert isinstance(bot.bot, Bot)
    assert isinstance(message, Message)
    assert isinstance(message.chat, Chat)
    assert isinstance(message.chat.id, int)
    chat_id = message.chat.id

    # only do it in groups
    if message.chat.type not in POSSIBLE_CHAT_TYPES:
        logger.debug(
            "Discarding message (not a chat type with admins): {}".format(
                message))
        return
    # end def

    # prepare the messages
    msgs = []
    chat = format_chat(message)
    user = format_user(message.from_peer)
    link = format_message_permalink(message)

    logger.debug("user: "******"chat: " + repr(chat))
    if message.reply_to_message:
        # is reply
        if message.reply_to_message.from_peer.id == message.from_peer.id:
            # same user
            text = LangEN.admin_reply_info_same.format(user=user,
                                                       chat=chat,
                                                       msg_link=link)

        else:
            # different user
            text = LangEN.admin_reply_info.format(
                user=user,
                chat=chat,
                reply_user=format_user(message.reply_to_message.from_peer),
                msg_link=link)
        # end if
        msgs.append(
            HTMLMessage(text + (LangEN.unstable_text if bot.username ==
                                "hey_admin_bot" else "")))
        msgs.append(
            ForwardMessage(message.reply_to_message.message_id, chat_id))
    else:
        # isn't reply
        msgs.append(
            HTMLMessage(
                LangEN.admin_message_info.format(
                    user=user, chat=chat, msg_link=link) +
                (LangEN.unstable_text if bot.username ==
                 "hey_admin_bot" else "")))
    # end if
    msgs.append(ForwardMessage(message.message_id, chat_id))
    batch = MessageWithReplies(*msgs)
    batch.reply_id = None

    # notify each admin
    try:
        admins = bot.bot.get_chat_administrators(chat_id)
    except TgApiServerException as e:
        if "there is no administrators in the private chat" in e.description:
            return "There is no administrators in the private chat"
        # end if
        raise e
    # end try

    failed_admins = []
    random.shuffle(admins)
    for admin in admins:
        admin_formatted = format_user(admin.user)
        logger.debug(f"Found admin {admin_formatted}: {admin.user!s}.")
        if admin.user.is_bot:
            logger.debug("Skipping admin, is bot.")
            continue  # can't send messages to bots
        # end if
        for backoff in range(SEND_BACKOFF):
            logger.debug(
                f"Sending from {chat_id} to {admin.user.id} {admin_formatted!s} (old: {batch.receiver!r}). Try {backoff + 1}/{SEND_BACKOFF}."
            )
            batch.receiver = admin.user.id
            batch.top_message.receiver = admin.user.id
            for reply in batch.reply_messages:
                reply.receiver = admin.user.id
            # end def

            try:
                batch.send(bot.bot)
                logger.debug(f"Sending to admin {admin_formatted!s}")
                break
            except TgApiServerException as e:
                logger.info("Server Exception. Aborting.")
                if "bot can't initiate conversation with a user" in e.description:
                    logger.debug("Can't contact admin, not started.")
                    failed_admins.append(admin)
                else:
                    logger.warn('sending to admin failed', exc_info=True)
                # end if
                break
            except (TgApiException, RequestException) as e:
                logger.exception("Unknown Exception. Retrying.")
            # end if
        else:
            # backoff exceeded
            logger.debug("Admin failed: {}".format(format_user(admin.user)))
        # end for
    # end for
    logger.debug("That's all the admins.")
    if len(failed_admins) == 0:
        logger.debug("Sent to all admins are successfully.")
        return
    elif len(failed_admins) == 1:
        logger.debug("Sent to all admins but one.")
        return HTMLMessage(
            LangEN.couldnt_contact_singular(admin=format_user(
                failed_admins[0].user),
                                            num=len(admins),
                                            bot=bot.username,
                                            chat_id=chat_id))
    else:
        logger.debug(f"Sent to all admins but {failed_admins}.")
        return HTMLMessage(
            LangEN.couldnt_contact_plural(
                [format_user(admin.user) for admin in failed_admins],
                num=len(admins),
                bot=bot.username,
                chat_id=chat_id))
def cmd_start(update, text):
    return HTMLMessage(LangEN.help_message)
Пример #12
0
def cmd_start(update, text):
    return HTMLMessage(l(update.message.from_peer.language_code).help_message)
Пример #13
0
def start(update, text):
    # update is the update object. It is of type pytgbot.api_types.receivable.updates.Update
    # text is the text after the command. Can be empty. Type is str.
    return HTMLMessage("<b>Hello!</b> Thanks for using @" + app.username + "!")
Пример #14
0
def cmd_version(update, text):
    return HTMLMessage('Version <code>{version}</code> of bot <a href="tg://user?id={bot_id}">@{bot_username}</a>'.format(
        version=escape(VERSION_STR), bot_id=escape(str(bot.user_id)), bot_username=escape(bot.username)
    ))
Пример #15
0
def cmd_start(update, text):
    return HTMLMessage(l(update.message).help_message)
Пример #16
0
def cmd_version(update, text):
    return HTMLMessage(
        '<code>{version}</code>'.format(version=escape(VERSION_STR)))