Python emoji.emojize() Examples

The following are 30 code examples of emoji.emojize(). 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 emoji , or try the search function .
Example #1
Source File: bridge.py    From hangoutsbot with GNU Affero General Public License v3.0 8 votes vote down vote up
def _relay_msg(self, msg, conv_id, image_id=None):
        try:
            user = Base.slacks[self.team].users[msg.user]["name"]
        except KeyError:
            # Bot message with no corresponding Slack user.
            user = msg.user_name
        try:
            source = Base.slacks[self.team].channels[msg.channel]["name"]
        except KeyError:
            source = self.team
        yield from self._send_to_internal_chat(conv_id,
                                               from_slack.convert(emoji.emojize(msg.text, use_aliases=True),
                                                                  Base.slacks[self.team]),
                                               {"source_user": user,
                                                "source_uid": msg.user,
                                                "source_title": source,
                                                "source_edited": msg.edited,
                                                "source_action": msg.action},
                                               image_id=image_id) 
Example #2
Source File: defaults.py    From terraform-compliance with MIT License 5 votes vote down vote up
def __init__(self):
        self.interactive_mode = self.detect_term()
        self.no_failure_tags = ['warning', 'no-failure', 'no-fail', 'info', 'nofailure', 'nofail', 'dontfail']
        self.case_sensitive_tags = ['case-sensitive', 'case_sensitive', 'casesensitive', 'case-sensitivity']
        self.no_skip_tags = ['noskip', 'no-skip', 'dontskip', 'failonskip', 'fail-on-skip']

        if '--no-ansi' in sys.argv or not sys.stdout.isatty():
            self.skip_colour = \
            self.warning_colour = \
            self.failure_colour = \
            self.info_colour = \
            self.yellow = \
            self.red = \
            self.green = \
            self.blue = \
                self.no_coloured_output

            self.info_icon = '*'
            self.warning_icon = '!'
            self.tada = ''
            self.icon = '>'

        else:
            self.skip_colour = colorful.bold_purple
            self.failure_colour = colorful.bold_red
            self.warning_colour = colorful.bold_yellow
            self.info_colour = colorful.bold_blue
            self.yellow = colorful.yellow
            self.red = colorful.red
            self.green = colorful.green
            self.blue = colorful.blue

            self.info_icon = emojize(':bulb:', use_aliases=True)
            self.warning_icon = emojize(':exclamation:', use_aliases=True)
            self.tada = emojize(':tada:', use_aliases=True)
            self.icon = emojize(':triangular_flag_on_post:', use_aliases=True)

        self.types_list = ['resource', 'variable', 'provider', 'data', 'resource that supports tags'] 
Example #3
Source File: facebook_messenger_conversation.py    From FacebookChatStatistics with MIT License 5 votes vote down vote up
def top_emojis(self, nbr):
        """Returns the top `nbr` emojis used and who sent them.

        Args:
            nbr (int): The number of emojis to include in top list.

        Returns:
            tuple: List of top emojis and dict showing how many of
                these were sent by each participant.

        """
        emojis = {e: 0 for e in iter(emoji.UNICODE_EMOJI.values())}
        emojis_p = {p: 0 for p in self.p}
        for p in emojis_p:
            emojis_p[p] = {e: 0 for e in iter(emoji.UNICODE_EMOJI.values())}
        for message in self.data['messages']:
            if 'content' in message and len(message) == 4:
                msg = message['content']
                sender = message['sender_name']
                for c in msg:
                    emoji_str = emoji.demojize(c)
                    if emoji_str in emojis:
                        emojis_p[sender][emoji_str] += 1
                        emojis[emoji_str] += 1
        top_emojis = [emoji_key for emoji_key, count in sorted(emojis.items(),
                                       key=lambda kv: (-kv[1], kv[0]))[:nbr]]
        emojis_count_p = {p: {} for p in self.p}
        for p in self.p:
                emojis_count_p[p] = [emojis_p[p][e] for e in top_emojis]
        top_emojis = [emoji.emojize(top_emoji) for top_emoji in top_emojis]
        return top_emojis, emojis_count_p 
Example #4
Source File: markdown_extensions.py    From allura with Apache License 2.0 5 votes vote down vote up
def handleMatch(self, m):
        emoji_code = m.group(2)
        return emoji.emojize(emoji_code, use_aliases=True) 
Example #5
Source File: helpers.py    From allura with Apache License 2.0 5 votes vote down vote up
def emojize(text):
    """Coverts emoji codes to unicode emojis"""
    return emoji.emojize(text, use_aliases=True) 
Example #6
Source File: utils.py    From allura with Apache License 2.0 5 votes vote down vote up
def get_reactions_json():
    """ Returns global reactions json """
    j = OrderedDict()
    for em in get_reaction_emoji_list():
        j[em] = emoji.emojize(em, use_aliases=True)
    return json.dumps(j) 
Example #7
Source File: __init__.py    From idiot with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(IdiotApp, self).__init__(*args, **kwargs)
        self.title = emoji.emojize(random.choice(list(config.ok_titles)), use_aliases=True)
        self.cm = CheckManager()
        self.quit_button = None
        self.update_menu()
        self.timer = rumps.Timer(self.cm.run_checks, config.check_interval)
        self.timer.start() 
Example #8
Source File: __init__.py    From idiot with MIT License 5 votes vote down vote up
def run_checks(self, _=None):
        log.debug("Running checks")
        all_ok = True
        for check in self.checks:
            log.debug("Running check {}".format(check))
            success, msg = check.run()
            check.last_result = (success, msg)
            if success:
                log.debug("Success: {}".format(msg))
                check.snooze_until = None
            else:
                all_ok = False
                log.error("Fail: {}".format(msg))
                if not check.snoozing:
                    log.debug("Sending notification")
                    rumps.notification("{} check failed".format(check.name), "", msg, data={"name": check.name},
                                       actionButton="Snooze", otherButton="Dismiss")
                else:
                    log.debug("Check is snoozing until {} - not sending notification".format(check.snooze_until))

        try:
            if self.last_ok != all_ok:
                self.last_ok = all_ok
                if all_ok:
                    app.title = emoji.emojize(random.choice(list(config.ok_titles)), use_aliases=True)
                else:
                    app.title = emoji.emojize(random.choice(list(config.not_ok_titles)), use_aliases=True)
            app.update_menu()
        except NameError:
            log.error("No app") 
Example #9
Source File: cliutils.py    From newrelic-lambda-cli with Apache License 2.0 5 votes vote down vote up
def warning(message):
    """Prints a warningmessage to the terminal"""
    click.echo(
        emoji.emojize(":heavy_exclamation_mark: %s" % message, use_aliases=True),
        color="blue",
    ) 
Example #10
Source File: cliutils.py    From newrelic-lambda-cli with Apache License 2.0 5 votes vote down vote up
def success(message):
    """Prints a success message to the terminal"""
    click.echo(
        emoji.emojize(":heavy_check_mark: %s" % message, use_aliases=True),
        color="green",
    ) 
Example #11
Source File: cliutils.py    From newrelic-lambda-cli with Apache License 2.0 5 votes vote down vote up
def failure(message, exit=False):
    """Prints a failure message to the terminal"""
    click.echo(
        emoji.emojize(":heavy_multiplication_x: %s" % message, use_aliases=True),
        color="red",
        err=True,
    )
    if exit:
        raise Exit(1) 
Example #12
Source File: cliutils.py    From newrelic-lambda-cli with Apache License 2.0 5 votes vote down vote up
def done(message):
    """Prints a done message to the terminal"""
    click.echo(emoji.emojize(":sparkles: %s :sparkles:" % message, use_aliases=True)) 
Example #13
Source File: models.py    From kaggler_ja_slack_archiver with MIT License 5 votes vote down vote up
def _conv_emoji(self, text):
        return emoji.emojize(text, use_aliases=True) 
Example #14
Source File: formatter.py    From slack-export-viewer with MIT License 5 votes vote down vote up
def render_text(self, message, process_markdown=True):
        message = message.replace("<!channel>", "@channel")
        message = message.replace("<!channel|@channel>", "@channel")
        message = message.replace("<!here>", "@here")
        message = message.replace("<!here|@here>", "@here")
        message = message.replace("<!everyone>", "@everyone")
        message = message.replace("<!everyone|@everyone>", "@everyone")
        message = self._slack_to_accepted_emoji(message)

        # Handle mentions of users, channels and bots (e.g "<@U0BM1CGQY|calvinchanubc> has joined the channel")
        message = self._MENTION_PAT.sub(self._sub_annotated_mention, message)
        # Handle links
        message = self._LINK_PAT.sub(self._sub_hyperlink, message)
        # Handle hashtags (that are meant to be hashtags and not headings)
        message = self._HASHTAG_PAT.sub(self._sub_hashtag, message)

        # Introduce unicode emoji
        message = emoji.emojize(message, use_aliases=True)

        if process_markdown:
            # Handle bold (convert * * to ** **)
            message = re.sub(r'\*', "**", message)

            message = markdown2.markdown(
                message,
                extras=[
                    "cuddled-lists",
                    # This gives us <pre> and <code> tags for ```-fenced blocks
                    "fenced-code-blocks",
                    "pyshell"
                ]
            ).strip()

        # Special handling cases for lists
        message = message.replace("\n\n<ul>", "<ul>")
        message = message.replace("\n<li>", "<li>")

        return message 
Example #15
Source File: message.py    From slack-export-viewer with MIT License 5 votes vote down vote up
def reactions(self):
        reactions = self._message.get("reactions", [])
        return [
            {
                "usernames": self.usernames(reaction),
                "name": emoji.emojize(':'+reaction.get("name")+':', use_aliases=True)
            }
            for reaction in reactions
        ] 
Example #16
Source File: emotbot.py    From Automate-it with MIT License 5 votes vote down vote up
def button(bot, update):
    query = update.callback_query
    if query.data == "1":
        em = emoji.emojize(':smile:', use_aliases=True)
        bot.editMessageText(text="Oh wow! %s " % em,
                        chat_id=query.message.chat_id,
                        message_id=query.message.message_id)

    if query.data == "2":
        em = emoji.emojize(':expressionless:', use_aliases=True)
        bot.editMessageText(text="Does it matter? %s " % em,
                        chat_id=query.message.chat_id,
                        message_id=query.message.message_id)

    if query.data == "3":
        em = emoji.emojize(':disappointed:', use_aliases=True)
        bot.editMessageText(text="Oh man! %s " % em,
                        chat_id=query.message.chat_id,
                        message_id=query.message.message_id) 
Example #17
Source File: models.py    From blog with Apache License 2.0 5 votes vote down vote up
def content_to_markdown(self):
        # 先转换成emoji然后转换成markdown,'escape':所有原始HTML将被转义并包含在文档中
        to_emoji_content = emoji.emojize(self.content, use_aliases=True)
        to_md = markdown.markdown(to_emoji_content,
                                  safe_mode='escape',
                                  extensions=[
                                      'markdown.extensions.extra',
                                      'markdown.extensions.codehilite',
                                  ])
        return to_md


# 文章评论区,据继承评论信息表 
Example #18
Source File: __main__.py    From PyPCAPKit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    """Entrypoint."""
    parser = get_parser()
    args = parser.parse_args()
    warnings.simplefilter('ignore')

    if args.format:
        fmt = args.format
    elif args.json:
        fmt = JSON
    elif args.plist:
        fmt = PLIST
    elif args.tree:
        fmt = TREE
    else:
        fmt = None

    extractor = Extractor(store=False, format=fmt,
                          fin=args.fin, fout=args.fout,
                          auto=args.verbose, files=args.files,
                          layer=args.layer, protocol=args.protocol,
                          engine=args.engine, extension=args.auto_extension)

    if not args.verbose:
        try:
            print(emoji.emojize(f":police_car_light: Loading file {extractor.input!r}"))
        except UnicodeEncodeError:
            print(f"[*] Loading file {extractor.input!r}")
        for _ in extractor:
            print(f' - Frame {extractor.length:>3d}: {extractor.protocol}')
        try:
            print(emoji.emojize(f":beer_mug: Report file{'s' if args.files else ''} stored in {extractor.output!r}"))
        except UnicodeEncodeError:
            print(f"[*] Report file{'s' if args.files else ''} stored in {extractor.output!r}") 
Example #19
Source File: solution_emoji.py    From tiny_python_projects with MIT License 5 votes vote down vote up
def main():
    """Make a jazz noise here"""

    args = get_args()
    verses = map(verse, range(1, args.num + 1))
    print(emoji.emojize('\n\n'.join(verses)), file=args.outfile)


# -------------------------------------------------- 
Example #20
Source File: slack.py    From hangoutsbot with GNU Affero General Public License v3.0 5 votes vote down vote up
def process_request(self, path, query_string, content):
        payload  = parse_qs(content)

        path = path.split("/")
        conversation_id = path[1]
        if not conversation_id:
            raise ValueError("conversation id must be provided in path")

        if "text" in payload:
            try:
                text = emoji.emojize(str(payload["text"][0]), use_aliases=True)
            except NameError: # emoji library likely missing
                text = str(payload["text"][0])
                
            if "user_name" in payload:
                if "slackbot" not in str(payload["user_name"][0]):
                    text = self._remap_internal_slack_ids(text)

                    user = payload["user_name"][0] + "@slack"
                    original_message = unescape(text)

                    message = "{}: {}".format(user, original_message)
                    passthru = {
                        "original_request": {
                            "message": original_message,
                            "image_id": None,
                            "segments": None,
                            "user": user },
                        "norelay": [ __name__ ]}

                    yield from self.send_data(
                        conversation_id,
                        message,
                        context = {
                            "base": {
                                'tags': ['slack', 'relay'], 
                                'source': 'slack', 
                                'importance': 50 },
                            "passthru": passthru }) 
Example #21
Source File: chatbridge_slack.py    From hangoutsbot with GNU Affero General Public License v3.0 5 votes vote down vote up
def process_request(self, path, query_string, content):
        payload  = parse_qs(content)

        path = path.split("/")
        conv_id = path[1]
        if not conv_id:
            raise ValueError("conversation id must be provided in path")

        if "text" in payload:
            try:
                text = emoji.emojize(str(payload["text"][0]), use_aliases=True)
            except NameError: # emoji library likely missing
                text = str(payload["text"][0])

            if "user_name" in payload:
                if "slackbot" not in str(payload["user_name"][0]):
                    file_upload = re.search(r"<@[A-Z0-9]+\|.*?> uploaded a file: (<https?://.*?>)", text)
                    if file_upload:
                        text = re.sub(r"<@[A-Z0-9]+\|.*?> uploaded a file:", "uploaded", text)
                        # make the link clickable in hangouts
                        match = file_upload.group(1)
                        tokens = match[1:-1].rsplit("|", 1)
                        full_link = tokens[0]
                        file_name = tokens[1]
                        text = re.sub(re.escape(match), "{} with title \"{}\"".format(full_link, file_name), text)

                    text = self._slack_label_users(text)
                    text = self._slack_label_channels(text)

                    user = payload["user_name"][0] + "@slack"
                    original_message = unescape(text)

                    # cheat and use an an external variable to reach BridgeInstance

                    yield from _externals['BridgeInstance']._send_to_internal_chat(
                        conv_id,
                        original_message,
                        {   "source_user": user,
                            "source_title": False }) 
Example #22
Source File: botmoji.py    From neural_chat with MIT License 5 votes vote down vote up
def emojize_text(self, text, maxemojis, minconfidence):
        prob = self.encode(text)

        # Top emoji ID
        emoji_ids = top_emojis(prob, maxemojis, minconfidence)
        if len(emoji_ids) == 0:
            return ''

        # Map to emojis
        emojis = map(lambda x: EMOJIS[x], emoji_ids)
        return emoji.emojize(' '.join(emojis), use_aliases=True) 
Example #23
Source File: player.py    From PyRoyale with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, client, name, team, match, skin):
        self.client = client
        self.server = client.server
        self.match = match
        self.skin = skin
        
        self.name = ' '.join(emoji.emojize(re.sub(r"[^\x00-\x7F]+", "", emoji.demojize(name)).strip())[:20].split()).upper()
        self.team = team
        if len(self.team) > 0 and self.server.checkCurse(self.name):
            self.name = str()
        if len(self.name) == 0:
            self.name = self.server.defaultName
        self.pendingWorld = None
        self.level = int()
        self.zone = int()
        self.posX = int()
        self.posY = int()
        self.dead = True
        self.win = bool()
        self.voted = bool()
        self.loaded = bool()
        self.lobbier = bool()
        self.lastUpdatePkt = None

        self.trustCount = int()
        self.lastX = int()
        self.lastXOk = True
        
        self.id = match.addPlayer(self) 
Example #24
Source File: test_studierendenwerk.py    From OmNomNom with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_parse_sample_menu(studierendenwerk_sample: str):
    parsed = studierendenwerk.parse_menu(studierendenwerk_sample)
    assert parsed == emojize('*Group 1*\n'
                             ':fish: Group 1 Item 1: *1,75€*\n'
                             '\n*Group 2*\n'
                             ':seedling: Group 2 Item 1: *1,75€*\n'
                             ':seedling: Group 2 Item 2: *0,65€*\n'
                             '\n*Group 3*\n'
                             ':seedling: Group 3 Item 1: *0,60€*\n'
                             '\n*Group 4*\n'
                             ':seedling: Group 4 Item 1: *1,90€*\n'
                             ':poultry_leg: Group 4 Item 2: *1,75€*\n'
                             ':poultry_leg: Group 4 Item 3: *1,35€*\n'
                             '\n*Group 5*\n'
                             ':seedling: Group 5 Item 1: *0,60€*\n'
                             ':seedling: Group 5 Item 2: *0,60€*\n'
                             ':seedling: Group 5 Item 3: *0,60€*\n'
                             '\n*Group 6*\n'
                             ':ear_of_corn: Group 6 Item 1: *0,65€*') 
Example #25
Source File: inlinequeries.py    From BotListBot with MIT License 5 votes vote down vote up
def category_article(cat):
    cat_bots = Bot.of_category_without_new(cat)
    txt = messages.PROMOTION_MESSAGE + '\n\n'
    txt += "There are *{}* bots in the category *{}*:\n\n".format(len(cat_bots), str(cat))
    txt += '\n'.join([str(b) for b in cat_bots])
    return InlineQueryResultArticle(
        id=uuid4(),
        title=emoji.emojize(cat.emojis, use_aliases=True) + cat.name,
        input_message_content=InputTextMessageContent(message_text=txt,
                                                      parse_mode=ParseMode.MARKDOWN),
        description=cat.extra,
        # thumb_url='https://pichoster.net/images/2017/03/13/cfa5e29e29e772373242bc177a9e5479.jpg'
    ) 
Example #26
Source File: country.py    From BotListBot with MIT License 5 votes vote down vote up
def emojized(self):
        return emoji.emojize(self.emoji, use_aliases=True) 
Example #27
Source File: category.py    From BotListBot with MIT License 5 votes vote down vote up
def __str__(self):
        return '•' + emoji.emojize(self.emojis, use_aliases=True) + self.name + \
               (' - ' + self.extra if self.extra else '') 
Example #28
Source File: mdformat.py    From BotListBot with MIT License 5 votes vote down vote up
def results_list(args, prefix=''):
    # TODO make this method recursive
    result = '```'
    memo = emoji.emojize(':memo:', use_aliases=True)
    if isinstance(args, dict):
        for value in args.values():
            if isinstance(value, list):
                # TODO: doesnt work
                for s in value:
                    result += '\n{} {}'.format(memo, s)
            else:
                result += '\n{} {}'.format(memo, value)

    result += '```'
    return result 
Example #29
Source File: comment_util.py    From FacebookPy with GNU General Public License v3.0 4 votes vote down vote up
def comment_image(browser, username, comments, blacklist, logger, logfolder, Settings):
    """Checks if it should comment on the image"""
    # check action availability
    if quota_supervisor(Settings, "comments") == "jump":
        return False, "jumped"

    rand_comment = random.choice(comments).format(username)
    rand_comment = emoji.demojize(rand_comment)
    rand_comment = emoji.emojize(rand_comment, use_aliases=True)

    open_comment_section(browser, logger)
    comment_input = get_comment_input(browser)

    try:
        if len(comment_input) > 0:
            comment_input[0].clear()
            comment_input = get_comment_input(browser)
            # below, an extra space is added to force
            # the input box to update the reactJS core
            comment_to_be_sent = rand_comment + " "

            browser.execute_script(
                "arguments[0].value = arguments[1];",
                comment_input[0],
                comment_to_be_sent,
            )
            # below, it also will remove that extra space added above
            # COS '\b' is a backspace char in ASCII
            comment_input[0].send_keys("\b")
            comment_input = get_comment_input(browser)
            comment_input[0].submit()
            update_activity(Settings, "comments")

            if blacklist["enabled"] is True:
                action = "commented"
                add_user_to_blacklist(
                    username, blacklist["campaign"], action, logger, logfolder
                )
        else:
            logger.warning(
                "--> Comment Action Likely Failed!" "\t~comment Element was not found"
            )
            return False, "commenting disabled"

    except InvalidElementStateException:
        logger.warning(
            "--> Comment Action Likely Failed!"
            "\t~encountered `InvalidElementStateException` :/"
        )
        return False, "invalid element state"

    logger.info("--> Commented: {}".format(rand_comment.encode("utf-8")))

    # get the post-comment delay time to sleep
    naply = get_action_delay("comment", Settings)
    sleep(naply)

    return True, "success" 
Example #30
Source File: reddit.py    From rowboat with MIT License 4 votes vote down vote up
def send_post(self, config, channel, data):
        if config.mode is FormatMode.PLAIN:
            channel.send_message('**{}**\n{}'.format(
                data['title'],
                'https://reddit.com{}'.format(data['permalink'])
            ))
        else:
            embed = MessageEmbed()

            if 'nsfw' in data and data['nsfw']:
                if not config.nsfw:
                    return
                embed.color = 0xff6961
            else:
                embed.color = 0xaecfc8

            # Limit title to 256 characters nicely
            if len(data['title']) > 256:
                embed.title = data['title'][:253] + '...'
            else:
                embed.title = data['title']

            embed.url = u'https://reddit.com{}'.format(data['permalink'])
            embed.set_author(
                name=data['author'],
                url=u'https://reddit.com/u/{}'.format(data['author'])
            )

            image = None

            if data.get('media'):
                if 'oembed' in data['media']:
                    image = data['media']['oembed']['thumbnail_url']
            elif data.get('preview'):
                if 'images' in data['preview']:
                    image = data['preview']['images'][0]['source']['url']

            if 'selftext' in data and data['selftext']:
                # TODO better place for validation
                sz = min(64, max(config.text_length, 1900))
                embed.description = data['selftext'][:sz]
                if len(data['selftext']) > sz:
                    embed.description += u'...'
                if image:
                    embed.set_thumbnail(url=image)
            elif image:
                embed.set_image(url=image)

            if config.include_stats:
                embed.set_footer(text=emoji.emojize('{} upvotes | {} downvotes | {} comments'.format(
                    data['ups'], data['downs'], data['num_comments']
                )))

            channel.send_message('', embed=embed)