예제 #1
2
def statusUpdateResponse():
    statusCur = db.cursor()
    statusCur.execute("SELECT * FROM tracklist")
    rows = statusCur.fetchall()
    if len(rows) < 1:
        return
    else:
        try:
            for row in rows:
                curStatus = row[19]
                m=str(row[0])
                newRow = getRow(m)
                newStatus = statusList(newRow[19])
                chat_id = str(row[20])
                if newStatus != curStatus and (newStatus != "Gereed"):
                    updateCur = db.cursor()
                    query = 'UPDATE tracklist SET huidige_planplaats=? WHERE id=? and chat_id=?'
                    updateCur.execute(query, (newStatus,str(row[0]),str(row[20]),))
                    db.commit()
                    bot.send_message(chat_id,emoji.emojize(":new: - updated!\n/"+str(row[0])+"\n"+str(row[1])+"\nvan: "+str(curStatus)+"\nnaar::round_pushpin:"+str(newStatus), use_aliases=True))
                    break
                if newStatus == "Gereed":
                    bot.send_message(chat_id,emoji.emojize("completed!:checkered_flag:\n/"+str(row[0])+"\n"+str(row[1])+"\nvan: "+str(curStatus)+"\nnaar: :package:"+str(newStatus)+"\njob verwijderd uit je /tracklist.", use_aliases=True))
                    curDel = db.cursor()
                    query = "DELETE from tracklist where id is ? and chat_id is ?"
                    curDel.execute(query, (str(row[0]),str(row[20]),))
                    db.commit()
                    break
        except Exception as e:
            bot.send_message('kevinJelsChatID', "error in statusUpdateResponse")
            print (e)
    threading.Timer(15, statusUpdateResponse).start()
 def process_action(self, action, node):
     """ Helper function for processing actions, finds out what does each action do and sets the appropriate attributed of the node
     :param obj action The action to be processed.
     :param obj node The node to be changed."""
     if action.isFormat:
         node.add_emoji("Fmt:")
         node.addAttribute("action", "Format")
     else:
         node.add_emoji("Dev:")
         node.addAttribute("action", "Device")
     if action.isDestroy or action.isRemove:
         print("Adding action: Delete for node: " + node.getName())
         node.addAttribute("action", "delete")
         node.change_color(self.pallete.complement["2"])
         node.add_emoji(emoji.emojize(":fire:"))
     if action.isCreate or action.isAdd:
         print("Adding action: Add for node: " + node.getName())
         node.addAttribute("action", "add")
         node.change_color(self.pallete.primary["2"])
         node.add_emoji(emoji.emojize(":building_construction:"))
     if action.isResize or action.isShrink or action.isGrow:
         print("Adding action: Resize for node: " + node.getName())
         node.addAttribute("action", "resize")
         node.change_color(self.pallete.secondary_second["2"])
         node.add_emoji(emoji.emojize(":wrench:"))
예제 #3
0
파일: __init__.py 프로젝트: y011/idiot
    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")
예제 #4
0
 def remove_admin(root_cid, admin_user, auth_user):
     msg = bot.send_message(root_cid, emojize(
         'Going to downgrade the Admin: {0} :smirking_face:\n'.format(admin_user)))
     deleted_rows = admin_user.delete_instance()
     bot.edit_message_text(emojize(
         'Done! Downgraded successfully for user: {0} :thumbs_up_sign: \n'
         '(deleted rows: {1})'.format(auth_user, deleted_rows)), root_cid, msg.message_id)
예제 #5
0
def get_emoji(image_bin):
    with open('img.jpg', 'wb') as img_file:  
        img_file.write(image_bin)
        image = Image.open('img.jpg')

        return emoji.emojize(face_recognition.classify_image(image))

    return emoji.emojize(':pile_of_poo:')
예제 #6
0
파일: utils.py 프로젝트: P-KID/Todo.py
def format_show(idx, status, text):
    e = EMOJI.get(status, None)
    if e is None:
        raise
    if idx == -1:
        print emoji.emojize(' {}  {}'.format(e, text), use_aliases=True)
    else:
        print emoji.emojize('{}. {}  {}'.format(idx, e, text), use_aliases=True)
예제 #7
0
 def print_badges(cls):
     print emoji.emojize(
         Badges.NOTHING[1] + ": " + Badges.NOTHING[2] + " | " + Badges.NOTHING[3] + ": " + Badges.NOTHING[4] + "\n" +
         Badges.FIRST[1] + ": " + Badges.FIRST[2] + " | " + Badges.FIRST[3] + ": " + Badges.FIRST[4] + "\n" +
         Badges.SECOND[1] + ": " + Badges.SECOND[2] + " | " + Badges.SECOND[3] + ": " + Badges.SECOND[4] + "\n" +
         Badges.THIRD[1] + ": " + Badges.THIRD[2] + " | " + Badges.THIRD[3] + ": " + Badges.THIRD[4] + "\n" +
         Badges.FOURTH[1] + ": " + Badges.FOURTH[2] + " | " + Badges.FOURTH[3] + ": " + Badges.FOURTH[4] + "\n" +
         Badges.FIFTH[1] + ": " + Badges.FIFTH[2] + " | " + Badges.FIFTH[3] + ": " + Badges.FIFTH[4] + "\n" +
         Badges.SIXTH[1] + ": " + Badges.SIXTH[2] + " | " + Badges.SIXTH[3] + ": " + Badges.SIXTH[4],
         use_aliases=True)
예제 #8
0
def test_emoji_names():

    for use_aliases, group in (
        (False, emoji.unicode_codes.EMOJI_UNICODE),
        (True, emoji.unicode_codes.EMOJI_ALIAS_UNICODE),
    ):
        for name, ucode in group.items():
            assert name.startswith(":") and name.endswith(":") and len(name) >= 3
            emj = emoji.emojize(name, use_aliases=use_aliases)
            assert emj == ucode, "%s != %s" % (emoji.emojize(name), ucode)
예제 #9
0
def main_menu_keyboard(user_db, update=None, session=None):
    if not user_db:
        db_object = UserProfile(
            chat_id=update.message.chat_id,
            notify_sound=True,
            spy=False,
            notify_timer=False
        )
        session.add(db_object)
        session.commit()
        status_notifications = emojize(':no_entry_sign:', use_aliases=True)
        status_sound = emojize(":white_check_mark:", use_aliases=True)
        status_timer = emojize(':no_entry_sign:', use_aliases=True)
    else:
        if user_db.spy:
            status_notifications = emojize(":white_check_mark:", use_aliases=True)
        else:
            status_notifications = emojize(':no_entry_sign:', use_aliases=True)

        if user_db.notify_sound:
            status_sound = emojize(":white_check_mark:", use_aliases=True)
        else:
            status_sound = emojize(':no_entry_sign:', use_aliases=True)

        if user_db.notify_timer:
            status_timer = emojize(":white_check_mark:", use_aliases=True)
        else:
            status_timer = emojize(':no_entry_sign:', use_aliases=True)

    button_list = [
        [KeyboardButton('Новинки'), KeyboardButton('Уведомления ' + status_notifications)],
        [KeyboardButton('Настройка расписания уведомлений ' + status_timer)],
        [KeyboardButton('Звук уведомлений ' + status_sound)]
    ]
    return ReplyKeyboardMarkup(button_list, resize_keyboard=True)
예제 #10
0
파일: mogui.py 프로젝트: notptr/mogui-BBS
def showMessage(db, gid, mid, term):
    topicMsg = db['messages']
    topics = topicMsg.find(gid=gid,mid=mid)
    
    for topic in topics:
        print(term.green + "Author: " + term.normal + topic['msgStarter'])
        print(term.green + "Topic: " + term.normal + emojize(topic['subject']))
        print(term.green + "Date: " + term.normal + topic['date'])
        print("------------------------------------------------------------------------------------------------------------")
        print()
        print()
        print(emojize(topic['message']))
예제 #11
0
파일: ignition.py 프로젝트: djk121/ignition
def fire(ser, pins, dry_run=True):
    for pin in pins:
        print (emoji.emojize(" :fire:  :fireworks: "), end="")
        if not dry_run:
            ser.write(struct.pack("cb", b'H', pin))
            status = ser.read()
            if status != b'A':
                return pin
        else:
            print("XXX DRY RUN XXX", end="")
        print(emoji.emojize(" :sparkles: "), end="")
    print("\n")
    return 0
예제 #12
0
파일: ignition.py 프로젝트: djk121/ignition
def comm_check(ser, dry_run=True):
    print("Checking serial connectivity:")
    print(emoji.emojize(" :clock1: ", use_aliases=True), end="")
    if not dry_run:
        ser.write(struct.pack("cb", b'K', 0))
        status = ser.read()
        if status != b'A':
            print(emoji.emojize(" :x: ", use_aliases=True))
            return 1
    else:
        print("XXX DRY RUN XXX", end="")
    print(emoji.emojize(" :100: ", use_aliases=True), end="")
    print("\n")
    return 0
예제 #13
0
    def __sub__(self, other):
        """What happens when you subtract two animals"""

        if other in self.best_friends:
            self.best_friends.remove(other)
            self.frenemies.add(other)
            print emoji.emojize(self.anguished, use_aliases=True)

            return"{} is now {} frenemy".format(other.name, (self.name + '\'s'))

        self.mortal_enemy.add(other)

        print emoji.emojize(self.anger, use_aliases=True)
        return"{} is {} mortal enemy".format(other.name, (self.name + '\'s'))
예제 #14
0
파일: Client.py 프로젝트: hawkins/Shawk
    def __sendmail(self, address, text, emojize=None):
        """Send the content of message to address"""

        # Check if emojize was specified
        if emojize is not None:
            # If so, follow its rule
            if emojize:
                text = emoji.emojize(text, use_aliases=True)
        else:
            # Otherwise, follow client rule
            if self.emojize:
                text = emoji.emojize(text, use_aliases=True)

        return self.smtp.sendmail('0', address, text)
예제 #15
0
 def add_user_from_type(m, class_type):
     cid = m.chat.id
     try:
         text = m.text.split(' ', 1)[1]
         try:
             tg_user = username_or_telegram_id(text)
             try:
                 class_type.create_from_telegram_user(tg_user, blocked=False, access_requested_count=0)
                 bot.send_message(cid, emojize('Done! :thumb_up_sign:'))
             except UserAlreadyException as e:
                 bot.send_message(cid, emojize('{0}.. :neutral_face:'.format(e)))
         except ParseException as e:
             bot.send_message(cid, str(e))
     except IndexError as e:
         pass
예제 #16
0
    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)
                    response = "<b>" + str(payload["user_name"][0]) + ":</b> " + unescape(text)
                    response += self._bot.call_shared("reprocessor.attach_reprocessor", _slack_repeater_cleaner)

                    yield from self.send_data( conversation_id, 
                                               response, 
                                               context = { 'base': {
                                                                'tags': ['slack', 'relay'], 
                                                                'source': 'slack', 
                                                                'importance': 50 }} )
예제 #17
0
파일: repos.py 프로젝트: vuonghv/letgithub
def view_list_repos(username: str):
    g = config['GITHUB']
    try:
        repositories = g.get_user(username).get_repos()
        for repo in repositories:
            name = repo.name
            name = _color_field('name', name)

            desc = 'Description: {}'.format(repo.description) if repo.description else ''
            desc = _color_field('description', desc) if desc else ''

            stars = ':star: {}'.format(repo.stargazers_count)
            stars = _color_field('stargazers_count', stars)

            forks = ':whale: {}'.format(repo.forks_count)
            forks = _color_field('forks_count', forks)

            upd_at = repo.updated_at
            upd_at = _color_field('updated_at', upd_at)

            parent = repo.parent.full_name if repo.parent else ''
            parent = _color_field('parent', parent) if parent else ''
 
            template = ('{name}  {stars_count}  {forks_count}\n',
                        'forked from {parent}\n' if parent else '{parent}',
                        '{description}\n' if desc else '{description}',
                        'Updated on {updated_at}',)
            template = ''.join(template)
            info = template.format(name=name, stars_count=stars,
                                    forks_count=forks, parent=parent,
                                    description=desc, updated_at=upd_at)
            info = align_text(info, LEFT_MARGIN, MAX_WIDTH)
            print(emoji.emojize(info), '\n')
    except UnknownObjectException as err:
        perr(red(err))
예제 #18
0
 def run(self):
     while True:
         # Get the work from the queue and expand the tuple
         msg = self.queue.get()
         
         payload = { 'secret' : self.key }
         
         try:
             if self.filterMsg(msg):
                 continue
             
             # msg.extras['url'] # maybe later. supported since errbot 5.0
             
             tsStruct = self.extractTimestamp(msg)
             
             payload['time'] = '{:02d}:{:02d}'.format(tsStruct.tm_hour, tsStruct.tm_min)
             payload['nick'] = str(msg.frm.person)[1:]
             
             try:
                 payload['post'] = emoji.emojize(msg.body, use_aliases=True)
             except NameError:
                 payload['post'] = msg.body # no emoji support, continue without
             
             try:
                 if self.key is not None: # simply discard if no key has been configured
                     r = requests.post('https://happyshooting.de/live/add_line.php', data=payload, timeout=0.5);
                     self.log.debug("request sent " + r.url + " -> " + str(r))
                 else:
                     self.log.debug("no key, discarding")
             except requests.exceptions.RequestException as e:
                 self.log.exception("failed to forward message to HSLive Slack Stream")
         except Exception as e:
             self.log.exception("something went wrong")
         
         self.queue.task_done()
예제 #19
0
 def sub_standard_emoji(m):
     text = m.group(1)
     subbed = emoji.emojize(text, use_aliases=True)
     if subbed != text:
         return "<span title='%s'>%s</span>" % (text, subbed)
     else:
         return text
예제 #20
0
파일: users.py 프로젝트: vuonghv/letgithub
def show_user(username: str=None, *args, **kwagrs):
    g = config.get('GITHUB')
    try:
        user = g.get_user(username) if username else g.get_user()
        login = _color_field('login', ':smiling_imp: {}'.format(user.login))
        name = _color_field('name', user.name)
        email = _color_field('email', 'Email: {}'.format(user.email))
        company = _color_field('company', 'Company: {}'.format(user.company))
        location = _color_field('location', 'Location: {}'.format(user.location))
        blog = _color_field('blog', 'Blog: {}'.format(user.blog))
        bio = _color_field('bio', 'bio: {}'.format(user.bio))
        public_repos = _color_field('public_repos', '{} repositories'.format(user.public_repos))
        public_gists = _color_field('public_gists', '{} gists'.format(user.public_gists))
        followers = _color_field('followers', '{} followers'.format(user.followers))
        following = _color_field('following', '{} following'.format(user.following))
        joined_at = _color_field('created', 'joined at {}'.format(user.created_at))

        template = ('{login} ({name})\n'
                    '{email}\n'
                    '{company}  {location}\n'
                    '{blog}\n'
                    '{bio}\n'
                    '{public_repos}  {public_gists}\n'
                    '{followers}  {following}\n'
                    '{joined_at}')
        info = template.format(login=login, name=name, email=email,
                                company=company, location=location,
                                blog=blog, bio=bio, public_repos=public_repos,
                                public_gists=public_gists, followers=followers,
                                following=following, joined_at=joined_at)
        info = align_text(info, left_margin=2, max_width=100)
        print(emoji.emojize(info))
    except UnknownObjectException:
        perr(red('user `{}` not found!'.format(username)))
예제 #21
0
def comment_image(browser, comments):
  """Checks if it should comment on the image"""
  rand_comment = (choice(comments))
  rand_comment = emoji.demojize(rand_comment)
  rand_comment = emoji.emojize(rand_comment, use_aliases=True)



  comment_input = browser.find_elements_by_xpath('//textarea[@placeholder = "Add a comment…"]')
  if len(comment_input) <= 0:
    comment_input = browser.find_elements_by_xpath('//input[@placeholder = "Add a comment…"]')

  if len(comment_input) > 0:
    browser.execute_script("arguments[0].value = '" + rand_comment + " ';", comment_input[0]);
    #An extra space is added here and then deleted. This forces the input box to update the reactJS core
    comment_input[0].send_keys("\b")
    comment_input[0].submit()
  else:
    print(u'--> Warning: Comment Action Likely Failed: Comment Element not found')
    # print(u'--> Commented: {}'.format(rand_comment))
  #print("--> Commented: " + rand_comment.encode('utf-8'))
  print("--> Commented: {}".format(rand_comment.encode('utf-8')))
  sleep(2)


  return 1
예제 #22
0
    def _render_text(self, message):
        message = message.replace("<!channel>", "@channel")
        message = self._slack_to_accepted_emoji(message)
        # Handle "<@U0BM1CGQY|calvinchanubc> has joined the channel"
        message = re.sub(r"<@U\d\w+\|[A-Za-z0-9.-_]+>",
                         self._sub_annotated_mention, message)
        # Handle "<@U0BM1CGQY>"
        message = re.sub(r"<@U\d\w+>", self._sub_mention, message)
        # Handle links
        message = re.sub(
            # http://stackoverflow.com/a/1547940/1798683
            # TODO This regex is likely still incomplete or could be improved
            r"<(https|http|mailto):[A-Za-z0-9_\.\-\/\|\?\,\=\#\:\@]+>",
            self._sub_hyperlink, message
        )
        # Handle hashtags (that are meant to be hashtags and not headings)
        message = re.sub(r"(^| )#[A-Za-z0-9\.\-\_]+( |$)",
                         self._sub_hashtag, message)
        # Handle channel references
        message = re.sub(r"<#C0\w+>", self._sub_channel_ref, message)
        # Handle italics (convert * * to ** **)
        message = re.sub(r"(^| )\*[A-Za-z0-9\-._ ]+\*( |$)",
                         self._sub_bold, message)
        # Handle italics (convert _ _ to * *)
        message = re.sub(r"(^| )_[A-Za-z0-9\-._ ]+_( |$)",
                         self._sub_italics, message)

        # Escape any remaining hash characters to save them from being turned
        #  into headers by markdown2
        message = message.replace("#", "\\#")

        message = markdown2.markdown(
            message,
            extras=[
                "cuddled-lists",
                # Disable parsing _ and __ for em and strong
                # This prevents breaking of emoji codes like :stuck_out_tongue
                #  for which the underscores it liked to mangle.
                # We still have nice bold and italics formatting though
                #  because we pre-process underscores into asterisks. :)
                "code-friendly",
                "fenced-code-blocks",
                "pyshell"
            ]
        ).strip()
        # markdown2 likes to wrap everything in <p> tags
        if message.startswith("<p>") and message.endswith("</p>"):
            message = message[3:-4]

        # Newlines to breaks
        # Special handling cases for lists
        message = message.replace("\n\n<ul>", "<ul>")
        message = message.replace("\n<li>", "<li>")
        # Indiscriminately replace everything else
        message = message.replace("\n", "<br />")

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

        return message
예제 #23
0
    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)
                    # strip out formatted links and use the second group because
                    # we don't normally format links in normal chat
                    text = re.sub(r"\<([^<>]+?)\|([^<>]+?)\>", r"\2", text)
                    response = "<b>" + str(payload["user_name"][0]) + ":</b> " + unescape(text)
                    response += self._bot.call_shared("reprocessor.attach_reprocessor", _slack_repeater_cleaner)

                    yield from self.send_data(
                        conversation_id,
                        response,
                        context={"base": {"tags": ["slack", "relay"], "source": "slack", "importance": 50}},
                    )
예제 #24
0
파일: slack.py 프로젝트: jmduke/corji
def slack_corgi():
    from_name = request.values.get('user_name', '')
    from_team = request.values.get('team_domain', '')
    text = request.values.get('text', '')
    text = text.strip()
    corgis = {}
    if text_contains_emoji(text):
        emoji = text
        corgis = api.get(emoji)
        if not corgis['count']:
            response_content = generate_slack_failure_case_message(
                'Oh no! No corgi found for emoji {},' +
                ' try sending us a different one!'.format(emoji)),
            return Response(response_content, mimetype='application/json')
    else:
        detected_emoji = emojize(text, use_aliases=True)
        if len(detected_emoji) != len(text):
            corgis = api.get(detected_emoji)
    if not corgis or not corgis['count']:
        response_content = generate_slack_failure_case_message(
            'Oh no! No emoji detected in your message! ' +
            'Try sending us an emoji!')
        return Response(response_content, mimetype='application/json')

    corgi_url = random.choice(corgis['results'])
    response_content = generate_slack_corgi_case(corgi_url)
    return Response(response_content, mimetype='application/json')
예제 #25
0
파일: emojinal.py 프로젝트: sprax/python
def test_misc():
    trans()
    print(u'\U0001f604'.encode('unicode-escape'))
    print(u'\U0001f604')
    ss = u'\U0001f604'
    xx = chr(ss[0])
    print("ss({}) xx({})".format(ss, xx))
    # -*- coding: UTF-8 -*-
    #convert to unicode
    teststring =  "I am happy \U0001f604"
    # #teststring = unicode(teststring, 'utf-8')

    #encode it with string escape
    teststring = teststring.encode('unicode_escape')
    print("💗 Growing Heart")
    print(emoji.emojize('Water! :water_wave:'))
    print(emoji.demojize(u'🌊')) # for Python 2.x
# print(emoji.demojize('🌊')) # for Python 3.x.
    print(u"And \U0001F60D")
    print("(-woman) astronaut", chr(int("0001f680", 16)))
    print("woman_astronaut", chr(int("0x0001f680", 0)))

    print("\U0001f483\U0001f3fe")

    print(chr(0x001f483),chr(0x001f3fe))
    print('💃 🏾 ')
    print(chr(0x001f483)+chr(0x001f3fe))
    print('💃🏾 ')
    print(chr(int('1f483',16))+chr(int('1f3fe',16)))
    print('%8s %8s %8s' % qw_tuple('surf wave whitecap'))
    print("('%s', '%s', '%s')" % qw_tuple("surf's-up wave rip-curl"))
예제 #26
0
파일: models.py 프로젝트: matmegat/emotalk
def drop_updated(sender, instance=None, created=False, **kwargs):
	if created:
		if instance.to_user.push_new_msg:
			devices = DropDevice.objects.filter(user=instance.to_user)
			msg = '@%s sent you a %s drop' % (instance.from_user.username, settings.DROP_EMOJI[instance.emoji])
			msg = emoji.emojize(msg, use_aliases=True)
			devices.send_message(msg, True, extra={'type': 'drop', 'id': instance.id})
예제 #27
0
파일: baht.py 프로젝트: mdellavo/baht
    def emoji(self, bot, event, args):
        if not args:
            return

        rv = emoji.emojize(":" + args[0] + ":", use_aliases=True)
        if args[0] not in rv:
            bot.say(rv)
예제 #28
0
 def statusCheck(self):
     print(emojize(GIT_STATUS))
     n = len(cs.STYLES)
     output = []
     for idx,repo in enumerate(self.repos):
         name = getName(repo)
         title = cs.STYLES[idx % n].format('{}'.format(name.ljust(10)))
         r = git.Repo(repo)
         try:
             branch = r.active_branch.name.ljust(10)
         except Exception, e:
             print 'error in repo {0}\n{1}'.format(name, e)
         diff = r.index.diff(None)
         emoj = ':white_check_mark:' if len(diff) == 0 else ':exclamation:'*len(diff)
         result = emojize('{0}\t{1}\t{2}'.format(title, branch, emoj), use_aliases=True)
         output.append(result)
예제 #29
0
    def __add__(self, other):
        """What happens when you add two animals"""

        if self.cranky > 7 or self.friendly < 3:
            if other in self.best_friends:
                self.best_friends.remove(other)

            self.mortal_enemy.add(other)
            print emoji.emojize(self.anger, use_aliases=True)

            return"{} is {} mortal enemy".format(other.name, (self.name + '\'s'))

        self.best_friends.add(other)

        print emoji.emojize(self.smile, use_aliases=True),  emoji.emojize(other.smile, use_aliases=True)

        return "{} is {} best friend".format(other.name, (self.name + '\'s'))
예제 #30
0
def test_emojize_complicated_string():
    # A bunch of emoji's with UTF-8 strings to make sure the regex expression is functioning
    name_code = {
        ':flag_for_Ceuta_&_Melilla:': u'\U0001F1EA \U0001F1E6',
        ':flag_for_St._Barthélemy:': u'\U0001F1E7 \U0001F1F1',
        ':flag_for_Côte_d’Ivoire:': u'\U0001F1E8 \U0001F1EE',
        ':flag_for_Åland_Islands:': u'\U0001F1E6 \U0001F1FD',
        ':flag_for_São_Tomé_&_Príncipe:': u'\U0001F1F8 \U0001F1F9',
        ':flag_for_Curaçao:': u'\U0001F1E8 \U0001F1FC'
    }
    string = ' complicated! '.join(list(name_code.keys()))
    actual = emoji.emojize(string, False)
    expected = string
    for name, code in name_code.items():
        expected = expected.replace(name, code)
    expected = emoji.emojize(actual, False)
    assert expected == actual, "%s != %s" % (expected, actual)
예제 #31
0
#Para importar uma um modulo(biblioteca) inteira de bebidas: import bebidas
#Para eu importar apenas um item do modulo(biblioteca) bebidas eu dou: from bebidas import cafe
#Para eu importar apenas um item ou mais que um do modulo(biblioteca) bebidas eu dou: from bebidas import cafe, cha, agua
import math
import random
import emoji

#Metodo para fazer a raiz de um numero com math
num = int(input("Digite um número: "))
raiz = math.sqrt(num)
print("A Raiz de {} é igual a {:.2f}".format(num, raiz))

print(emoji.emojize(":smile:", use_aliases=True))

input("Deseja sortear um numero?")
#Este bloco de código o metodo randint ira sortear um numero aleatorio de 1 até 10
num = random.randint(1, 10)
print("O numero sorteado foi {}.".format(num))
예제 #32
0
async def on_update():
    cache = {}
    while True:
        try:
            # Reset bindings,
            bindings = get_bindings()

            # Iterate through each message bind,
            for message in bindings['locations']:
                if message not in cache:
                    cache[message] = []
                all_users, channel, roles = [
                    member for member in [
                        server for server in client.servers if server.id ==
                        bindings['locations'][message]['server']
                    ][0].members
                ], bindings['locations'][message]['channel'], bindings[
                    'locations'][message]['roles']

                # Find actual message,
                msg = await client.get_message(client.get_channel(channel),
                                               int(message))

                # Add some starter emojis,
                if len(msg.reactions) < len(roles):
                    for role in roles:
                        get = discord.utils.get(client.get_all_emojis(),
                                                name=role)
                        if get == None:
                            get = emoji.emojize(role)
                        await client.add_reaction(msg, get)

                for i, reaction in enumerate(msg.reactions):
                    if len(cache[message]) <= i:
                        cache[message].append(-1)
                    print(reaction.emoji)
                    reactors = []
                    after = None
                    if reaction.count != cache[message][i]:
                        while True:
                            count = 0
                            for user in await client.get_reaction_users(
                                    reaction, limit=100, after=after):
                                reactors.append(user)
                                after = user
                                count += 1

                            cache[message][i] = reaction.count

                            if count < bindings['settings']['chunk']:
                                break
                        for user in all_users:
                            for role in roles:
                                role_obj = discord.utils.get(
                                    reaction.message.server.roles,
                                    name=roles[role])
                                # print(reaction.emoji, role, reaction.custom_emoji, emoji_equal(reaction.emoji, role, reaction.custom_emoji))
                                if emoji_equal(reaction.emoji, role,
                                               reaction.custom_emoji):
                                    if user in reactors:
                                        if role_obj not in user.roles:
                                            print('GIVE: {} to {}.'.format(
                                                role, user))
                                            await client.add_roles(
                                                reaction.message.server.
                                                get_member(user.id), role_obj)
                                    else:
                                        if role_obj in user.roles:
                                            print('TAKE: {} from {}.'.format(
                                                role, user))
                                            await client.remove_roles(
                                                user, role_obj)

            # Give bot/discord a rest,
            print("Before")
            await asyncio.sleep(bindings['settings']['refresh'])
            print("After")
        except KeyboardInterrupt:
            quit()
        except Exception:
            traceback.print_exc()
예제 #33
0
def send_message(message):
    bot.send_message(
        message.chat.id,
        'Я не против поговорить, но сейчас я не разговорчив. ' +
        emojize(':zipper-mouth_face:'))
예제 #34
0
def label_to_emoji(label):
    """
    Converts a label (int or string) into the corresponding emoji code (string) ready to be printed
    """
    return emoji.emojize(emoji_dictionary[str(label)], use_aliases=True)
예제 #35
0
def comment_image(browser, username, comments, blacklist, logger, logfolder):
    """Checks if it should comment on the image"""
    # check action availability
    if quota_supervisor("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)
    # wait, to avoid crash
    sleep(3)
    comment_input = get_comment_input(browser)

    try:
        if len(comment_input) > 0:
            # wait, to avoid crash
            sleep(2)
            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

            # wait, to avoid crash
            sleep(2)
            # click on textarea/comment box and enter comment
            (ActionChains(browser).move_to_element(
                comment_input[0]).click().send_keys(
                    comment_to_be_sent).perform())
            # wait, to avoid crash
            sleep(2)
            # post comment / <enter>
            (ActionChains(browser).move_to_element(comment_input[0]).send_keys(
                Keys.ENTER).perform())

            update_activity(
                browser,
                action="comments",
                state=None,
                logfolder=logfolder,
                logger=logger,
            )

            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"
    except WebDriverException as ex:
        logger.error(ex)

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

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

    return True, "success"
예제 #36
0
파일: ex045.py 프로젝트: WeDias/RespCEV
import emoji
from random import choice
repetir = 1
print('-' * 50)
print(' ' * 15 + '\033[1;36mPEDRA, PAPEL, TESOURA\033[m')
while repetir == 1:
    print('-' * 50)
    jogador = int(
        input('\033[1;m[0]SAIR DO JOGO' +
              emoji.emojize(' :heavy_multiplication_x:') + '\n\n[1]PEDRA' +
              emoji.emojize(' :baseball:') + '\n[2]PAPEL' +
              emoji.emojize(' :page_facing_up:') + '\n[3]TESOURA\033[m' +
              emoji.emojize(' :scissors:')))
    opc = 'PEDRA', 'PAPEL', 'TESOURA'
    pc = choice(opc)
    if jogador == 0:
        repetir = 0
        print('\n' + ' ' * 10 +
              '\033[1;36mFIM DE JOGO OBRIGADO, POR JOGAR!\033[m')
    elif jogador == 1 and pc == 'TESOURA' or jogador == 2 and pc == 'PEDRA' or jogador == 3 and pc == 'PAPEL':
        print(
            '\n\033[1mO PC Escolheu {} Portanto\033[m \033[1;32m[VOCÊ VENCEU!]\033[m'
            .format(pc))
    elif jogador == 1 and pc == 'PEDRA' or jogador == 2 and pc == 'PAPEL' or jogador == 3 and pc == 'TESOURA':
        print(
            '\n\033[1mO PC Escolheu {} Portanto\033[m \033[1;33m[VOCÊS EMPATARAM!]\033[m'
            .format(pc))
    else:
        print(
            '\n\033[1mO PC Escolheu {} Portanto\033[m \033[1;31m[VOCÊ PERDEU!]\033[m'
            .format(pc))
예제 #37
0
def main(cli_args=None):
    if cli_args is not None:
        args = parser.parse_args(cli_args)
    else:
        args = parser.parse_args()

    logging.config.dictConfig({
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'default': {
                'format': '%(levelname)s: %(message)s'
            },
        },
        'handlers': {
            'default': {
                'level': args.log_level,
                'class': 'logging.StreamHandler',
                'formatter': 'default',
            },
        },
        'loggers': {
            '': {
                'handlers': ['default'],
                'level': args.log_level,
                'propagate': True,
            }
        }
    })

    if args.config is not None:
        config = load_config(args.config)
    elif path.exists(path.expanduser(DEFAULT_CONFIG)):
        config = load_config(DEFAULT_CONFIG)
    elif path.exists(OLD_DEFAULT_CONFIG):
        config = load_config(OLD_DEFAULT_CONFIG)
    elif path.exists(path.expanduser(SITE_DEFAULT_CONFIG)):
        config = load_config(SITE_DEFAULT_CONFIG)
    else:  # get default config and print message about missing file
        config = load_config()

    if args.backend:
        config['backends'] = args.backend

    if args.option is None:
        args.option = {}
    for backend, backend_options in args.option.items():
        if backend is not None:
            config.setdefault(backend, {}).update(backend_options)

    if getattr(args, 'func', None) == run_cmd and args.longer_than is None and\
            'longer_than' in config:
        args.longer_than = config['longer_than']

    if hasattr(args, 'func'):
        message, retcode = args.func(args)
        if message is None:
            return 0
        if emojize is not None and not args.no_emoji:
            message = emojize(message, use_aliases=True)
        return notify(message,
                      args.title,
                      config,
                      retcode=retcode,
                      **dict(args.option.get(None, [])))
    else:
        parser.print_help()
예제 #38
0
def write_emoji_pic_to_file(filename):
    # print also all symbolic letters as emoji
    for e in emoji.EMOJI_UNICODE:
        emoji_pic = emoji.emojize(e)
        with open(filename, "a+", encoding="utf-8") as f:
            f.write(emoji_pic + "\n")
예제 #39
0
파일: views.py 프로젝트: Lally-maker/four
def index(request):
    if request.method == 'POST':
        # retrieve incoming message from POST request in lowercase
        incoming_msg = request.POST['Body'].lower()

        # create Twilio XML response
        resp = MessagingResponse()
        msg = resp.message()

        responded = False

        #insert/merge chatbot components here (minus response code)
        # Importing modules
        import re
        from nltk.corpus import wordnet

        # Building a list of Keywords
        list_words = [
            'hello', 'timings', 'trim', 'date', 'tomorrow', 'walk', 'open'
        ]  #added cut (was changed to barber here) to algorithm to see what i would need to add to facilitate a barber bot
        list_syn = {}
        for word in list_words:
            synonyms = []
            for syn in wordnet.synsets(word):
                for lem in syn.lemmas():

                    # Remove any special characters from synonym strings
                    lem_name = re.sub('[^a-zA-Z0-9 \n\.]', ' ', lem.name())
                    synonyms.append(lem_name)

            list_syn[word] = set(synonyms)

        print(list_syn)

        #the below lines of codes allows me to create a dictionary [..ie keywords] of intents based on the synonyms within the keyword list...ie list_syn
        #the keyword dictionary is appended and the synonyms of the keyword from list_syn is added to the dictionary
        #another line of code is [down below] is used to find the keywrods from the dictionary in the......
        #customer's response to find their, the customer's, intent.

        # Building dictionary of Intents & Keywords
        keywords = {}
        keywords_dict = {}

        keywords = {
            'weekday': [
                '.*\\bmonday\\b.*', '.*\\btuesday\\b.*', '.*\\bwednesday\\b.*',
                '.*\\bthursday\\b.*', '.*\\bfriday\\b.*'
            ],
            'weekend': ['.*\\bsaturday\\b.*', '.*\\bsunday\\b.*'],
        }

        #to be added to the dictionary
        #niceties
        #some local slang....eg 'Yo!'

        # Defining a new key in the keywords dictionary
        keywords['greet'] = []

        # Populating the values in the keywords dictionary with synonyms of keywords formatted with RegEx metacharacters
        for synonym in list(list_syn['hello']):
            keywords['greet'].append(
                '.*\\b' + synonym + '\\b.*'
            )  #this regex expression tells the code to search from beginning to end .* and \b indicates that the parameter is the keyword

        #if i leave the below two lines of code attached to the above lines,
        #it will repeatedly print yo and cap
        #keywords['greet'].append('yo') #any word that begins with yo is being represented as yo
        keywords['greet'].append(
            '.*\\byo\\b.*')  #this regex fixes the above line of code
        keywords['greet'].append('.*\\bcap\\b.*')
        keywords['greet'].append(
            '.*\\bi love you\\b.*'
        )  #can use multiple words hear to represent intent

        # Defining a new key in the keywords dictionary
        keywords['timings'] = []

        # Populating the values in the keywords dictionary with synonyms of keywords formatted with RegEx metacharacters
        for synonym in list(list_syn['timings']):
            keywords['timings'].append('.*\\b' + synonym + '\\b.*')

        for intent, keys in keywords.items():

            # Joining the values in the keywords dictionary with the OR (|) operator updating them in keywords_dict dictionary
            keywords_dict[intent] = re.compile(
                '|'.join(keys))  #| is the OR operator
            #AND re.compile(str) creates a pattern object hence line 74 & 77 not being defined traditionally
        for synonym in list(list_syn['open']):
            keywords['timings'].append('.*\\b' + synonym + '\\b.*')

        for intent, keys in keywords.items():

            # Joining the values in the keywords dictionary with the OR (|) operator updating them in keywords_dict dictionary
            keywords_dict[intent] = re.compile(
                '|'.join(keys))  #| is the OR operator
            #AND re.compile(str) creates a pattern object hence line 74 & 77 not being defined traditionally

        # Populating the values in the keywords dictionary with synonyms of keywords formatted with RegEx metacharacters
        for synonym in list(list_syn['tomorrow']):
            keywords['timings'].append(
                '.*\\b' + synonym + '\\b.*'
            )  #doesnt contain 'a hair cut' but i should be able to add it to the dictionary

        for intent, keys in keywords.items():

            # Joining the values in the keywords dictionary with the OR (|) operator updating them in keywords_dict dictionary
            keywords_dict[intent] = re.compile(
                '|'.join(keys))  #| is the OR operator
            #AND re.compile(str) creates a pattern object hence line 74 & 77 not being defined traditionally
        keywords['hair cut'] = []

        # Populating the values in the keywords dictionary with synonyms of keywords formatted with RegEx metacharacters
        for synonym in list(list_syn['trim']):
            keywords['hair cut'].append(
                '.*\\b' + synonym + '\\b.*'
            )  #doesnt contain 'a hair cut' but i should be able to add it to the dictionary

        for intent, keys in keywords.items():

            # Joining the values in the keywords dictionary with the OR (|) operator updating them in keywords_dict dictionary
            keywords_dict[intent] = re.compile(
                '|'.join(keys))  #| is the OR operator
            #AND re.compile(str) creates a pattern object hence line 74 & 77 not being defined traditionally
            #the below code is COMMENTED OUT because
            #tomorrow was added tot he timings key in the dictionary

            #keywords['tomorrow']=[] #no idea why tomorrow wasnt working at first!

            # Populating the values in the keywords dictionary with synonyms of keywords formatted with RegEx metacharacters
            #for synonym in list(list_syn['tomorrow']):
            # keywords['tomorrow'].append('.*\\b'+synonym+'\\b.*') #doesnt contain 'a hair cut' but i should be able to add it to the dictionary

            #for intent, keys in keywords.items():

            # Joining the values in the keywords dictionary with the OR (|) operator updating them in keywords_dict dictionary
            keywords_dict[intent] = re.compile(
                '|'.join(keys))  #| is the OR operator
            #AND re.compile(str) creates a pattern object hence line 74 & 77 not being defined traditionally

        # Defining a new key in the keywords dictionary
        keywords['date'] = []

        # Populating the values in the keywords dictionary with synonyms of keywords formatted with RegEx metacharacters
        for synonym in list(list_syn['date']):
            keywords['date'].append('.*\\b' + synonym + '\\b.*')

        for intent, keys in keywords.items():

            # Joining the values in the keywords dictionary with the OR (|) operator updating them in keywords_dict dictionary
            keywords_dict[intent] = re.compile(
                '|'.join(keys))  #| is the OR operator
            #AND re.compile(str) creates a pattern object hence line 74 & 77 not being defined traditionally

        # Defining a new key in the keywords dictionary
        keywords['walk'] = []

        # Populating the values in the keywords dictionary with synonyms of keywords formatted with RegEx metacharacters
        for synonym in list(list_syn['walk']):
            keywords['walk'].append('.*\\b' + synonym + '\\b.*')

        for intent, keys in keywords.items():

            # Joining the values in the keywords dictionary with the OR (|) operator updating them in keywords_dict dictionary
            keywords_dict[intent] = re.compile(
                '|'.join(keys))  #| is the OR operator
            #AND re.compile(str) creates a pattern object hence line 74 & 77 not being defined traditionally

        # Defining a new key in the keywords dictionary
        keywords['walk'] = []

        # Populating the values in the keywords dictionary with synonyms of keywords formatted with RegEx metacharacters
        for synonym in list(list_syn['walk']):
            keywords['walk'].append('.*\\b' + synonym + '\\b.*')

        for intent, keys in keywords.items():

            # Joining the values in the keywords dictionary with the OR (|) operator updating them in keywords_dict dictionary
            keywords_dict[intent] = re.compile(
                '|'.join(keys))  #| is the OR operator
            #AND re.compile(str) creates a pattern object hence line 74 & 77 not being defined traditionally

        #merge response code with below code
        # Building a dictionary of responses
        responses = {
            'greet':
            'Hello! How can I help you?',
            'timings':
            'We are open from 9AM to 5PM, Monday to Friday. We are closed on weekends and public holidays.',
            #'tomorrow': 'what time my n***a?',
            'fallback': [
                'I dont quite understand. Could you repeat that?',
                'repeat M**********R'
            ],
            'hair cut': ['np.that is doable. When?', 'standard'],
            'date': ['What day?', 'WHEN?'],
            'weekday':
            'what time?',
        }

        print("\nWelcome to the xXx Barber. How may I help you?\n"
              )  #Welcome to MyBank. How may I help you?

        #this response algo is not much different from the ML approach because that approach tokenize and lemmatizes the word and chooses
        #the appropriate response based on the class and patterm...ultimately choosing a predefined response to answer the consumer's question
        #tokenizing and lemmatizing can be sueful for sentences which contain multiple keywords; such as...
        #what time do you open tomorrow. the algo responds to the keyword 'tomorrow'

        if incoming_msg == 'hello':
            response = emoji.emojize("""
*Hi! I am the Quarantine Bot* :wave:
Let's be friends :wink:

You can give me the following commands:
:black_small_square: *'quote':* Hear an inspirational quote to start your day! :rocket:
:black_small_square: *'cat'*: Who doesn't love cat pictures? :cat:
:black_small_square: *'dog'*: Don't worry, we have dogs too! :dog:
:black_small_square: *'meme'*: The top memes of today, fresh from r/memes. :hankey:
:black_small_square: *'news'*: Latest news from around the world. :newspaper:
:black_small_square: *'recipe'*: Searches Allrecipes.com for the best recommended recipes. :fork_and_knife:
:black_small_square: *'recipe <query>'*: Searches Allrecipes.com for the best recipes based on your query. :mag:
:black_small_square: *'get recipe'*: Run this after the 'recipe' or 'recipe <query>' command to fetch your recipes! :stew:
:black_small_square: *'statistics <country>'*: Show the latest COVID19 statistics for each country. :earth_americas:
:black_small_square: *'statistics <prefix>'*: Show the latest COVID19 statistics for all countries starting with that prefix. :globe_with_meridians:
""",
                                     use_aliases=True)
            msg.body(response)
            responded = True

        import random
        # While loop to run the chatbot indefinetely
        while (True):

            # Takes the user input and converts all characters to lowercase
            #user_input = input().lower()
            #i think i would be able to put tokenize and lemmatizer here by user input

            # Defining the Chatbot's exit condition, can a synonym type list be used to add more quit 'words'?
            if incoming_msg == 'a':  #change back 'a' to 'quit' when finished
                def_res = print("Thank you for visiting.")
                responded = True
                break

            for intent, pattern in keywords_dict.items(
            ):  #pattern acts as an object because it was created by re.compile(str)

                #will have toc reate bigrams here and add to keywords_dict.items() or create a new dictionary

                # Using the regular expression search function to look for keywords in user input
                if re.search(pattern, incoming_msg):

                    # if a keyword matches, select the corresponding intent from the keywords_dict dictionary
                    matched_intent = intent

            # The fallback intent is selected by default
            key = 'fallback'
            if matched_intent in responses:

                # If a keyword matches, the fallback intent is replaced by the matched intent as the key for the responses dictionary
                key = matched_intent

            # The chatbot prints the response that matches the selected intent
            please_work = print(
                responses[key]
            )  #random.choice will allow for random responses by the chatbot
            #the random.choice function is return random LETTERS from the responses instead of the responses, hence it was removed temporarily

            responded = True

            if not responded:
                msg.body(
                    "Sorry, I don't understand. Send 'hello' for a list of commands."
                )

            return HttpResponse(str(resp))
예제 #40
0
# first: pip install emoji

from emoji import emojize

print(emojize("It's me, Phika :smile: :grin:", use_aliases=True))
print(emojize('Python is :heart: :thumbsup: :lock:', use_aliases=True))
print(emojize(":two_hearts: :broken_heart: :couple:", use_aliases=True))
print(emojize(":heart_eyes: :v: :boom: :running:", use_aliases=True))

print(emojize("Instagram :id: Phika.ir", use_aliases=True))

# complete list:
# https://www.webfx.com/tools/emoji-cheat-sheet/
예제 #41
0
# pip install emoji
import emoji
print(emoji.emojize("Olá, Mundo :earth_americas:", use_aliases=True))
예제 #42
0
def counts(bot, update):
    x = utils.db_like(update.message.from_user.id)
    update.message.reply_text(
        emojize('Вы можете поставить ещё ' + str(x) + ' сердечек!',
                use_aliases=True))
예제 #43
0
def hello(bot, update):
    update.message.reply_text(emojize(utils.help_text +
                                      utils.escapize(utils.cmd_list),
                                      use_aliases=True),
                              parse_mode='HTML')
예제 #44
0
    def post_titles(self):
        titles = [submission.title for submission in self.sub_posts()]
        return titles


# main
# creates instance off credentials in praw file
reddit = praw.Reddit(
    'bot1',
    user_agent='bot1 user agent',
)

# creates sub to crawl instance, limits to front page, creates list of post objects
new_sub = Subobj(subs_to_crawl()[0], 25)
posts = new_sub.sub_posts()

# empty word dict to count the word, sets word and reply word
word = 'crab_emoji'
reply_word = emoji.emojize(':crab:', use_aliases=True)
num_of_crabs = {word: 0}

# loads more comments after "load more", limit is set to 2 to for memory purposes
posts[0].comments.replace_more(limit=2)

# crawls the comment, if comment has word, reply with reply_word
for comment in posts[0].comments.list():
    if word in comment.body:
        num_of_crabs[word] += 1
        comment.reply(reply_word)
예제 #45
0
def test_emoji():
    print emojize(":thumbs_up:")
예제 #46
0
from time import sleep
from emoji import emojize

print('\033[33m-=-\033[m' * 20)
print('\033[33m************* Contagem regressiva! *************\033[m')
print('\033[33m-=-\033[m' * 20)
for c in range(10, -1, -1):
    print('{}!' .format(c))
    sleep(1)
print(emojize(':fireworks: :fire: ' *5))
예제 #47
0
def unknown(update, context):
    emoj = emojize(':smiley:', use_aliases=True)
    update.message.reply_text("Desculpa, Nao conheço este comando. " + emoj,
                              parse_mode="Markdown")
예제 #48
0
def callback_inline(call):
    if call.message:
        try:
            if call.data.startswith("add"):
                id = call.data.split('_')[1]
                temp_storage[call.message.chat.id] = {}
                temp_storage[call.message.chat.id]['id'] = id
                bot.edit_message_text(
                    chat_id=call.message.chat.id,
                    message_id=call.message.message_id,
                    text=emoji.emojize(
                        ":credit_card: Укажите, сколько GT нужно начислить или введите 0 для отмены.",
                        use_aliases=True))
                bot.clear_step_handler(call.message)
                bot.register_next_step_handler(call.message, process_money)
            elif call.data.startswith("buy"):
                item = call.data.split('_')[1]
                user_token = shop_storage[call.message.chat.id]
                if not user_token:
                    raise Exception("no token")
                is_admin = get_permissions_by_token(user_token)
                keyboard = get_keyboard(is_admin)
                shop_storage[call.message.chat.id] = None
                if make_buy(user_token, item):
                    bot.edit_message_text(
                        chat_id=call.message.chat.id,
                        message_id=call.message.message_id,
                        text=emoji.emojize(
                            ':white_check_mark: Платеж прошел, ожидайте доставку!',
                            use_aliases=True))
                else:
                    bot.edit_message_text(
                        chat_id=call.message.chat.id,
                        message_id=call.message.message_id,
                        text=emoji.emojize(
                            ':cry: Недостаточно средств или товар закончился.',
                            use_aliases=True))
                answer = bot.send_message(call.message.chat.id,
                                          "Что дальше?",
                                          reply_markup=keyboard)
                bot.register_next_step_handler(answer, process_command)
            elif call.data.startswith("cancel"):
                user_token = shop_storage[call.message.chat.id]
                if not user_token:
                    raise Exception("no token")
                is_admin = get_permissions_by_token(user_token)
                keyboard = get_keyboard(is_admin)
                bot.edit_message_text(chat_id=call.message.chat.id,
                                      message_id=call.message.message_id,
                                      text=emoji.emojize(
                                          ':new_moon_with_face: Нет, так нет.',
                                          use_aliases=True))
                answer = bot.send_message(call.message.chat.id,
                                          "Что дальше?",
                                          reply_markup=keyboard)
                bot.register_next_step_handler(answer, process_command)

            elif call.data == "yes":
                comment = temp_storage[call.message.chat.id]['comment']
                id = temp_storage[call.message.chat.id]['id']
                money = temp_storage[call.message.chat.id]['money']
                user_token = temp_storage[call.message.chat.id]['token']
                is_admin = get_permissions_by_token(user_token)
                keyboard = get_keyboard(is_admin)

                if submit_gotocoins(user_token, id, money, comment):
                    bot.edit_message_text(
                        chat_id=call.message.chat.id,
                        message_id=call.message.message_id,
                        text=emoji.emojize(':thumbsup: GT начислены. Спасибо!',
                                           use_aliases=True))
                    try:
                        student_id = find_telegram_by_id(id)
                        if student_id:
                            bot.send_message(
                                student_id,
                                emoji.emojize(
                                    ':metal: Вам начислено {} GT за "{}".'.
                                    format(money, comment),
                                    use_aliases=True))
                    except:
                        pass
                else:
                    raise Exception("transaction error")
                answer = bot.send_message(call.message.chat.id,
                                          "Что дальше?",
                                          reply_markup=keyboard)
                temp_storage[call.message.chat.id]['comment'] = {}
                bot.register_next_step_handler(answer, process_command)
            elif call.data == "no":
                user_token = temp_storage[call.message.chat.id]['token']
                is_admin = get_permissions_by_token(user_token)
                keyboard = get_keyboard(is_admin)
                bot.edit_message_text(chat_id=call.message.chat.id,
                                      message_id=call.message.message_id,
                                      text=emoji.emojize(
                                          ':confused: Нет, так нет. Отменяем.',
                                          use_aliases=True))
                answer = bot.send_message(call.message.chat.id,
                                          "Что дальше?",
                                          reply_markup=keyboard)
                temp_storage[call.message.chat.id]['comment'] = {}
                bot.register_next_step_handler(answer, process_command)
            else:
                raise Exception("unknown command")
        except Exception as e:
            print(e)
            answer = bot.send_message(
                call.message.chat.id,
                text='Что-то пошло не так :(. Нажмите /start.')
            bot.register_next_step_handler(answer, process_command)
예제 #49
0
import emoji
print('=-' * 44)
print(
    'Aqui iremos lhe mostrar todos os números os números impares divisiveis por 3 de 0 a 50'
)
print('=-' * 44)
print('''Preparado?
\033[34m[1]SIM
\033[31m[2]NÃO\033[1;97m''')
a = int(input(':'))
if a == 1:
    for c in range(0, 52, 2):
        print('\033[31m', c, end=' ')
else:
    print(emoji.emojize('Ok, até mais tarde!:thumbs_up:'))
예제 #50
0
'''Faça um programa que mostre na tela uma contagem regressiva
para o estouro de fogos de artifício, indo de 10 até 0,
com uma pausa de 1 segundo entre eles'''
from time import sleep
import emoji
for c in range(10, -1, -1):
    print(c)
    sleep(1)
print(emoji.emojize(':tada: FELIZ ANO NOVO :tada:', use_aliases=True))
예제 #51
0
from math import sqrt, floor
num = int(input('Digite um número: '))
raiz = sqrt(num)
print('A raiz quadrada de {} é igual a {}'.format(num, floor(raiz)))
print('--' * 20)
import random
num = random.randint(1, 10)
print(num)
print('--' * 20)
import emoji
print(emoji.emojize('Olá mundo! :earth_americas:', use_aliases=True))
예제 #52
0
def trivia_answer(call):
    """Options for Trivia Questions"""

    global winners
    global answers
    global correct
    global incorrect
    global condition
    global scoreboard

    print(f"{call.from_user.id} the from user {call.from_user.username}")
    print(call.message.chat)
    if call.data == "start" and call.from_user.id in Admins:
        trivia_game(call.message)
        condition = True
    if call.data == "stop" and call.from_user.id in Admins:
        stop_trivia(call.message)
        condition = False
    if call.data == "pause" and call.from_user.id in Admins:
        condition = False
        pause_trivia(call.message)
    if call.data == "continue" and call.from_user.id in Admins:
        condition = True
        trivia_game(call.message)
    if call.data == "stats":
        trivia_scoreboard(call.message)
        condition = False
    if call.data == "rank":
        user_rank(call.message)

    if call.data == "A" and condition == True:
        if pick[0] in answer:
            # user got the right answer
            bot.send_message(
                chat_id,
                emoji.emojize(
                    f":trophy: Congratulations {call.from_user.username}, your answer is correct!!! You got 1 point",
                    use_aliases=True))
            if call.from_user.username in winners:
                scr = scoreboard.get(call.from_user.username)
                scr += 1
                dict = {call.from_user.username: scr}
                scoreboard.update(dict)
            else:
                winners.append(call.from_user.username)
                dict = {call.from_user.username: 0}
                scoreboard.update(dict)
            print(call.from_user.username)
            answers += 1
            correct += 1
            trivia_game(call.message)
        else:
            # user failed
            bot.send_message(
                chat_id,
                emoji.emojize(
                    f":turtle: Sorry {call.from_user.username}, but your answer is wrong. Better next time",
                    use_aliases=True))
            print(call.from_user.username)
            answers += 1
            incorrect += 1

    if call.data == "B" and condition == True:
        if pick[1] in answer:
            # user got the right answer
            bot.send_message(
                chat_id,
                emoji.emojize(
                    f":trophy: Congratulations {call.from_user.username}, your answer is correct!!! You got 1 point",
                    use_aliases=True))
            if call.from_user.username in winners:
                scr = scoreboard.get(call.from_user.username)
                scr += 1
                dict = {call.from_user.username: scr}
                scoreboard.update(dict)
            else:
                winners.append(call.from_user.username)
                dict = {call.from_user.username: 0}
                scoreboard.update(dict)
            print(call.from_user.username)
            answers += 1
            correct += 1
            trivia_game(call.message)
        else:
            # user failed
            bot.send_message(
                chat_id,
                emoji.emojize(
                    f":turtle: Sorry {call.from_user.username}, but your answer is wrong. Better next time",
                    use_aliases=True))
            print(call.from_user.username)
            answers += 1
            incorrect += 1

    if call.data == "C" and condition == True:
        if pick[2] in answer:
            # user got the right answer
            bot.send_message(
                chat_id,
                emoji.emojize(
                    f":trophy: Congratulations {call.from_user.username}, your answer is correct!!! You got 1 point",
                    use_aliases=True))
            if call.from_user.username in winners:
                scr = scoreboard.get(call.from_user.username)
                scr += 1
                dict = {call.from_user.username: scr}
                scoreboard.update(dict)
            else:
                winners.append(call.from_user.username)
                dict = {call.from_user.username: 0}
                scoreboard.update(dict)
            print(call.from_user.username)
            answers += 1
            correct += 1
            trivia_game(call.message)
        else:
            # user failed
            bot.send_message(
                chat_id,
                emoji.emojize(
                    f":turtle: Sorry {call.from_user.username}, but your answer is wrong. Better next time",
                    use_aliases=True))
            print(call.from_user.username)
            answers += 1
            incorrect += 1

    if call.data == "D" and condition == True:
        if pick[3] in answer:
            # user got the right answer
            bot.send_message(
                chat_id,
                emoji.emojize(
                    f":trophy: Congratulations {call.from_user.username}, your answer is correct!!! You got 1 point",
                    use_aliases=True))
            if call.from_user.username in winners:
                scr = scoreboard.get(call.from_user.username)
                scr += 1
                dict = {call.from_user.username: scr}
                scoreboard.update(dict)
            else:
                winners.append(call.from_user.username)
                dict = {call.from_user.username: 0}
                scoreboard.update(dict)
            print(call.from_user.username)
            answers += 1
            correct += 1
            trivia_game(call.message)
        else:
            # user failed
            bot.send_message(
                chat_id,
                emoji.emojize(
                    f":turtle: Sorry {call.from_user.username}, but your answer is wrong. Better next time",
                    use_aliases=True))
            print(call.from_user.username)
            answers += 1
            incorrect += 1

    return winners, answers, correct, incorrect, scoreboard
예제 #53
0
from emoji import emojize

new_user_conn = "Somebody's knocking! ID:"

goods = {'1': u"Красный маркер", '2': u"Шариковая ручка"}
first_us_mess = "I am your assistant. I can help you create your own bot.\nAre you ready to follow my instructions?"
second_us_mess = "What kind of bot do you need? I offer you next variants!\nBut we can discuss another one... " \
                 "Describe your bot project and send me in text message."
third_us_mess = "I'll try to convince you. Please, read info about my bots!"
seller_info = "You can see some example this kind of bot. Please, click 'Example'!"
chat_mate_info = "About"
spy_info = "About"
assistant_info = "You can see some example this kind of bot. Please, click 'Example'!"
base_seller_mess = "<b>Beauty Studio</b>\n"
it1_mess = "Some"
it2_mess = emojize(":lower_left_crayon:", use_aliases=True) + " - Красный маркер\nPrice: 0.99$\n/addtobasket1\n" \
           + emojize(":lower_left_ballpoint_pen:", use_aliases=True) + " - Шариковая ручка\nPrice: 1.05$\n/addtobasket2\n"
dialogs_us = {
    'd0': {
        'y0': "Yes",
        'n0': "I'm not sure...",
        'mess': first_us_mess
    },
    'y0': {
        'seller': "Seller",
        'chat_mate': "Chat mate",
        'spy': "Spy",
        'assistant': "Assistant",
        'mess': second_us_mess
    },
    'n0': {
# Escreva um programa que leia um número n inteiro qualquer e mostre na tela os primeiros elementos de uma sequencia de fibonacci. Ex.: 0,1,1,2,3,8
import emoji
print('{:=^50}'.format(' SEQUÊNCIA DE FIBONACCI '))
n = int(input('Quantos termos você deseja mostrar? '))
t1 = 0
t2 = 1

print('1º',
      t1,
      emoji.emojize('\033[1;34m:arrow_forward:\033[m', use_aliases=True),
      '2º',
      t2,
      emoji.emojize('\033[1;34m:arrow_forward:\033[m', use_aliases=True),
      end=' ')

cont = 3
mais = n
total = 0

while mais != 0:
    total += mais
    while cont <= total:
        t3 = t2 + t1
        print('{}º'.format(cont),
              t3,
              emoji.emojize('\033[1;34m:arrow_forward:\033[m',
                            use_aliases=True) if cont < total else ' ',
              end=' ')
        t1 = t2
        t2 = t3
        cont += 1
예제 #55
0
print("JO")
sleep(1)
print("KEN")
sleep(1)
print("PO!!!")


print("-=" * 12)
print("Computador jogou {}".format(itens[computador]))
print("Jogador jogou {}".format(itens[jogador]))
print("-=" * 12)

if computador == 0: #Computador jogou PEDRA
    if jogador == 0:
        print(emoji.emojize("EMPATE :grey_exclamation:", use_aliases = True))
    elif jogador == 1:
        print(emoji.emojize("JOGADOR GANHOU :tada:", use_aliases = True))
    elif jogador == 2:
        print(emoji.emojize("COMPUTADOR GANHOU :clap:", use_aliases = True))


elif computador == 1: #Computador jogou PAPEL
    if jogador == 0:
        print(emoji.emojize("COMPUTADOR GANHOU :clap:", use_aliases = True))
    elif jogador == 1:
        print(emoji.emojize("EMPATE :grey_exclamation:", use_aliases = True))
    elif jogador == 2:
        print(emoji.emojize("JOGADOR GANHOU :tada:", use_aliases = True))

예제 #56
0
print('executing login-script')

driver.execute_script(load_jQuery)

driver.execute_script(login_script)

print('login-script executed')

time.sleep(1)

print('executing otp-send')

driver.execute_script(load_jQuery)
time.sleep(1)
driver.execute_script(otp_send)

print('otp-send executed')

exploit = open('exploit.js', 'r')
exploit = str(exploit.read())

print('executing exploit :)')

driver.execute_script(load_jQuery)
driver.execute_script(exploit)

victim = driver.find_element_by_id(
    'ContentPlaceHolder1_txtStudentName').get_attribute('value')

print(emoji.emojize('{} is compromised :thumbs_up:').format(victim))
예제 #57
0
    'washer2': 'Washer 2',
    'dryer1': 'Dryer 1',
    'dryer2': 'Dryer 2'
}

# Building menu for every occasion
def build_menu(buttons, n_cols, header_buttons=None, footer_buttons=None):
    menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
    if header_buttons:
        menu.insert(0, header_buttons)
    if footer_buttons:
        menu.append(footer_buttons)
    return InlineKeyboardMarkup(menu)

# Building emojis for every occasion
ebluediamond = emojize(":small_blue_diamond: ", use_aliases=True)
etick = emojize(":white_check_mark: ", use_aliases=True)
ecross = emojize(":x: ", use_aliases=True)
esoon = emojize(":soon: ", use_aliases=True)

# start command initializes: 
def check_handler(bot, update, user_data):
    user = update.message.from_user
    if 'pinned_level' in user_data:
        level_status(bot, update, user_data,
                     from_pinned_level=True, new_message=True)
    else:
        ask_level(bot, update)

def ask_level(bot, update):  
    level_text = "Heyyo! I am RC4's Laundry Bot. <i>As I am currently in [BETA] mode, I can only show details for Ursa floor.</i>\n\n<b>Which laundry level do you wish to check?</b>"
예제 #58
0
파일: api.py 프로젝트: icoder18/Emojifier
def predict(x):
    X = pd.Series([x])
    emb_X = embedding_output(X)
    p = model.predict_classes(emb_X)
    return emoji.emojize(emoji_dictionary[str(p[0])])
예제 #59
0
def start(bot, update):
    update.message.reply_text(
        emojize('Введи /h для получения списка команд :wink:',
                use_aliases=True))
예제 #60
0
from time import sleep
from emoji import emojize
from source.classes.menu import Menu

print()
sleep(1)
print(emojize('Bem vindo ao jogo da Adivinhação! :smile: ', use_aliases=True))
sleep(1)
print()

Menu()