Example #1
0
def generate() -> List[str]:
    """Generate the method names"""
    global names_defined_here
    global rev_mapper
    secret_names = ["upsidedown", "names_defined_here", "rev_mapper"]
    rev_mapper = {upsidedown.transform(name): name for name in names_defined_here}
    return [upsidedown.transform(name) for name in names_defined_here if name not in secret_names]
Example #2
0
def roll(bot, trigger):
    target = trigger.group(1).strip()
    if target.endswith(' down a hill'):
        target = target[:-12]
        tegrat = transform(target)
        bot.say("(╮°-°)╯︵ %s %s %s %s %s (@_@;)" % (tegrat, target, tegrat, target, tegrat))
    else:
        bot.say("(╮°-°)╯︵ %s" % transform(target))
Example #3
0
    def flip_text(message=None):
        if not message:
            message = "┻━┻"
        else:
            message = upsidedown.transform(message)

        return str("(╯°□°)╯︵ " + message)
Example #4
0
def flip(bot, trigger):
    """Flips things... because that is the whole point."""
    if not trigger.group(2):
        bot.say('What should I flip? o.o')
        return
    target = trigger.group(2)
    try:
        if target == 'table':
            return bot.say(u'(╯°□°)╯︵ ┻━┻')
        if target == 'table over':
            return bot.say(u'┬──┬ ノ(゜-゜ノ)')
        elif target == 'tables':
            return bot.say(u'┻━┻ ︵ヽ(`Д´)ノ︵ ┻━┻')
        elif target == 'out':
            return bot.say(u'ಠ﹏ಠ')
        elif target == 'bird':
            return bot.say(u't(°□ °t)')
        elif target == 'person':
            return bot.say(u'(╯°Д°)╯︵ /(.□ . \)')
        elif target == 'russia':
            bot.reply('In Soviet Russia, table flip you!')
            return bot.say(u'┬─┬ ︵  ( \o°o)\\')
        else:
            return bot.say(upsidedown.transform(target))
    except ValueError:
        return bot.reply(u'I can\'t flip that. -_-;')
def sorted_sentence(input):
    #def sorted_sentence():
    # implement a function of your choice that rearranges the poem in a unique way

    for index in range(0, len(input)):
        line = upsidedown.transform(input[index])
        print(str(index) + ": " + line)
Example #6
0
    def flip_text(message=None):
        if not message:
            message = "┻━┻"
        else:
            message = upsidedown.transform(message)

        return unicode("(╯°□°)╯︵ " + message)
Example #7
0
	def doubleflip(room, event, *args):
		if len(args)==0: # no args
			room.sendMessage(random.choice(coolTables["tablesList"]))
		else:
			msg=args[0]
			sss=upsidedown.transform(msg)
			room.sendMessage("{}{}{}".format(sss,random.choice(coolTables["doubleflipsList"]),sss[::-1]))
Example #8
0
def upsidedown(s):
    try:
        import upsidedown as _upsidedown
        return ''.join((_upsidedown.transform(s)))
    except ImportError:
        log("Cannot import upsidedown")
        return s
def flip(bot, trigger):
    """Flips things... because that is the whole point."""
    if not trigger.group(2):
        bot.say('What should I flip? o.o')
        return
    target = trigger.group(2)
    try:
        if target == 'table':
            return bot.say(u'(╯°□°)╯︵ ┻━┻')
        if target == 'table over':
            return bot.say(u'┬──┬ ノ(゜-゜ノ)')
        elif target == 'tables':
            return bot.say(u'┻━┻ ︵ヽ(`Д´)ノ︵ ┻━┻')
        elif target == 'out':
            return bot.say(u'ಠ﹏ಠ')
        elif target == 'bird':
            return bot.say(u't(°□ °t)')
        elif target == 'person':
            return bot.say(u'(╯°Д°)╯︵ /(.□ . \)')
        elif target == 'russia':
            bot.reply('In Soviet Russia, table flip you!')
            return bot.say(u'┬─┬ ︵  ( \o°o)\\')
        else:
            return bot.say(upsidedown.transform(target))
    except ValueError:
        return bot.reply(u'I can\'t flip that. -_-;')
Example #10
0
def flip(bot, trigger):
    """Flips things... because that is the whole point."""
    if not trigger.group(2):
        bot.say("What should I flip? o.o")
        return

    target = " ".join(trigger.group().split()[1:])
    try:
        if target == "table":
            return bot.say(u"(╯°□°)╯︵ ┻━┻")
        elif target == "table over":
            return bot.say(u"┬──┬ ノ(゜-゜ノ)")
        elif target == "tables":
            return bot.say(u"┻━┻ ︵ヽ(`Д´)ノ︵ ┻━┻")
        elif target == "out":
            return bot.say(u"ಠ﹏ಠ")
        elif target == "bird":
            return bot.say(u"t(°□ °t)")
        elif target == "person":
            return bot.say(u"(╯°Д°)╯︵ /(.□ . \)")
        elif target == "russia":
            bot.reply("In Soviet Russia, table flip you!")
            return bot.say(u"┬─┬ ︵  ( \o°o)\\")
        else:
            return bot.say(upsidedown.transform(target))
    except ValueError:
        return bot.reply(u"I can\'t flip that. -_-;")
Example #11
0
async def flip(msg):
    content = msg.content.replace(f"{prefix}flip ", "")
    if content.startswith("upsidedown"):
        await msg.delete()
        await msg.channel.send(
            upsidedown.transform(content.replace("upsidedown", "")))
    elif content.startswith("reverse"):
        await msg.delete()
        await msg.channel.send(content.replace("reverse", "")[::-1])
Example #12
0
def animate():
    asa = upsidedown.transform('  ..')
    for c in itertools.cycle(['..  ', ' : ', asa, ':  ']):
        if done:
            break
        sys.stdout.write('\rLoading ' + c)
        sys.stdout.flush()
        time.sleep(0.05)
    sys.stdout.write('\rDone!     \r')
Example #13
0
 def command(self, bot, comm, groups):
     msg = groups[0].decode('utf-8')
     angry = '(╯°□°)╯︵ '
     try:
         flip = upsidedown.transform(msg).encode('utf-8')
         ret = angry + flip
     except:
         ret = u'ಠ_ಠ'.encode('utf-8')
     bot.reply(comm, ret, encode=False)
     return True
Example #14
0
File: flip.py Project: CMB/hamper
 def command(self, bot, comm, groups):
     msg = groups[0].decode('utf-8')
     angry = '(╯°□°)╯︵ '
     try:
         flip = upsidedown.transform(msg).encode('utf-8')
         ret = angry + flip
     except:
         ret = u'ಠ_ಠ'.encode('utf-8')
     bot.reply(comm, ret)
     return True
Example #15
0
 def mock_in_upsidedown(self, tweet, db):
     tweet_target = self.api.get_status(tweet.in_reply_to_status_id,
                                        tweet_mode="extended")
     text_transformed = Kalimat(tweet_target.full_text)
     text_transformed = text_transformed.removeWords()
     text_transformed = upsidedown.transform(text_transformed)
     self.api.update_status(status=text_transformed,
                            in_reply_to_status_id=tweet.id,
                            auto_populate_reply_metadata=True)
     self.show_what_tweeted(text_transformed)
     db.insert_object({'tweet_last_id': tweet.id})
Example #16
0
 async def upsidecmd(self, message):
     if message.is_reply:
         txt = await message.get_reply_message()
         txt = txt.raw_text
         txt = upsidedown.transform(txt)
         if len(txt) > 4096:
             await message.edit('🐺 Сообщение слишком длинное (`4096`).')
         else:
             await message.edit(txt)
     else:
         await message.edit(
             '🐺 Перешлите сообщения с командой `.upside` для его переворота.'
         )
Example #17
0
 async def apply_guild(self, ctx):
     guild = ctx.guild
     results = db.query(
         ["SELECT name FROM name_backups WHERE id = ?", [str(guild.id)]])
     if not results:
         db.query([
             "INSERT INTO name_backups VALUES (?, ?)",
             [str(guild.id), str(guild.name)]
         ])
         try:
             await guild.edit(name=upsidedown.transform(guild.name))
         except Exception as e:
             print(e)
             print("in apply_guild")
             await asyncio.sleep(10)
Example #18
0
def response(ctx, flow):
 try:
  if re.match('image/',flow.response.headers["content-type"][0]):
   proc = subprocess.Popen('/usb/usr/bin/convert -flip - -', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
   flow.response.content=proc.communicate(flow.response.content)[0]
   proc.stdin.close()
  
  if re.match('text/html',flow.response.headers["content-type"][0]):
   flow.response.decode()
   soup = BeautifulSoup(flow.response.content)
   for text in soup.findAll(text=True):
    text.replaceWith(upsidedown.transform(text))
   
   flow.response.content=str(soup)
 
 except IndexError:
  ctx.log("no content-type[0]")
Example #19
0
 async def apply_roles(self, ctx):
     guild = ctx.guild
     for role in guild.roles:
         await asyncio.sleep(1)
         results = db.query(
             ["SELECT name FROM name_backups WHERE id = ?", [str(role.id)]])
         if not results:
             db.query([
                 "INSERT INTO name_backups VALUES (?, ?)",
                 [str(role.id), str(role.name)]
             ])
             try:
                 await role.edit(name=upsidedown.transform(role.name))
             except Exception as e:
                 print(e)
                 print(f"in apply_roles / {role.name}")
                 await asyncio.sleep(10)
Example #20
0
def rage(response, args=[]):
    toFlip = ''
    donger = '(ノಠ益ಠ)ノ彡'
    for n in range(0, len(args)):
        toFlip += args[n] + " "

    if toFlip == '':
        toFlip = unicode('┻━┻', "utf-8")

    try:
        donger = unicode(donger, "utf-8")
        flippedmsg = upsidedown.transform(toFlip)
        return [donger + flippedmsg]
    except:
        print "PantherBot:Log:Flip:Error in flip"
        return [
            "Sorry, I can't seem to flip right now, or you gave an invalid argument"
        ]  # noqa: 501
Example #21
0
 async def apply_channels(self, ctx):
     guild = ctx.guild
     for channel in guild.channels:
         await asyncio.sleep(1)
         results = db.query([
             "SELECT name FROM name_backups WHERE id = ?",
             [str(channel.id)]
         ])
         if not results:
             try:
                 db.query([
                     "INSERT INTO name_backups VALUES (?, ?)",
                     [str(channel.id), str(channel.name)]
                 ])
                 await channel.edit(name=upsidedown.transform(channel.name))
             except Exception as e:
                 print(e)
                 print(f"in apply_channels / {channel.name}")
                 await asyncio.sleep(10)
Example #22
0
def run(response, args=[]):
    response_obj = Response(sys.modules[__name__])
    toFlip = ''
    donger = '(╯°□°)╯︵'
    if len(args) >= 0:
        for n in range(0, len(args)):
            toFlip += args[n] + " "

    if toFlip == '':
        toFlip = unicode('┻━┻', "utf-8")

    try:
        donger = unicode(donger, "utf-8")
        logger.info(toFlip[:15 or len(toFlip)] + "...")
        flippedmsg = upsidedown.transform(toFlip)
        response_obj.messages_to_send.append(donger + flippedmsg)
    except Exception as e:
        logger.error(str(e))
        response_obj.status_code = -1
    return response_obj
Example #23
0
def run(response, args=[]):
    response_obj = Response(sys.modules[__name__])
    toFlip = ''
    donger = '(ノಠ益ಠ)ノ彡'
    for n in range(0, len(args)):
        toFlip += args[n] + " "

    if toFlip == '':
        toFlip = unicode('┻━┻', "utf-8")

    try:
        donger = unicode(donger, "utf-8")
        logger.info(toFlip[:15 or len(toFlip)] + "...")
        flippedmsg = upsidedown.transform(toFlip)
        response_obj.messages_to_send.append(donger + flippedmsg)
    except Exception as e:
        logger.error("Error in flip: " + str(e))
        response_obj.messages_to_send.append(
            "Sorry, I can't seem to flip right now, or you gave an invalid argument"
        )
    return response_obj
Example #24
0
def processText():
    
    # decode the Json text from the request Body, returns a Python object
    data = request.get_json()
    
    #extract from the Pithon object the fields that we are interested in
    text = data['text']
    
    # process the string
    if data['reverse'] :
        text = text[::-1] 
        # full-lenght slice of the string, with increment -1
        # see https://docs.python.org/2.7/reference/expressions.html#slicings
        # examples at: https://docs.python.org/2.7/whatsnew/2.3.html?highlight=slicing#extended-slices 
        
    if data['flip'] :
        text = transform(text) 

    # build the response object
    result = { 'text': text }
    # return the object in json format
    return jsonify(result)
Example #25
0
def flip(inp):
    ".flip <something> -- wow mom, life upside down"

    return transform(inp)
Example #26
0
 async def upsidedown(self, context, *, text):
     text = text.replace('||', '')
     text = upsidedown.transform(text)
     await context.send(text)
Example #27
0
 def on_command(self, connection, commander, replyto, groups):
     response = u"(\u256F\u00B0\u25A1\u00B0)\u256F \uFE35 " + upsidedown.transform(groups[0])
     connection.privmsg(replyto, response)
Example #28
0
 async def updown(self, ctx, *, text: str):
     await ctx.send(upsidedown.transform(text))
Example #29
0
	def flip(room, event, *args):
		if len(args)==0: # no args
			room.sendMessage(random.choice(coolTables["tablesList"]))
		else:
			msg=args[0]
			room.sendMessage(random.choice(coolTables["flipsList"])+upsidedown.transform(msg)[::-1])
Example #30
0
    def privmsg(self, user, channel, msg):
        
                
        
        
        
        
        try:
            print channel+'>',user+':',msg
            user_nick,_,_ = user.partition('!')
            
            variables = {'nick':self.nickname,'user_nick':user_nick,'response_channel':channel,'channel':channel}
            variables['response_prefix'] = user_nick + ': '
            
            """
            #if this is not a pm
            if channel != self.nickname:
                if msg.startswith(self.nickname + ":"):
                    self.msg(channel, user_nick+': '+ '/msg me, or pm me, I cannot do business in an open channel.')
                    return
                return
            """
            
            full_cmd = ''
            
            variables['in_channel'] = True
            
            #if this is a pm
            if channel == self.nickname:
                
                
                variables['response_channel'] = user_nick
                variables['response_prefix'] = ''
                variables['in_channel'] = False
                full_cmd = msg
                
                
                if msg.startswith(self.nickname + ":"):
                    self.msg(variables['response_channel'], variables['response_prefix']+ 'This is a PM, Don\'t prefix your commands with "{botnick}:".'.format(botnick=self.nickname))
                    return
                
            elif msg.startswith(self.nickname + ":"):
                full_cmd = msg[ len(self.nickname + ":"): ].strip()
                
            else:
                #not directed at the bot
                
                if msg.lower().find("sholom") != -1:
                
                    dweed_exasperated_msgs = ['Oh Dweed ...', 'JeNug SHoiN!','Oy. Do you even lift??!', 'Come at me bro', 'Ain\'t nobody got time for that.']
                    self.msg(channel, dweed_exasperated_msgs[random.randint(0,len(dweed_exasperated_msgs)-1)])
                    
                    return
                
                if msg.find("sS") != -1 or msg.find("hH") != -1:# or msg.find(u'Hɥ') != -1 or msg.find(u'Ss') != -1:
                    self.msg(channel, upsidedown.transform(msg).encode('utf-8'))
                    
                    return
                
                
                if msg.lower().find('come at me') != -1:
                    rurls = [
                                'http://img.pr0gramm.com/2013/04/ggpkbtv.gif', #pool table nut
                                'http://i.imgur.com/Zm8WxSG.gif', #Yoda
                                'http://i.imgur.com/m4fOtwE.gif', #sith
                                'http://i.imgur.com/uktLLMF.gif', #mighty spider
                                'http://i.imgur.com/F0ja0Y2.gif', #matrix guy
                                'http://i.imgur.com/aB7Ujnl.gif', #dean supernatural
                                'http://i.imgur.com/iBA9903.gif', #stick figures playing game
                            ]
                    
                    rurl = random.choice(rurls)
                    
                    self.msg(channel, variables['response_prefix'] \
                        + shorten_url(rurl).encode('utf-8'))
                
                #print 'self.factory.non_cmd_privmsg_monitors:',self.factory.non_cmd_privmsg_monitors
                for cb in self.factory.non_cmd_privmsg_monitors:
                    try:
                        cb(self,variables,user,channel,msg)
                    except Exception as e:
                        print 'exception in Bot.privmsg(), privmsg_cb (',cb,') e:',e
                        traceback.print_exc(file=sys.stdout)
                return
            
            
            
            if len(full_cmd) == 0:
                self.msg(channel, 'shhh'.format(**variables))
                return
            
            if full_cmd[0] == '!':
                self.run_command(full_cmd[1:],variables)
                return
            
            
            full_cmd = full_cmd.lower()
            
            d = {'shalom':'shalom {user_nick}, my name is {nick}',
                 'sholom':'Oh Dweed ...'}
            
            
            if full_cmd not in d:
                self.msg(variables['response_channel'], 'Odd, I thought I heard something.'.format(**variables))
                return
            
            self.msg(channel, d[full_cmd].format(**variables))
            
            return
            
                

            pass
        except Exception as e:
            traceback.print_exc(file=sys.stdout)

            
            print 'Exception:',e
Example #31
0
def word_upside_downer(token: str) -> str:
    # Quases upside down word transformer

    token = upsidedown.transform(token)

    return token
Example #32
0
"""
flip_out.py
=====
upsidedown is a module that allows you to flip the characters in a string so that it they are upside-down.  Read the documentation to learn how to use it: http://pypi.python.org/pypi/upsidedown/0.3

Prep:
1. Open terminal and run: pip install upsidedown
2. You should see the following:
-----
Downloading/unpacking upsidedown
  Running setup.py egg_info for package upsidedown
    
Installing collected packages: upsidedown
  Running setup.py install for upsidedown
    
    Installing upsidedown script to /usr/local/bin
Successfully installed upsidedown
Cleaning up...
-----

Code
1.  Bring in the upsidedown module 
2.  Check out the documentation: http://pypi.python.org/pypi/upsidedown/0.3
3.  Print the string "flip out!" upside-down using the function specified in the documentation
"""
import upsidedown
print upsidedown.transform('flip out!')
Example #33
0
 def flip(self, s):
     '''Flip latin characters in s to create an "upside-down" impression.'''
     s = self.unescape(s)
     return upsidedown.transform(s)
Example #34
0
    for i, line in enumerate(lines):
        if line.strip() == '':
            continue
        else:
            # random upper case or scramble case event
            if random.random() < 0.333:
                if random.random() < 0.5:
                    line = line.upper()
                else:
                    newline = ""
                    for char in line:
                        if random.random() < 0.5:
                            newline += char.upper()
                        else:
                            newline += char.lower()
                    line = newline
            # random upside down event
            if random.random() < 0.05:
                line = upsidedown.transform(line)
            evt.wait()
            if quit_next:
                evt.clear()
                exit()
            sleep(0.03)
            line = line + " ({}/{})".format(i + 1, total_lines)
            k.type(line)

            k.press(Key.enter)
            k.release(Key.enter)
            evt.clear()
Example #35
0
    def privmsg(self, user, channel, msg):
        """This will get called when the bot receives a message."""
        source = user.split('!', 1)[0]
        global teddy_mute

        if msg.lower().startswith("!%s" % self.nickname):
            parse_last = re.split(' ', msg.strip())
            if len(parse_last) == 2:
                if source == 'jason' and parse_last[1] == 'mute':
                    teddy_mute = True
                    self.msg(channel, 'i will stop talking now ' + source)
                elif source == 'jason' and parse_last[1] == 'unmute':
                    teddy_mute = False
                    self.msg(channel, 'lets talk ' + source)

        if msg.lower().startswith("!%s" % "all"):
            parse_last = re.split(' ', msg.strip())
            if len(parse_last) == 2:
                for url in self.url_by_source(parse_last[1]):
                    self.msg(source, url)

        if msg.lower().startswith("!%s" % "search"):
            parse_last = re.split(' ', msg.strip())
            if len(parse_last) == 2:
                for url in self.url_by_search(parse_last[1]):
                    self.msg(source, url)

        if msg.lower().startswith("!%s" % "last"):
            parse_last = re.split(' ', msg.strip())
            if len(parse_last) == 2:
                short = self.get_short_from_db('source', parse_last[1])
                title = self.get_title_from_db('short', short)
                self.msg(channel, title)
                self.msg(channel, "http://wgeturl.com/" + short)
            elif len(parse_last) == 1:
                short = self.get_short_from_db('source', source)
                title = self.get_title_from_db('short', short)
                self.msg(channel, title)
                self.msg(channel, "http://wgeturl.com/" + short)
            else:
                self.msg(channel, "!last username")

        if msg.lower().startswith("!%s" % "stock"):
            parse_last = re.split(' ', msg.strip())
            try:
                stock_data = stock.get(parse_last[1])
                self.msg(channel, stock_data)
            except:
                print "Unexpected error:", sys.exc_info()

        if msg.lower().startswith("!%s" % "flip"):
            parse_last = msg.strip()[6:]
            angry = '(╯°□°)╯︵'

            if parse_last:
                flip = upsidedown.transform(parse_last)
                flipit = '%s %s' % (angry, flip.encode('utf-8'))
            else:
                flipit = '%s %s' % (angry, '┻━┻ ')

            try:
                self.msg(channel, flipit)
            except:
                print "Unexpected error:", sys.exc_info()

        if msg.lower().startswith("!%s" % "moofi"):
            parse_last = re.split(' ', msg.strip())
            try:
                items = woot.get(woot_key, event='moofi')
                for item in items:
                    output = "%s - Sale:$%s List:$%s" % (item['title'], item['saleprice'], item['listprice'])
                    short = self.write_url_to_db(source, item['url'])
                    self.msg(channel, output)
                    self.msg(channel, "http://wgeturl.com/" + short)
            except:
                print "Unexpected error:", sys.exc_info()

#       if msg.lower().startswith("!%s" % "woot"):
#           parse_last = re.split(' ', msg.strip())
#           try:
#               item = woot.get(woot_key)
#               output = "%s - Sale:$%s List:$%s" % (item['title'], item['saleprice'], item['listprice'])
#               short = self.write_url_to_db(source, item['url'])
#               self.msg(channel, output)
#               self.msg(channel, "http://wgeturl.com/" + short)
#           except:
#               print "Unexpected error:", sys.exc_info()

        if "pug me" in msg.lower():
            self.msg(channel, getpug())

        if "lgtm" in msg.lower():
            self.msg(channel, getlgtm())

        if "t**s" in msg.lower():
            self.msg(channel, getreddit('t**s'))

        if msg.lower().startswith("!r"):
            m = re.search('!r\W(.*)', msg.lower())
            self.msg(channel, getreddit(m.group(1)))

        if msg.lower().endswith('++'):
            m = re.search('(.*)\+\+', msg.lower())
            score.increment(m.group(1))

        if msg.lower().endswith('--'):
            m = re.search('(.*)\-\-', msg.lower())
            score.decrement(m.group(1))

        if msg.lower().startswith('!score'):
            user_score_name = re.split(' ', msg.strip())[1]

            user_score = score.get_score(user_score_name)
            self.msg(channel, '%s has %s points!' % (user_score_name, user_score))

        if msg.lower().startswith("!%s" % "dance"):
            self.msg(channel, ":D\<")
            self.msg(channel, ":D|<")
            self.msg(channel, ":D/<")
            self.msg(channel, ":D|<")

        if msg.lower().startswith("!%s" % "angrydance"):
            self.msg(channel, ">\D:")
            self.msg(channel, ">|D:")
            self.msg(channel, ">/D:")
            self.msg(channel, ">|D:")

        if re.search("http", msg.lower()) and source != 'wesley':
            try:
                parse_string = msg[msg.find("http"):]
                url = parse_string.strip()
                short = self.write_url_to_db(source, url)
                title = self.get_title_from_db('short', short)
                self.msg(channel, title)
                if (len(parse_string) >= 29):
                    self.msg(channel, "http://wgeturl.com/" + short)
            except:
                print "Unexpected error:", sys.exc_info()

        if "teddy" in msg.lower():
            try:
                teddy_response = self.teddy_ai(msg.lower())
                self.msg(channel, source + ": " + teddy_response)
            except:
                self.msg(channel, source + ": My brain is broken :(")
Example #36
0
from __future__ import unicode_literals

import upsidedown

assert upsidedown.transform('Hello there') == '\u01dd\u0279\u01dd\u0265\u0287 o\ua781\ua781\u01ddH';
    def on_message(self, message):
        lcontent = message.content.strip().lower()

        # Only read commands from other users on the current channel
        if message.author.id == self.user.id:
            return
        # Only read commands that we are mentioned in
        # elif self.user.id not in [u.id for u in message.mentions]:
        #     return
        # Only read commands from channels we are active in
        elif message.channel.id not in [c.id for c in self.channels]:
            if '!wakeup' not in lcontent:
                return

        ## Parse commands in current channel

        # $help - print help
        if '!help' in lcontent:
            self.send_message(message.channel, self.halp(), False)

        # $info - dump some misc info
        elif '!info' in lcontent:
            self.send_message(message.channel, self.info(message.channel), False)

        # $last - show last tweet
        elif '!last' in lcontent:
            old_count = self.ntweets
            if self.stream.last():
                self.tweet(self.stream.last(), True, False)
            else:
                self.send_message(message.channel, self.pre+"No tweet to display.")
            self.ntweets = old_count # not actually a new tweet

        # $top <N> - show last N tweets
        elif '!top' in lcontent:
            latest = list(self.stream.latest())

            # Get count argument
            count = self.stream.store
            lsplit = lcontent.split()
            ind = lsplit.index('!top')
            if len(lsplit) > ind and ind >= 0:
                try:
                    count = int(lsplit[ind+1])
                except ValueError:
                    self.send_message(message.channel,
                                      self.pre+"Invalid !top count, defaulting to "
                                      +str(count)+".")
            # Hard limits on count
            if count < 1:
                return
            elif count > self.stream.store:
                count = self.stream.store

            old_count = self.ntweets
            for tweet in latest[-count:]:
                self.tweet(tweet, True, False)
            self.ntweets = old_count # don't add to tweet count

        # $follow <user> - switch to following a new Twitter user
        elif '!follow' in lcontent:
            # e.g. "$follow user"
            lsplit = lcontent.split()
            ind = lsplit.index('!follow')
            if len(lsplit) > ind and ind >= 0:
                tuser = message.content.split()[ind+1]
                self.stream.disconnect()
                self.follow(tuser, message.channel)

        # $addchannel - add new channel to receive tweets
        elif '!wakeup' in lcontent:
            channel_list = [c for c in self.get_all_channels()]
            for c in channel_list:
                if c.type == 'text' and c.name.encode('utf-8') in allowed_channels:
                    self.channels.append(c)
            self.channels.append(message.channel)
            self.send_message(message.channel, "I am awake i swear ResidentSleeper ")
            for tuser in initial_followed_users:
                self.follow(tuser, message.channel)

        # $rmchannel - remove channel from receiving tweets
        elif '!rmchannel' in lcontent:
            ind = self.channels.index(message.channel)
            if ind >= 0:
                del self.channels[ind]
                self.send_message(message.channel, self.pre+"Channel removed.")

        # $mention - register user to be mentioned on receiving tweets
        elif '!mention' in lcontent:
            if message.channel.id not in self.mentions:
                self.mentions[message.channel.id] = list()
            self.mentions[message.channel.id].append(message.author)
            self.send_message(message.channel,
                self.pre+"You WILL be @mentioned when tweets are received.")

        # $nomention - remove user from mention list per channel
        elif '!nomention' in lcontent:
            if message.channel.id in self.mentions:
                self.mentions[message.channel.id].remove(message.author)
                self.send_message(message.channel,
                    self.pre+"You will NOT be @mentioned when tweets are received.")

        elif '!resend' in lcontent:
            self.tweet(self.stream.last())

        # $quit - kill the bot
        elif '!quit' in lcontent:
            self.end()

        elif '!flip' in lcontent:
            lsplit = lcontent.split()
            ind = lsplit.index('!flip')
            if len(lsplit) > ind and ind >= 0:
                target = message.content.split()[ind+1]
                try:
                    if target not in exception_users:
                        self.send_message(message.channel, table_flip.decode('utf-8') + '   '
                                          + upsidedown.transform(target))
                    else:
                        self.send_message(message.channel, exception_msg + ' ' + table_flip.decode('utf-8') + '   ' +
                                          upsidedown.transform(str(message.author)))
                except AttributeError:
                    print('F**K')

        elif '!hype' in lcontent:
            self.send_message(message.channel, hype_text)

        elif '!mediaso' in lcontent:
            self.send_message(message.channel, mediaso)

        elif '!selfdestruct' in lcontent:
            self.send_message(message.channel, selfdestruct)

        elif '!8ball' in lcontent:
            lsplit = lcontent.split()
            ind = lsplit.index('!8ball')
            print(lsplit)
            test = False
            for c in lsplit:
                if '?' in c:
                    test = True
            if len(lsplit) >= 3 and ind >= 0 and test:
                try:
                    r = requests.get(ball_url)
                    self.send_message(message.channel, r.text)
                except Exception:
                    self.send_message(message.channel, global_error)
            else:
                self.send_message(message.channel, ball_error)
        elif '!choose' in lcontent:
            lsplit = lcontent.replace('!choose ', '')
            if 'or' in lsplit:
                lsplit = lsplit.split(' or ')
                if lsplit:
                    self.send_message(message.channel, choose_response_1 + random.choice(lsplit) + choose_response_2)
                else:
                    self.send_message(message.channel, choose_command_error)
            else:
                self.send_message(message.channel, choose_command_error)
        elif '!rps' in lcontent:
            lsplit = lcontent.split()
            ind = lsplit.index('!rps')
            choice = lsplit[1]
            rpsbot = {"rock": ":moyai:",
                      "paper": ":page_facing_up:",
                      "scissors": ":scissors:"}
            if choice in rpsbot.keys():
                botchoice = randchoice(list(rpsbot.keys()))
                msgs = {
                    "win": " You win {}!".format(str(message.author)),
                    "square": " We're square {}!".format(str(message.author)),
                    "lose": " You lose {}!".format(str(message.author))
                }
                if choice == botchoice:
                    self.send_message(message.channel, rpsbot[botchoice] + msgs["square"])
                elif choice == "rock" and botchoice == "paper":
                    self.send_message(message.channel, rpsbot[botchoice] + msgs["lose"])
                elif choice == "rock" and botchoice == "scissors":
                    self.send_message(message.channel, rpsbot[botchoice] + msgs["win"])
                elif choice == "paper" and botchoice == "rock":
                    self.send_message(message.channel, rpsbot[botchoice] + msgs["win"])
                elif choice == "paper" and botchoice == "scissors":
                    self.send_message(message.channel, rpsbot[botchoice] + msgs["lose"])
                elif choice == "scissors" and botchoice == "rock":
                    self.send_message(message.channel, rpsbot[botchoice] + msgs["lose"])
                elif choice == "scissors" and botchoice == "paper":
                    self.send_message(message.channel, rpsbot[botchoice] + msgs["win"])
            else:
                self.send_message(message.channel, "Choose rock, paper or scissors CimpBro ")
        elif '!muffin' in lcontent:
            lsplit = lcontent.split()
            ind = lsplit.index('!muffin')
            user = lsplit[1]
            self.send_message(message.channel, muffin_msg_1 + user + muffin_msg_2)
        elif 'muffin' in lcontent:
            self.send_message(message.channel, 'HeavyBreathing')
        elif '!rip' in lcontent:
            self.send_message(message.channel, 'PepeRIP')
        elif '!commands' in lcontent:
            self.send_message(message.channel, commands)
"""
flip_out.py
=====
upsidedown is a module that allows you to flip the characters in a string so that it they are upside-down.  Read the documentation to learn how to use it: http://pypi.python.org/pypi/upsidedown/0.3

Prep:
1. Open terminal and run: pip install upsidedown
2. You should see the following:
-----
Downloading/unpacking upsidedown
  Running setup.py egg_info for package upsidedown
    
Installing collected packages: upsidedown
  Running setup.py install for upsidedown
    
    Installing upsidedown script to /usr/local/bin
Successfully installed upsidedown
Cleaning up...
-----

Code
1.  Bring in the upsidedown module 
2.  Check out the documentation: http://pypi.python.org/pypi/upsidedown/0.3
3.  Print the string "flip out!" upside-down using the function specified in the documentation
"""

import upsidedown

print upsidedown.transform("flip out!")
Example #39
0
    async def upsidedown(self, ctx, *, text: str):
        ''' Prints the given text upside down '''

        result = upsidedown.transform(text)
        await ctx.message.edit(content=result)
Example #40
0
def make_upsidedown(text):
    return upsidedown.transform(text)
Example #41
0
def flips(bot, trigger):
    target = trigger.group(1).strip()
    if target == 'a table':
        bot.say("(╯°□°)╯︵ ┻━┻")
    else:
        bot.say("(╯°□°)╯︵ %s" % transform(target))
Example #42
0
def fuckWord(str):
    if str == "":
        return "Передайте текст для функции, чтобы текст перевернулся"
    else:
        return upsidedown.transform(str)
Example #43
0
    def privmsg(self, user, channel, msg):

        try:
            print channel + ">", user + ":", msg
            user_nick, _, _ = user.partition("!")

            variables = {"nick": self.nickname, "user_nick": user_nick, "response_channel": channel, "channel": channel}
            variables["response_prefix"] = user_nick + ": "

            """
            #if this is not a pm
            if channel != self.nickname:
                if msg.startswith(self.nickname + ":"):
                    self.msg(channel, user_nick+': '+ '/msg me, or pm me, I cannot do business in an open channel.')
                    return
                return
            """

            full_cmd = ""

            variables["in_channel"] = True

            # if this is a pm
            if channel == self.nickname:

                variables["response_channel"] = user_nick
                variables["response_prefix"] = ""
                variables["in_channel"] = False
                full_cmd = msg

                if msg.startswith(self.nickname + ":"):
                    self.msg(
                        variables["response_channel"],
                        variables["response_prefix"]
                        + 'This is a PM, Don\'t prefix your commands with "{botnick}:".'.format(botnick=self.nickname),
                    )
                    return

            elif msg.startswith(self.nickname + ":"):
                full_cmd = msg[len(self.nickname + ":") :].strip()

            else:
                # not directed at the bot

                if msg.lower().find("sholom") != -1:

                    dweed_exasperated_msgs = [
                        "Oh Dweed ...",
                        "JeNug SHoiN!",
                        "Oy. Do you even lift??!",
                        "Come at me bro",
                        "Ain't nobody got time for that.",
                    ]
                    self.msg(channel, dweed_exasperated_msgs[random.randint(0, len(dweed_exasperated_msgs) - 1)])

                    return

                if msg.find("sS") != -1 or msg.find("hH") != -1:  # or msg.find(u'Hɥ') != -1 or msg.find(u'Ss') != -1:
                    self.msg(channel, upsidedown.transform(msg).encode("utf-8"))

                    return

                if msg.lower().find("come at me") != -1:
                    rurls = [
                        "http://img.pr0gramm.com/2013/04/ggpkbtv.gif",  # pool table nut
                        "http://i.imgur.com/Zm8WxSG.gif",  # Yoda
                        "http://i.imgur.com/m4fOtwE.gif",  # sith
                        "http://i.imgur.com/uktLLMF.gif",  # mighty spider
                        "http://i.imgur.com/F0ja0Y2.gif",  # matrix guy
                        "http://i.imgur.com/aB7Ujnl.gif",  # dean supernatural
                        "http://i.imgur.com/iBA9903.gif",  # stick figures playing game
                    ]

                    rurl = random.choice(rurls)

                    self.msg(channel, variables["response_prefix"] + shorten_url(rurl).encode("utf-8"))

                # print 'self.factory.non_cmd_privmsg_monitors:',self.factory.non_cmd_privmsg_monitors
                for cb in self.factory.non_cmd_privmsg_monitors:
                    try:
                        cb(self, variables, user, channel, msg)
                    except Exception as e:
                        print "exception in Bot.privmsg(), privmsg_cb (", cb, ") e:", e
                        traceback.print_exc(file=sys.stdout)
                return

            if len(full_cmd) == 0:
                self.msg(channel, "shhh".format(**variables))
                return

            if full_cmd[0] == "!":
                self.run_command(full_cmd[1:], variables)
                return

            full_cmd = full_cmd.lower()

            d = {"shalom": "shalom {user_nick}, my name is {nick}", "sholom": "Oh Dweed ..."}

            if full_cmd not in d:
                self.msg(variables["response_channel"], "Odd, I thought I heard something.".format(**variables))
                return

            self.msg(channel, d[full_cmd].format(**variables))

            return

            pass
        except Exception as e:
            traceback.print_exc(file=sys.stdout)

            print "Exception:", e
Example #44
0
 def response(self, query, message):
     return upsidedown.transform(query)
Example #45
0
"""
flip_out.py
=====
upsidedown is a module that allows you to flip the characters in a string so that it they are upside-down.  Read the documentation to learn how to use it: http://pypi.python.org/pypi/upsidedown/0.3

Prep:
1. Open terminal and run: pip install upsidedown
2. You should see the following:
-----
Downloading/unpacking upsidedown
  Running setup.py egg_info for package upsidedown
    
Installing collected packages: upsidedown
  Running setup.py install for upsidedown
    
    Installing upsidedown script to /usr/local/bin
Successfully installed upsidedown
Cleaning up...
-----

Code
1.  Bring in the upsidedown module 
2.  Check out the documentation: http://pypi.python.org/pypi/upsidedown/0.3
3.  Print the string "flip out!" upside-down using the function specified in the documentation
"""
import upsidedown
print upsidedown.transform("flip out!")
print upsidedown.transform("Bacon Stripssss!!")
def flip(*, what_to_flip):
    print("flip:" + what_to_flip)
    if(what_to_flip == "table" ):
        yield from bot.say("(╯✿ㆁᴗㆁ)╯︵ ┻━┻")
    else:
        yield from bot.say("(╯✿ㆁᴗㆁ)╯︵" + upsidedown.transform(what_to_flip) )
Example #47
0
 async def _upsidedown(self, ctx, *, text:str):
     text = upsidedown.transform(text)
     await ctx.send(text)
Example #48
0
def word_upside_downer_preserve_char_order(token: str) -> str:
    new_token = []
    for char_ in token:
        new_token.append(upsidedown.transform(char_))
    return "".join(new_token)
Example #49
0
"""
flip_out.py
=====
upsidedown is a module that allows you to flip the characters in a string so that it they are upside-down.  Read the documentation to learn how to use it: http://pypi.python.org/pypi/upsidedown/0.3

Prep:
1. Open terminal and run: pip install upsidedown
2. You should see the following:
-----
Downloading/unpacking upsidedown
  Running setup.py egg_info for package upsidedown
    
Installing collected packages: upsidedown
  Running setup.py install for upsidedown
    
    Installing upsidedown script to /usr/local/bin
Successfully installed upsidedown
Cleaning up...
-----

Code
1.  Bring in the upsidedown module 
2.  Check out the documentation: http://pypi.python.org/pypi/upsidedown/0.3
3.  Print the string "flip out!" upside-down using the function specified in the documentation
"""
import upsidedown
str = "flip out!"
print upsidedown.transform(str)
Example #50
0
"""
flip_out.py
=====
upsidedown is a module that allows you to flip the characters in a string so that it they are upside-down.  Read the documentation to learn how to use it: http://pypi.python.org/pypi/upsidedown/0.3

Prep:
1. Open terminal and run: pip install upsidedown
2. You should see the following:
-----
Downloading/unpacking upsidedown
  Running setup.py egg_info for package upsidedown
    
Installing collected packages: upsidedown
  Running setup.py install for upsidedown
    
    Installing upsidedown script to /usr/local/bin
Successfully installed upsidedown
Cleaning up...
-----

Code
1.  Bring in the upsidedown module 
2.  Check out the documentation: http://pypi.python.org/pypi/upsidedown/0.3
3.  Print the string "flip out!" upside-down using the function specified in the documentation
"""

import upsidedown
print upsidedown.transform('Say Hello 2 my little Fried')
Example #51
0
flip_out.py
=====
upsidedown is a module that allows you to flip the characters in a string so that it they are upside-down.  Read the documentation to learn how to use it: http://pypi.python.org/pypi/upsidedown/0.3

Prep:
1. Open terminal and run: pip install upsidedown
2. You should see the following:
-----
Downloading/unpacking upsidedown
  Running setup.py egg_info for package upsidedown
    
Installing collected packages: upsidedown
  Running setup.py install for upsidedown
    
    Installing upsidedown script to /usr/local/bin
Successfully installed upsidedown
Cleaning up...
-----

Code
1.  Bring in the upsidedown module 
2.  Check out the documentation: http://pypi.python.org/pypi/upsidedown/0.3
3.  Print the string "flip out!" upside-down using the function specified in the documentation
"""

import upsidedown

m = "Blah blah blah"
a = "This is sparta"
print upsidedown.transform(m)
print upsidedown.transform(a)