Python telegram.ParseMode.HTML Examples

The following are 30 code examples of telegram.ParseMode.HTML(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module telegram.ParseMode , or try the search function .
Example #1
Source File: commands.py    From forwardscoverbot with GNU Affero General Public License v3.0 8 votes vote down vote up
def disable_web_page_preview(update, context):
    if not update.message.reply_to_message:
        text = ("This command permits to remove the web page preview from a message with "
                "a link.\n\nUse it replying to the message the bot already echoed and you "
                "want to disable the preview with this command.")
        update.message.reply_text(text=text)
        return

    if not update.message.reply_to_message.text:
        text = "This message does not have a web page preview"
        update.message.reply_to_message.reply_text(text=text, quote=True)
        return

    entities_list = [MessageEntity.URL, MessageEntity.TEXT_LINK]
    entities = update.message.reply_to_message.parse_entities(entities_list)
    if len(entities) == 0:
        text = "This message does not have a web page preview"
        update.message.reply_to_message.reply_text(text=text, quote=True)
        return

    text = update.message.reply_to_message.text_html
    update.message.reply_to_message.reply_text(
            text=text, 
            disable_web_page_preview=True, 
            parse_mode=ParseMode.HTML) 
Example #2
Source File: util.py    From rules-bot with GNU Affero General Public License v3.0 7 votes vote down vote up
def reply_or_edit(update, context, text):
    chat_data = context.chat_data
    if update.edited_message:
        chat_data[update.edited_message.message_id].edit_text(text,
                                                              parse_mode=ParseMode.HTML,
                                                              disable_web_page_preview=True)
    else:
        issued_reply = get_reply_id(update)
        if issued_reply:
            chat_data[update.message.message_id] = context.bot.sendMessage(update.message.chat_id, text,
                                                                           reply_to_message_id=issued_reply,
                                                                           parse_mode=ParseMode.HTML,
                                                                           disable_web_page_preview=True)
        else:
            chat_data[update.message.message_id] = update.message.reply_text(text,
                                                                             parse_mode=ParseMode.HTML,
                                                                             disable_web_page_preview=True) 
Example #3
Source File: processing.py    From telegram-robot-rss with Mozilla Public License 2.0 6 votes vote down vote up
def update_feed(self, url):
        telegram_users = self.db.get_users_for_url(url=url[0])

        for user in telegram_users:
            if user[6]:  # is_active
                try:
                    for post in FeedHandler.parse_feed(url[0]):
                        self.send_newest_messages(
                            url=url, post=post, user=user)
                except:
                    traceback.print_exc()
                    message = "Something went wrong when I tried to parse the URL: \n\n " + \
                        url[0] + "\n\nCould you please check that for me? Remove the url from your subscriptions using the /remove command, it seems like it does not work anymore!"
                    self.bot.send_message(
                        chat_id=user[0], text=message, parse_mode=ParseMode.HTML)

        self.db.update_url(url=url[0], last_updated=str(
            DateHandler.get_datetime_now())) 
Example #4
Source File: feds.py    From EmiliaHikari with GNU General Public License v3.0 6 votes vote down vote up
def fed_chat(update, context):
	chat = update.effective_chat  # type: Optional[Chat]
	user = update.effective_user  # type: Optional[User]
	fed_id = sql.get_fed_id(chat.id)

	user_id = update.effective_message.from_user.id
	if not is_user_admin(update.effective_chat, user_id):
		send_message(update.effective_message, tl(update.effective_message, "Anda harus menjadi admin untuk menjalankan perintah ini"))
		return

	if not fed_id:
		send_message(update.effective_message, tl(update.effective_message, "Grup ini tidak dalam federasi apa pun!"))
		return

	user = update.effective_user  # type: Optional[Chat]
	chat = update.effective_chat  # type: Optional[Chat]
	info = sql.get_fed_info(fed_id)

	text = tl(update.effective_message, "Obrolan ini adalah bagian dari federasi berikut:")
	text += "\n{} (ID: <code>{}</code>)".format(info['fname'], fed_id)

	send_message(update.effective_message, text, parse_mode=ParseMode.HTML) 
Example #5
Source File: simple_commands.py    From mau_mau_bot with GNU Affero General Public License v3.0 6 votes vote down vote up
def source(bot, update):
    """Handler for the /help command"""
    source_text = _("This bot is Free Software and licensed under the AGPL. "
      "The code is available here: \n"
      "https://github.com/jh0ker/mau_mau_bot")
    attributions = _("Attributions:\n"
      'Draw icon by '
      '<a href="http://www.faithtoken.com/">Faithtoken</a>\n'
      'Pass icon by '
      '<a href="http://delapouite.com/">Delapouite</a>\n'
      "Originals available on http://game-icons.net\n"
      "Icons edited by ɳick")

    send_async(bot, update.message.chat_id, text=source_text + '\n' +
                                                 attributions,
               parse_mode=ParseMode.HTML, disable_web_page_preview=True) 
Example #6
Source File: blacklist.py    From Marie-2.0-English with GNU General Public License v3.0 6 votes vote down vote up
def add_blacklist(bot: Bot, update: Update):
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    words = msg.text.split(None, 1)
    if len(words) > 1:
        text = words[1]
        to_blacklist = list(set(trigger.strip() for trigger in text.split("\n") if trigger.strip()))
        for trigger in to_blacklist:
            sql.add_to_blacklist(chat.id, trigger.lower())

        if len(to_blacklist) == 1:
            msg.reply_text("Added <code>{}</code> to the blacklist!".format(html.escape(to_blacklist[0])),
                           parse_mode=ParseMode.HTML)

        else:
            msg.reply_text(
                "Added <code>{}</code> triggers to the blacklist.".format(len(to_blacklist)), parse_mode=ParseMode.HTML)

    else:
        msg.reply_text("Tell me which words you would like to remove from the blacklist.") 
Example #7
Source File: geeks_for_geeks.py    From superCodingBot with MIT License 6 votes vote down vote up
def gfg3(bot, update, user_data):
        query = update.callback_query
        try:
            val = query.data
            val = str(val).replace("gfg3", "")
            with open("geeks_for_geeks/"+user_data['gfg'], encoding='utf-8') as data_file:
                data = json.load(data_file)
            se = data["Advanced Data Structures"][val]
            s = ""
            for i in se:
                s = s + '<a href="' + se[i] + '">' + i + '</a>\n\n'
            bot.edit_message_text(text=val + "\n\n" + s, chat_id=query.message.chat_id,
                                  message_id=query.message.message_id, parse_mode=ParseMode.HTML)
        except:
            return ConversationHandler.END
        user_data.clear()
        return ConversationHandler.END 
Example #8
Source File: warns.py    From SkittBot with GNU General Public License v3.0 6 votes vote down vote up
def list_warn_filters(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    all_handlers = sql.get_chat_warn_triggers(chat.id)

    if not all_handlers:
        update.effective_message.reply_text("No warning filters are active here!")
        return

    filter_list = CURRENT_WARNING_FILTER_STRING
    for keyword in all_handlers:
        entry = " - {}\n".format(html.escape(keyword))
        if len(entry) + len(filter_list) > telegram.MAX_MESSAGE_LENGTH:
            update.effective_message.reply_text(filter_list, parse_mode=ParseMode.HTML)
            filter_list = entry
        else:
            filter_list += entry

    if not filter_list == CURRENT_WARNING_FILTER_STRING:
        update.effective_message.reply_text(filter_list, parse_mode=ParseMode.HTML) 
Example #9
Source File: rss.py    From Marie-2.0-English with GNU General Public License v3.0 6 votes vote down vote up
def list_urls(bot, update):
    tg_chat_id = str(update.effective_chat.id)

    user_data = sql.get_urls(tg_chat_id)

    # this loops gets every link from the DB based on the filter above and appends it to the list
    links_list = [row.feed_link for row in user_data]

    final_content = "\n\n".join(links_list)

    # check if the length of the message is too long to be posted in 1 chat bubble
    if len(final_content) == 0:
        bot.send_message(chat_id=tg_chat_id, text="This chat is not subscribed to any links")
    elif len(final_content) <= constants.MAX_MESSAGE_LENGTH:
        bot.send_message(chat_id=tg_chat_id, text="This chat is subscribed to the following links:\n" + final_content)
    else:
        bot.send_message(chat_id=tg_chat_id, parse_mode=ParseMode.HTML,
                         text="<b>Warning:</b> The message is too long to be sent") 
Example #10
Source File: rss.py    From SkittBot with GNU General Public License v3.0 6 votes vote down vote up
def list_urls(bot, update):
    tg_chat_id = str(update.effective_chat.id)

    user_data = sql.get_urls(tg_chat_id)

    # this loops gets every link from the DB based on the filter above and appends it to the list
    links_list = [row.feed_link for row in user_data]

    final_content = "\n\n".join(links_list)

    # check if the length of the message is too long to be posted in 1 chat bubble
    if len(final_content) == 0:
        bot.send_message(chat_id=tg_chat_id, text="This chat is not subscribed to any links")
    elif len(final_content) <= constants.MAX_MESSAGE_LENGTH:
        bot.send_message(chat_id=tg_chat_id, text="This chat is subscribed to the following links:\n" + final_content)
    else:
        bot.send_message(chat_id=tg_chat_id, parse_mode=ParseMode.HTML,
                         text="<b>Warning:</b> The message is too long to be sent") 
Example #11
Source File: warns.py    From Marie-2.0-English with GNU General Public License v3.0 6 votes vote down vote up
def list_warn_filters(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    all_handlers = sql.get_chat_warn_triggers(chat.id)

    if not all_handlers:
        update.effective_message.reply_text("No warning filters are active here!")
        return

    filter_list = CURRENT_WARNING_FILTER_STRING
    for keyword in all_handlers:
        entry = " - {}\n".format(html.escape(keyword))
        if len(entry) + len(filter_list) > telegram.MAX_MESSAGE_LENGTH:
            update.effective_message.reply_text(filter_list, parse_mode=ParseMode.HTML)
            filter_list = entry
        else:
            filter_list += entry

    if not filter_list == CURRENT_WARNING_FILTER_STRING:
        update.effective_message.reply_text(filter_list, parse_mode=ParseMode.HTML) 
Example #12
Source File: warns.py    From Marie-2.0-English with GNU General Public License v3.0 6 votes vote down vote up
def button(bot: Bot, update: Update) -> str:
    query = update.callback_query  # type: Optional[CallbackQuery]
    user = update.effective_user  # type: Optional[User]
    match = re.match(r"rm_warn\((.+?)\)", query.data)
    if match:
        user_id = match.group(1)
        chat = update.effective_chat  # type: Optional[Chat]
        res = sql.remove_warn(user_id, chat.id)
        if res:
            update.effective_message.edit_text(
                "Warn removed by {}.".format(mention_html(user.id, user.first_name)),
                parse_mode=ParseMode.HTML)
            user_member = chat.get_member(user_id)
            return "<b>{}:</b>" \
                   "\n#UNWARN" \
                   "\n<b>Admin:</b> {}" \
                   "\n<b>User:</b> {}".format(html.escape(chat.title),
                                              mention_html(user.id, user.first_name),
                                              mention_html(user_member.user.id, user_member.user.first_name))
        else:
            update.effective_message.edit_text(
                "User has already has no warns.".format(mention_html(user.id, user.first_name)),
                parse_mode=ParseMode.HTML)

    return "" 
Example #13
Source File: blacklist.py    From tgbot with GNU General Public License v3.0 6 votes vote down vote up
def blacklist(bot: Bot, update: Update, args: List[str]):
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]

    all_blacklisted = sql.get_chat_blacklist(chat.id)

    filter_list = BASE_BLACKLIST_STRING

    if len(args) > 0 and args[0].lower() == 'copy':
        for trigger in all_blacklisted:
            filter_list += "<code>{}</code>\n".format(html.escape(trigger))
    else:
        for trigger in all_blacklisted:
            filter_list += " - <code>{}</code>\n".format(html.escape(trigger))

    split_text = split_message(filter_list)
    for text in split_text:
        if text == BASE_BLACKLIST_STRING:
            msg.reply_text("There are no blacklisted messages here!")
            return
        msg.reply_text(text, parse_mode=ParseMode.HTML) 
Example #14
Source File: blacklist.py    From tgbot with GNU General Public License v3.0 6 votes vote down vote up
def add_blacklist(bot: Bot, update: Update):
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    words = msg.text.split(None, 1)
    if len(words) > 1:
        text = words[1]
        to_blacklist = list(set(trigger.strip() for trigger in text.split("\n") if trigger.strip()))
        for trigger in to_blacklist:
            sql.add_to_blacklist(chat.id, trigger.lower())

        if len(to_blacklist) == 1:
            msg.reply_text("Added <code>{}</code> to the blacklist!".format(html.escape(to_blacklist[0])),
                           parse_mode=ParseMode.HTML)

        else:
            msg.reply_text(
                "Added <code>{}</code> triggers to the blacklist.".format(len(to_blacklist)), parse_mode=ParseMode.HTML)

    else:
        msg.reply_text("Tell me which words you would like to add to the blacklist.") 
Example #15
Source File: blacklist.py    From SkittBot with GNU General Public License v3.0 6 votes vote down vote up
def blacklist(bot: Bot, update: Update, args: List[str]):
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]

    all_blacklisted = sql.get_chat_blacklist(chat.id)

    filter_list = BASE_BLACKLIST_STRING

    if len(args) > 0 and args[0].lower() == 'copy':
        for trigger in all_blacklisted:
            filter_list += "<code>{}</code>\n".format(html.escape(trigger))
    else:
        for trigger in all_blacklisted:
            filter_list += " - <code>{}</code>\n".format(html.escape(trigger))

    split_text = split_message(filter_list)
    for text in split_text:
        if text == BASE_BLACKLIST_STRING:
            msg.reply_text("There are no blacklisted messages here!")
            return
        msg.reply_text(text, parse_mode=ParseMode.HTML) 
Example #16
Source File: blacklist.py    From SkittBot with GNU General Public License v3.0 6 votes vote down vote up
def add_blacklist(bot: Bot, update: Update):
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    words = msg.text.split(None, 1)
    if len(words) > 1:
        text = words[1]
        to_blacklist = list(set(trigger.strip() for trigger in text.split("\n") if trigger.strip()))
        for trigger in to_blacklist:
            sql.add_to_blacklist(chat.id, trigger.lower())

        if len(to_blacklist) == 1:
            msg.reply_text("Added <code>{}</code> to the blacklist!".format(html.escape(to_blacklist[0])),
                           parse_mode=ParseMode.HTML)

        else:
            msg.reply_text(
                "Added <code>{}</code> triggers to the blacklist.".format(len(to_blacklist)), parse_mode=ParseMode.HTML)

    else:
        msg.reply_text("Tell me which words you would like to add to the blacklist.") 
Example #17
Source File: misc.py    From Marie-2.0-English with GNU General Public License v3.0 5 votes vote down vote up
def send_to_list(bot: Bot, send_to: list, message: str, markdown=False, html=False) -> None:
    if html and markdown:
        raise Exception("Can only send with either markdown or HTML!")
    for user_id in set(send_to):
        try:
            if markdown:
                bot.send_message(user_id, message, parse_mode=ParseMode.MARKDOWN)
            elif html:
                bot.send_message(user_id, message, parse_mode=ParseMode.HTML)
            else:
                bot.send_message(user_id, message)
        except TelegramError:
            pass  # ignore users who fail 
Example #18
Source File: log_channel.py    From tgbot with GNU General Public License v3.0 5 votes vote down vote up
def send_log(bot: Bot, log_chat_id: str, orig_chat_id: str, result: str):
        try:
            bot.send_message(log_chat_id, result, parse_mode=ParseMode.HTML)
        except BadRequest as excp:
            if excp.message == "Chat not found":
                bot.send_message(orig_chat_id, "This log channel has been deleted - unsetting.")
                sql.stop_chat_logging(orig_chat_id)
            else:
                LOGGER.warning(excp.message)
                LOGGER.warning(result)
                LOGGER.exception("Could not parse")

                bot.send_message(log_chat_id, result + "\n\nFormatting has been disabled due to an unexpected error.") 
Example #19
Source File: rss.py    From Marie-2.0-English with GNU General Public License v3.0 5 votes vote down vote up
def show_url(bot, update, args):
    tg_chat_id = str(update.effective_chat.id)

    if len(args) >= 1:
        tg_feed_link = args[0]
        link_processed = parse(tg_feed_link)

        if link_processed.bozo == 0:
            feed_title = link_processed.feed.get("title", default="Unknown")
            feed_description = "<i>{}</i>".format(
                re.sub('<[^<]+?>', '', link_processed.feed.get("description", default="Unknown")))
            feed_link = link_processed.feed.get("link", default="Unknown")

            feed_message = "<b>Feed Title:</b> \n{}" \
                           "\n\n<b>Feed Description:</b> \n{}" \
                           "\n\n<b>Feed Link:</b> \n{}".format(html.escape(feed_title),
                                                               feed_description,
                                                               html.escape(feed_link))

            if len(link_processed.entries) >= 1:
                entry_title = link_processed.entries[0].get("title", default="Unknown")
                entry_description = "<i>{}</i>".format(
                    re.sub('<[^<]+?>', '', link_processed.entries[0].get("description", default="Unknown")))
                entry_link = link_processed.entries[0].get("link", default="Unknown")

                entry_message = "\n\n<b>Entry Title:</b> \n{}" \
                                "\n\n<b>Entry Description:</b> \n{}" \
                                "\n\n<b>Entry Link:</b> \n{}".format(html.escape(entry_title),
                                                                     entry_description,
                                                                     html.escape(entry_link))
                final_message = feed_message + entry_message

                bot.send_message(chat_id=tg_chat_id, text=final_message, parse_mode=ParseMode.HTML)
            else:
                bot.send_message(chat_id=tg_chat_id, text=feed_message, parse_mode=ParseMode.HTML)
        else:
            update.effective_message.reply_text("This link is not an RSS Feed link")
    else:
        update.effective_message.reply_text("URL missing") 
Example #20
Source File: misc.py    From Marie-2.0-English with GNU General Public License v3.0 5 votes vote down vote up
def markdown_help(bot: Bot, update: Update):
    update.effective_message.reply_text(MARKDOWN_HELP, parse_mode=ParseMode.HTML)
    update.effective_message.reply_text("Try forwarding the following message to me, and you'll see!")
    update.effective_message.reply_text("/save test This is a markdown test. _italics_, *bold*, `code`, "
                                        "[URL](example.com) [button](buttonurl:github.com) "
                                        "[button2](buttonurl://google.com:same)") 
Example #21
Source File: bot.py    From permabots with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_message(self, chat_id, text, keyboard, reply_message=None, user=None):
        parse_mode = ParseMode.HTML
        disable_web_page_preview = True
        reply_to_message_id = None
        if reply_message:
            if reply_message.message:
                reply_to_message_id = reply_message.message.message_id
            elif reply_message.callback_query:
                reply_to_message_id = reply_message.callback_query.message.message_id
        texts = text.strip().split('\\n')
        msgs = []
        for txt in texts:
            for chunk in textwrap.wrap(txt, 4096):
                msgs.append((chunk, None))
        if keyboard:
            msgs[-1] = (msgs[-1][0], keyboard)
        for msg in msgs:
            try:
                logger.debug("Message to send:(chat:%s,text:%s,parse_mode:%s,disable_preview:%s,keyboard:%s, reply_to_message_id:%s" %
                             (chat_id, msg[0], parse_mode, disable_web_page_preview, msg[1], reply_to_message_id))
                self._bot.send_message(chat_id=chat_id, text=msg[0], parse_mode=parse_mode, 
                                       disable_web_page_preview=disable_web_page_preview, reply_markup=msg[1], 
                                       reply_to_message_id=reply_to_message_id)        
                logger.debug("Message sent OK:(chat:%s,text:%s,parse_mode:%s,disable_preview:%s,reply_keyboard:%s, reply_to_message_id:%s" %
                             (chat_id, msg[0], parse_mode, disable_web_page_preview, msg[1], reply_to_message_id))
            except:
                exctype, value = sys.exc_info()[:2] 
                
                logger.error("""Error trying to send message:(chat:%s,text:%s,parse_mode:%s,disable_preview:%s,
                             reply_keyboard:%s, reply_to_message_id:%s): %s:%s""" % 
                             (chat_id, msg[0], parse_mode, disable_web_page_preview, msg[1], reply_to_message_id, exctype, value)) 
Example #22
Source File: robotrss.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def get(self, bot, update, args):
        """
        Manually parses an rss feed
        """

        telegram_user = update.message.from_user

        if len(args) > 2:
            message = "To get the last news of your subscription please use /get <entryname> [optional: <count 1-10>]. Make sure you first add a feed using the /add command."
            update.message.reply_text(message)
            return

        if len(args) == 2:
            args_entry = args[0]
            args_count = int(args[1])
        else:
            args_entry = args[0]
            args_count = 4

        url = self.db.get_user_bookmark(
            telegram_id=telegram_user.id, alias=args_entry)

        if url is None:
            message = "I can not find an entry with label " + \
                args_entry + " in your subscriptions! Please check your subscriptions using /list and use the delete command again!"
            update.message.reply_text(message)
            return

        entries = FeedHandler.parse_feed(url[0], args_count)
        for entry in entries:
            message = "[" + url[1] + "] <a href='" + \
                entry.link + "'>" + entry.title + "</a>"
            print(message)

            try:
                update.message.reply_text(message, parse_mode=ParseMode.HTML)
            except Unauthorized:
                self.db.update_user(telegram_id=telegram_user.id, is_active=0)
            except TelegramError:
                # handle all other telegram related errors
                pass 
Example #23
Source File: simple_commands.py    From mau_mau_bot with GNU Affero General Public License v3.0 5 votes vote down vote up
def help_handler(bot, update):
    """Handler for the /help command"""
    help_text = _("Follow these steps:\n\n"
      "1. Add this bot to a group\n"
      "2. In the group, start a new game with /new or join an already"
      " running game with /join\n"
      "3. After at least two players have joined, start the game with"
      " /start\n"
      "4. Type <code>@unobot</code> into your chat box and hit "
      "<b>space</b>, or click the <code>via @unobot</code> text "
      "next to messages. You will see your cards (some greyed out), "
      "any extra options like drawing, and a <b>?</b> to see the "
      "current game state. The <b>greyed out cards</b> are those you "
      "<b>can not play</b> at the moment. Tap an option to execute "
      "the selected action.\n"
      "Players can join the game at any time. To leave a game, "
      "use /leave. If a player takes more than 90 seconds to play, "
      "you can use /skip to skip that player. Use /notify_me to "
      "receive a private message when a new game is started.\n\n"
      "<b>Language</b> and other settings: /settings\n"
      "Other commands (only game creator):\n"
      "/close - Close lobby\n"
      "/open - Open lobby\n"
      "/kill - Terminate the game\n"
      "/kick - Select a player to kick "
      "by replying to him or her\n"
      "/enable_translations - Translate relevant texts into all "
      "languages spoken in a game\n"
      "/disable_translations - Use English for those texts\n\n"
      "<b>Experimental:</b> Play in multiple groups at the same time. "
      "Press the <code>Current game: ...</code> button and select the "
      "group you want to play a card in.\n"
      "If you enjoy this bot, "
      "<a href=\"https://telegram.me/storebot?start=mau_mau_bot\">"
      "rate me</a>, join the "
      "<a href=\"https://telegram.me/unobotupdates\">update channel</a>"
      " and buy an UNO card game.")

    send_async(bot, update.message.chat_id, text=help_text,
               parse_mode=ParseMode.HTML, disable_web_page_preview=True) 
Example #24
Source File: description.py    From OpenCryptoBot with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_action(self, bot, update, args):
        if not args:
            update.message.reply_text(
                text=f"Usage:\n{self.get_usage()}",
                parse_mode=ParseMode.MARKDOWN)
            return

        if RateLimit.limit_reached(update):
            return

        coin = args[0].upper()
        data = None

        try:
            response = APICache.get_cg_coins_list()
        except Exception as e:
            return self.handle_error(e, update)

        for entry in response:
            if entry["symbol"].lower() == coin.lower():
                try:
                    data = CoinGecko().get_coin_by_id(entry["id"])
                except Exception as e:
                    return self.handle_error(e, update)
                break

        if not data or not data["description"]["en"]:
            update.message.reply_text(
                text=f"{emo.INFO} No data for *{coin}*",
                parse_mode=ParseMode.MARKDOWN)
            return

        coin_desc = data["description"]["en"]

        for message in utl.split_msg(coin_desc):
            update.message.reply_text(
                text=message,
                parse_mode=ParseMode.HTML,
                disable_web_page_preview=True) 
Example #25
Source File: utils.py    From tnt-village-bot with MIT License 5 votes vote down vote up
def notify_error(e: Exception, bot: Bot):
    text = 'An error occurred while executing a job (safely catched): <code>{}</code>'.format(html_escape(str(e)))
    if config.telegram.get('unexpected_exceptions_notifications', None):
        bot.send_message(config.telegram.unexpected_exceptions_notifications, text, parse_mode=ParseMode.HTML) 
Example #26
Source File: decorators.py    From tnt-village-bot with MIT License 5 votes vote down vote up
def failwithmessage_job(func):
    @wraps(func)
    def wrapped(context: CallbackContext, *args, **kwargs):
        try:
            return func(context, *args, **kwargs)
        except Exception as e:
            jobslogger = logging.getLogger('jobs')

            jobslogger.error('unexpected error while executing a job: %s', str(e), exc_info=True)
            text = 'An error occurred while executing a job: <code>{}</code>'.format(html_escape(str(e)))
            if config.telegram.get('unexpected_exceptions_notifications', None):
                context.bot.send_message(config.telegram.unexpected_exceptions_notifications, text, parse_mode=ParseMode.HTML)

    return wrapped 
Example #27
Source File: processing.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def send_newest_messages(self, url, post, user):
        post_update_date = DateHandler.parse_datetime(datetime=post.updated)
        url_update_date = DateHandler.parse_datetime(datetime=url[1])

        if post_update_date > url_update_date:
            message = "[" + user[7] + "] <a href='" + post.link + \
                "'>" + post.title + "</a>"
            try:
                self.bot.send_message(
                    chat_id=user[0], text=message, parse_mode=ParseMode.HTML)
            except Unauthorized:
                self.db.update_user(telegram_id=user[0], is_active=0)
            except TelegramError:
                # handle all other telegram related errors
                pass 
Example #28
Source File: blacklist.py    From Marie-2.0-English with GNU General Public License v3.0 5 votes vote down vote up
def blacklist(bot: Bot, update: Update, args: List[str]):
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]

    all_blacklisted = sql.get_chat_blacklist(chat.id)

    filter_list = BASE_BLACKLIST_STRING

    if len(args) > 0 and args[0].lower() == 'copy':
        for trigger in all_blacklisted:
            filter_list += "<code>{}</code>\n".format(html.escape(trigger))
    else:
        for trigger in all_blacklisted:
            filter_list += " - <code>{}</code>\n".format(html.escape(trigger))

    split_text = split_message(filter_list)
    for text in split_text:
        if text == BASE_BLACKLIST_STRING:
            msg.reply_text("There are no blacklisted messages here!")
            return
        msg.reply_text(text, parse_mode=ParseMode.HTML) 
Example #29
Source File: robotrss.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def about(self, bot, update):
        """
        Shows about information
        """

        message = "Thank you for using <b>RobotRSS</b>! \n\n If you like the bot, please recommend it to others! \n\nDo you have problems, ideas or suggestions about what the bot should be able to do? Then contact my developer <a href='http://cbrgm.de'>@cbrgm</a> or create an issue on <a href='https://github.com/cbrgm/telegram-robot-rss'>Github</a>. There you will also find my source code, if you are interested in how I work!"
        update.message.reply_text(message, parse_mode=ParseMode.HTML) 
Example #30
Source File: robotrss.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def help(self, bot, update):
        """
        Send a message when the command /help is issued.
        """

        message = "If you need help with handling the commands, please have a look at my <a href='https://github.com/cbrgm/telegram-robot-rss'>Github</a> page. There I have summarized everything necessary for you!"
        update.message.reply_text(message, parse_mode=ParseMode.HTML)