async def onCommand(message_in): if message_in.body == '': return message.Message(body='Usage:\ntinyurl [url]') else: try: urllib.request.urlopen(message_in.body.strip()) return message.Message(body=urlopen("http://tinyurl.com/api-create.php?url=" + message_in.body.strip()).read().decode("utf-8")) except Exception as e: return message.Message(body='That website doesn\'t seem to exist')
async def onCommand(message_in): if message_in.command == 'source': return message.Message( body="https://github.com/StarbotDiscord/Starbot") if message_in.command == 'docs': return message.Message(body="http://starbot.readthedocs.io/en/latest/") if message_in.command == 'tests': return message.Message( body="https://travis-ci.org/StarbotDiscord/Starbot")
async def onCommand(message_in): if message_in.command == SERVERINFOCMD: # Get server. server = message_in.server # Create blank embed. server_embed = discord.Embed(color=server.me.color) # Add title of server and icon. server_embed.title = server.name server_embed.description = "Created at {} UTC".format(server.created_at.strftime("%Y-%m-%d %I:%M %p")) server_embed.set_thumbnail(url=server.icon_url) # Add members and role count. server_embed.add_field(name="Members", value=str(server.member_count)) server_embed.add_field(name="Roles", value=str(len(server.roles)), inline=True) # Add channel count and default channel. channels_voice = [c.name for c in server.channels if str(c.type) == "voice"] channels_text = [c.name for c in server.channels if str(c.type) == "text"] server_embed.add_field(name="Channels", value="{} text, {} voice".format(len(channels_text), len(channels_voice))) server_embed.add_field(name="Default Channel", value=server.default_channel.mention, inline=True) # Add region and AFK. server_embed.add_field(name="Voice Region", value=server.region) if server.afk_channel != None: server_embed.add_field(name="AFK Channel", value="{} after {} minutes".format(server.afk_channel.name, int(server.afk_timeout / 60))) else: server_embed.add_field(name="AFK Channel", value="None") # Add verification and owner. server_embed.add_field(name="Verification", value=str(server.verification_level)) server_embed.add_field(name="Owner", value=server.owner.mention, inline=True) # Add server ID to footer. server_embed.set_footer(text="Server ID: {}".format(server.id)) return message.Message("**Server Info:**", embed=server_embed) if message_in.command == EMOTEINFOCMD: # Get emotes. emotelist = "" for emote in sorted(message_in.server.emojis, key=SortEmote): emotelist += str(emote) + " " # Return message. return message.Message("**{}** emotes:\n{}".format(message_in.server.name, emotelist)) if message_in.command == SERVERINVITECMD: # Check that we have perms to create an invite. If not, return error. if not message_in.server.default_channel.permissions_for(message_in.server.me).create_instant_invite: return message.Message("Whoops I don't have permission to create instant invites for this server.") # Create invite and return message. invite = await Bot.client.create_invite(message_in.server.default_channel, unique=False) return message.Message("Use this link to invite people to this server: {}".format(invite.url))
async def onCommand(message_in): # Goldfish if message_in.command == 'goldfish': try: f = urllib.request.urlopen( "http://goldfishapi.azurewebsites.net/goldfish/rand.php").read( ).decode("utf-8") except urllib.error.URLError as e: return message.Message( body='There was an issue connecting to goldfish API.'.format( message_in.body)) imageName = f.split('/') caching.cache_download(f, imageName[-1], caller='goldfish') return message.Message(file='cache/goldfish_' + imageName[-1])
async def onCommand(message_in): '''Run plugin commands.''' if message_in.command == 'excuse': # Give excuses excuse_list = [ "I have an appointment with a robot.", "I was abducted by robots.", "I didn’t know what day it was because I was looking at the Robotic Calendar.", "My robot threw up on my source code.", "I need to take my robot for a walk.", "I had to get a cybernetic head and couldn't get anything done.", "My Robot Assistant blue-screened.", "A kernel panic erased my work.", "Somebody used up the data limit watching YouTube." ] randexcuse = random.randint(0, len(excuse_list) - 1) # Say sorry sorry_list = [ "Please excuse me,", "I'm sorry, but", "I hope you forgive me, because" ] randsorry = random.randint(0, len(sorry_list) - 1) msg = '*{} {}*'.format(sorry_list[randsorry], excuse_list[randexcuse]) # Return newly constructed message return message.Message(msg)
def test_excuse_msg(self): msg = message.Message(body="") msg.command = "excuse" excuse_list = [ "I have an appointment with a robot.", "I was abducted by robots.", "I didn’t know what day it was because I was looking at the Robotic Calendar.", "My robot threw up on my source code.", "I need to take my robot for a walk.", "I had to get a cybernetic head and couldn't get anything done.", "My Robot Assistant blue-screened.", "A kernel panic erased my work.", "Somebody used up the data limit watching YouTube." ] sorry_list = [ "Please excuse me,", "I'm sorry, but", "I hope you forgive me, because" ] msg_list = [] for sorry in sorry_list: for excuse in excuse_list: msg_list.append('*{} {}*'.format(sorry, excuse)) result = yield from excuses.onCommand(msg) self.assertEqual(type(result), type(msg)) self.assertEqual(result.body in msg_list, True)
def test_fun_beta_msg(self): msg = message.Message(body="") msg.command = "beta" result = yield from fun.onCommand(msg) self.assertEqual(type(result), type(msg)) self.assertEqual(result.body, 'It looks like something went wrong') self.assertEqual(result.file, 'beta.jpg')
def test_search_bing(self): msg = message.Message(body="hello world") msg.command = "bing" result = yield from search.onCommand(msg) self.assertEqual(type(result), type(msg)) self.assertEqual(result.body, "Bing search: https://www.bing.com/?q=hello%20world")
def test_search_duck_duck_go(self): msg = message.Message(body="hello world") msg.command = "duckduckgo" result = yield from search.onCommand(msg) self.assertEqual(type(result), type(msg)) self.assertEqual( result.body, "DuckDuckGo search: https://www.duckduckgo.com/?q=hello%20world")
async def onCommand(message_in): searchstring = urllib.parse.quote(str.title(message_in.body.strip())) if not searchstring: return message.Message("Usage: `!wikipedia [article name]") # Form URL formatargs = '?format=json&formatversion=2' actionarg = 'query' propargs = '&prop=extracts&exintro=&explaintext=' otherargs = '&redirects=1' url = 'https://en.wikipedia.org/w/api.php{}&action={}{}{}&titles={}' url = url.format(formatargs, actionarg, propargs, otherargs, searchstring) wikidata_json = caching.json_get(url, caller='wikipedia', name_custom=searchstring) wikidata = json.loads(wikidata_json) try: missing = wikidata["query"]["pages"][0]["missing"] except KeyError: missing = False if missing: return message.Message( "Article {} doesn't exist on Wikipedia!".format(searchstring)) title = wikidata["query"]["pages"][0]["title"] extract = wikidata["query"]["pages"][0]["extract"] # Cleanly cut extract to 900 characters if len(extract) >= 900: extract = extract[:900] extract = extract.rsplit('\n', 1)[0] # Cut to nearest paragraph. extract = extract.rsplit('.', 1)[0] + '.' # Cut to nearest sentence. # Form Embed card embed = discord.Embed(color=discord.Color.green()) embed.set_author(name=title) embed.add_field(name='From Wikipedia, The free Encyclopedia', value=extract) return message.Message(embed=embed)
def test_search_google(self): msg = message.Message(body="hello world") msg.command = "google" result = yield from search.onCommand(msg) self.assertEqual(type(result), type(msg)) print(result) self.assertEqual( result.body, 'Google search: https://www.google.com/#q=hello%20world')
def test_fun_fart_msg(self): msg = message.Message(body="") msg.command = "fart" result = yield from fun.onCommand(msg) msg_list = [ "Poot", "Prrrrt", "Thhbbthbbbthhh", "Plllleerrrrffff", "Toot", "Blaaaaahnk", "Squerk" ] self.assertEqual(type(result), type(msg)) self.assertEqual(result.body in msg_list, True)
def test_botutils_help(self): result = botutils.onInit(__import__('api.plugin')) bot.Bot.plugins.append(result) for command in result.commands: bot.Bot.commands.append(command) msg = message.Message(body="") msg.command = "help" result = yield from botutils.onCommand(msg) self.assertEqual(type(result), type(msg))
def test_botutils_hostinfo(self): server = Server server.me = 'StarBot' msg = message.Message(body="") msg.command = "hostinfo" msg.server = server result = yield from botutils.onCommand(msg) self.assertEqual(type(result), type(msg))
async def onCommand(message_in): if message_in.command == STARCMD: # Get JSON from Reddit API. r_json = caching.json_get( "https://www.reddit.com/r/StarVSTheForcesOfEvil/top.json?sort=top&t=week&limit=100", save=False) posts = json.loads(r_json)["data"]["children"] # Get random post. post = posts[random.randint(0, len(posts) - 1)]["data"] # Store URL in here. url = None # Try to get URL to image, up to 10 times if needed. for i in range(0, 10): # If the preview is valid, use that. if "preview" in post: url = post["preview"]["images"][0]["source"]["url"] else: # Check if URL points to an image. ext_list = ["jpg", "jpeg", "png", "gif", "tiff", "tif"] ext = post["url"].split(".")[-1] if ext in ext_list: url = post["url"] # If we have a URL, exit. if url: break if url: url_parsed = urllib.parse.urlparse(url) caching.cache_download(url, url_parsed.path.split("/")[-1], caller=STARCMD) return message.Message(post["title"], file="cache/{}_{}".format( STARCMD, url_parsed.path.split("/")[-1])) else: # No URL could be found, return error message. return message.Message("Whoops! I couldn't find any posts.")
async def onCommand(message_in): '''Run plugin commands.''' if message_in.command == 'cachecount': if message_in.body == '': return message.Message(body='No plugin specified') return message.Message(body='```{}```'.format( len(glob.glob('cache/{}_*'.format(message_in.body.strip()))))) if message_in.command == 'caches': cache_str = '' for cmd in bot.Bot.commands: cmd_cache_size = len(glob.glob('cache/{}_*'.format(cmd.name))) if cmd_cache_size > 0: cache_str += '{} - {}\n'.format(cmd.name, cmd_cache_size) return message.Message(body='```{}```'.format(cache_str)) if message_in.command == 'totalcache': return message.Message( body='```{}```'.format(len(glob.glob('cache/*'))))
async def onCommand(message_in): if message_in.command == 'starwiki': if message_in.body == '': return message.Message(body='Usage:\nstarwiki [search term]') else: return wikia_get('starvstheforcesofevil', message_in.body) if message_in.command == 'wikia': if message_in.body == '': return message.Message( body='Usage:\nwikia [wikia name] [search term]') input_split = message_in.body.split(' ', 2) print(input_split) if len(input_split) != 3: return message.Message( body='Usage:\nwikia [wikia name] [search term]') return wikia_get(input_split[1], input_split[2])
def test_eat_empty_msg(self): server = Server server.me = 'StarBot' msg = message.Message(body="") msg.command = "eat" msg.server = server result = yield from eat.onCommand(msg) nothing_list = [ '*None*, you sit quietly and eat *nothing*...', '*None*, you\'re *sure* there was something to eat, so you just chew on nothingness...', '*None*, there comes a time when you need to realize that you\'re just chewing nothing\ for the sake of chewing. That time is now.' ] print(result.body) self.assertEqual(type(result), type(msg)) self.assertEqual(result.body in nothing_list, True)
async def onCommand(message_in): '''Run plugin commands.''' # Get user. if message_in.server: me = message_in.server.me else: me = message_in.channel.me # Lenny. if message_in.command == LENNYCMD: # Create message. msg = "( ͡° ͜ʖ ͡°)" # Append extra on if needed. if message_in.body.strip(): msg += "\n" + message_in.body.strip() # Return message. return message.Message(msg, delete=True) # Shrug. if message_in.command == SHRUGCMD: # Create message. msg = r"¯\_(ツ)_/¯" # Append extra on if needed. if message_in.body.strip(): msg += "\n" + message_in.body.strip() # Return message. return message.Message(msg, delete=True) # Tableflip. if message_in.command == TABLEFLIPCMD: # Create message. msg = "(╯°□°)╯︵ ┻━┻" # Append extra on if needed. if message_in.body.strip(): msg += "\n" + message_in.body.strip() # Return message. return message.Message(msg, delete=True) # Fart. if message_in.command == FARTCMD: # Make farts. fart_list = [ "Poot", "Prrrrt", "Thhbbthbbbthhh", "Plllleerrrrffff", "Toot", "Blaaaaahnk", "Squerk" ] randnum = random.randint(0, len(fart_list) - 1) msg = '{}'.format(fart_list[randnum]) # Append extra on if needed. if message_in.body.strip(): msg += "\n" + message_in.body.strip() # Return fart message. return message.Message(msg, delete=True) if message_in.command == BETACMD: return message.Message(body='It looks like something went wrong', file="beta.jpg") if message_in.command == EATCMD: author = displayname.name(message_in.author) member = message_in.body.strip() if message_in.server: mem_check = displayname.memberForName(member, message_in.server.members, me) else: mem_check = displayname.memberForName( member, message_in.channel.recipients, me) # Check if we're eating nothing if member == "": msg_list = [ 'you sit quietly and eat *nothing*...', 'you\'re *sure* there was something to eat, so you just chew on nothingness...', 'there comes a time when you need to realize that you\'re just chewing nothing for the sake of chewing. That time is now.' ] elif mem_check: # We're eating a member - let's do a bot-check if mem_check.id == me.id: # It's me! msg_list = [ 'you try to eat *me* - but unfortunately, I saw it coming - your jaw hangs open as I deftly sidestep.', 'your mouth hangs open for a brief second before you realize that *I\'m* eating *you*.', 'I\'m a bot. You can\'t eat me.', 'your jaw clamps down on... wait... on nothing, because I\'m *digital!*.', 'what kind of bot would I be if I let you eat me?' ] elif mem_check.id == message_in.author.id: # We're eating... ourselves? msg_list = [ 'you clamp down on your own forearm - not surprisingly, it hurts.', 'you place a finger into your mouth, but *just can\'t* force yourself to bite down.', 'you happily munch away, but can now only wave with your left hand.', 'wait - you\'re not a sandwich!', 'you might not be the smartest...' ] else: mem_name = displayname.name(mem_check) msg_list = [ 'you unhinge your jaw and consume *{}* in one bite.'. format(mem_name), 'you try to eat *{}*, but you just can\'t quite do it - you spit them out, the taste of failure hanging in your mouth...' .format(mem_name), 'you take a quick bite out of *{}*. They probably didn\'t even notice.' .format(mem_name), 'you sink your teeth into *{}\'s* shoulder - they turn to face you, eyes wide as you try your best to scurry away and hide.' .format(mem_name), 'your jaw clamps down on *{}* - a satisfying *crunch* emanates as you finish your newest meal.' .format(mem_name) ] else: msg_list = [ 'you take a big chunk out of *{}*. *Delicious.*'.format( member), 'your teeth sink into *{}* - it tastes satisfying.'.format( member), 'you rip hungrily into *{}*, tearing it to bits!'.format( member), 'you just can\'t bring yourself to eat *{}* - so you just hold it for awhile...' .format(member), 'you attempt to bite into *{}*, but you\'re clumsier than you remember - and fail...' .format(member) ] randnum = random.randint(0, len(msg_list) - 1) return message.Message('*{}*, {}'.format(author, msg_list[randnum]))
def test_search_empty_msg(self): msg = message.Message(body="") msg.command = "google" result = yield from search.onCommand(msg) self.assertEqual(type(result), type(msg)) self.assertEqual(result.body, 'I need a topic to search for!')
async def onCommand(message_in): if message_in.command == 'plugins': plugin_list = [] for plugin_in in Bot.plugins: plugin_list.append(plugin_in.name) return message.Message(body='```{}```'.format(', '.join(plugin_list))) if message_in.command == 'commands' or message_in.command == 'help': cmd_names = [] cmd_descs = [] for botcommand in Bot.commands: if botcommand.devcommand != True: cmd_names.append(botcommand.name) cmd_descs.append(botcommand.shortdesc) cmd_list = [] pad_len = len(max(cmd_names, key=len)) for index, value in enumerate(cmd_names): cmd_list.append('{} - {}'.format(cmd_names[index].ljust(pad_len), cmd_descs[index])) return message.Message(body='```{}```'.format('\n'.join(cmd_list))) if message_in.command == 'info': sha = git.git_commit() track = git.git_branch() remote = git.get_remote() link = git.get_url() if track == 'master': embed = discord.Embed(color=discord.Color.red()) elif track == 'unstable': embed = discord.Embed(color=discord.Color.gold()) elif track == 'stable': embed = discord.Embed(color=discord.Color.green()) else: embed = discord.Embed(color=discord.Color.light_grey()) embed.set_author( name='Project StarBot v0.2.0-{} on track {}'.format( sha[:7], track), url=link, icon_url= 'https://pbs.twimg.com/profile_images/616309728688238592/pBeeJQDQ.png' ) embed.add_field(name="Bot Team Alpha", value="CorpNewt\nSydney Erickson\nGoldfish64") embed.add_field( name="Source Code", value= "Interested in poking around inside the bot?\nClick on the link above!" ) embed.set_footer(text="Pulled from {}".format(remote)) return message.Message(embed=embed) if message_in.command == 'plugintree': dups = commands_detect_dups() plugin_string = '```\n' for plugin_in in Bot.plugins: plugin_string += '{}\n'.format(plugin_in.name) plugin_commands = len(plugin_in.commands) index = 0 for command_in in plugin_in.commands: index += 1 if plugin_commands != index: if command_in.name in dups: plugin_string += '├ {} <-- duplicate\n'.format( command_in.name) else: plugin_string += '├ {}\n'.format(command_in.name) else: if command_in.name in dups: plugin_string += '└ {} <-- duplicate\n'.format( command_in.name) else: plugin_string += '└ {}\n'.format(command_in.name) plugin_string += '```' return message.Message(body=plugin_string) if message_in.command == 'uptime': time_current = int(time.time()) time_str = readableTime.getReadableTimeBetween(Bot.startTime, time_current) return message.Message(body='I\'ve been up for *{}*.'.format(time_str)) if message_in.command == 'hostinfo': # Get information about host environment. time_current = int(time.time()) # CPU stats. cpu_threads = os.cpu_count() cpu_usage = psutil.cpu_percent(interval=1) # Memory stats. mem_stats = psutil.virtual_memory() mem_percent = mem_stats.percent mem_used = convert_size(mem_stats.used) mem_total = convert_size(mem_stats.total) # Platform info. platform_current = platform.platform() # Python version info. pyver_major = sys.version_info.major pyver_minor = sys.version_info.minor pyver_micro = sys.version_info.micro pyver_release = sys.version_info.releaselevel # Storage info. stor = psutil.disk_usage('/') stor_used = convert_size(stor.used) stor_total = convert_size(stor.total) stor_free = convert_size(stor.total - stor.used) # Format hostinfo with OS, CPU, RAM, storage, and other bot info. msg = '***{}\'s*** **Home:**\n'.format( displayname.name(message_in.server.me)) msg += '```Host OS : {}\n'.format(platform_current) msg += 'Host Python : {}.{}.{} {}\n'.format(pyver_major, pyver_minor, pyver_micro, pyver_release) if not isinstance(cpu_threads, int): msg += 'Host CPU usage: {}% of {}\n'.format( cpu_usage, platform.machine()) elif cpu_threads > 1: msg += 'Host CPU usage: {}% of {} ({} threads)\n'.format( cpu_usage, platform.machine(), cpu_threads) else: msg += 'Host CPU usage: {}% of {} ({} thread)\n'.format( cpu_usage, platform.machine(), cpu_threads) msg += 'Host RAM : {} ({}%) of {}\n'.format( mem_used, mem_percent, mem_total) msg += 'Host storage : {} ({}%) of {} - {} free\n'.format( stor_used, stor.percent, stor_total, stor_free) msg += 'Hostname : {}\n'.format(platform.node()) msg += 'Host uptime : {}```'.format( readableTime.getReadableTimeBetween(psutil.boot_time(), time.time())) # Return completed message. return message.Message(body=msg) if message_in.command == 'cpuinfo': # Get CPU usage and create string for message. cpu_pcts = psutil.cpu_percent(interval=0.1, percpu=True) cpu_pct_str = '{}\n'.format(platform.processor()) cpu_threads = psutil.cpu_count() cpu_cores = psutil.cpu_count(logical=False) cpu_arch = platform.machine() # First, check to see if we can accurately determine the number of physical cores. If not, omit the core count. if not cpu_cores: if cpu_threads > 1: cpu_pct_str += '{} threads of {}'.format(cpu_threads, cpu_arch) else: cpu_pct_str += '{} thread of {}'.format(cpu_threads, cpu_arch) elif cpu_cores > 1: # Multiple cores. cpu_pct_str += '{} threads - {} cores of {}'.format( cpu_threads, cpu_cores, cpu_arch) else: if psutil.cpu_count() > 1: # Multiple threads, single core. cpu_pct_str += '{} threads - {} core of {}'.format( cpu_threads, cpu_cores, cpu_arch) else: # Single thread, single core. cpu_pct_str += '{} thread - {} core of {}'.format( cpu_threads, cpu_cores, cpu_arch) # Build CPU usage graph. cpu_pct_str += '\n\n' for index, value in enumerate(cpu_pcts): cpu_pct_str += 'CPU {}: {}\n'.format( str(index), progressBar.makeBar(cpu_pcts[index])) # Return completed message. return message.Message(body='```{}```'.format(cpu_pct_str)) if message_in.command == 'setprefix': if settings.owners_check(message_in.author.id): prefix = message_in.body.split(' ', 1)[-1] settings.prefix_set(message_in.server.id, prefix) return message.Message(body='Prefix set to {}'.format(prefix)) else: return message.Message(body='Only my owner can set the prefix!') if message_in.command == 'getprefix': return message.Message(body='Prefix is {}'.format( settings.prefix_get(message_in.server.id))) if message_in.command == 'speedtest': if settings.owners_check(message_in.author.id): speed = pyspeedtest.SpeedTest() msg = '**Speed Test Results:**\n' msg += '```\n' msg += ' Ping: {}\n'.format(round(speed.ping(), 2)) msg += 'Download: {}MB/s\n'.format( round(speed.download() / 1024 / 1024, 2)) msg += ' Upload: {}MB/s```'.format( round(speed.upload() / 1024 / 1024, 2)) return message.Message(body=msg) else: return message.Message( body='You do not have permisison to run a speedtest.') if message_in.command == "addowner": if settings.owners_get(): try: if settings.owners_check(message_in.author.id): member = message_in.body.strip() new_member = displayname.memberForName( member, message_in.server) if settings.owners_check(new_member.id): return message.Message( body="User is already an owner.") elif new_member.bot: return message.Message(body="Bots cannot be owners.") else: settings.owners_add(new_member.id) return message.Message( body="Added owner successfully.") else: return message.Message( body="You aren't an owner of the bot.") except AttributeError: return message.Message(body="Invalid user.") else: settings.owners_add(message_in.author.id) return message.Message( body= "You have successfully claimed yourself as the first owner!") if message_in.command == 'owners': owners = [] if not settings.owners_get(): return message.Message(body='I have no owners') for owner in settings.owners_get(): user = displayname.memberForID(str(owner), message_in.server) if user: owners.append(str(user.name)) else: owners.append(str(owner)) owner_list = ', '.join(owners) return message.Message(body=owner_list) if message_in.command == SERVERSCMD: # Get server count. servercount = len(Bot.client.servers) # Return message. if servercount == 1: return message.Message( "I am a member of **{} server**!".format(servercount)) else: return message.Message( "I am a member of **{} servers**!".format(servercount)) if message_in.command == 'messages': # Get server. server = message_in.server # If the server is null, show error. if not server: return message.Message("This is not a server. :wink:") msg_count = Bot.messagesSinceStart msg_count_server = logging.message_count_get(server.id) msg = "I've witnessed *{} messages* since I started and *{} messages* overall!" return message.Message(msg.format(msg_count, msg_count_server)) if message_in.command == 'invite': class perm_admin: value = 8 return message.Message( body=discord.utils.oauth_url(Bot.client.user.id, perm_admin)) if message_in.command == NICKNAMECMD: if message_in.channel.permissions_for( message_in.author).manage_nicknames: # Change nickname. await Bot.client.change_nickname(message_in.server.me, message_in.body.strip()) # if message_in.server.me.nick: # return message.Message("My new nickname in this server is **{}**".format(message_in.server.me.nick)) #else: # return message.Message("My nickname has been removed.") return message.Message("My nickname has been changed.") else: return message.Message( "You cannot change nicknames on this server.") if message_in.command == 'ping': return message.Message(body='PONG! Bot is up!')
def test_ud_randefine(self): emptyList = [] msg = message.Message(body="") msg.command = "randefine" result = yield from urbandictionary.onCommand(msg) self.assertEqual(type(result), type(emptyList))
def test_ud_define_empty(self): msg = message.Message(body="") msg.command = "define" result = yield from urbandictionary.onCommand(msg) self.assertEqual(type(result), type(msg))
def test_fun_lenny_msg(self): msg = message.Message(body="hi") msg.command = "lenny" result = yield from fun.onCommand(msg) self.assertEqual(type(result), type(msg)) self.assertEqual(result.body, "( ͡° ͜ʖ ͡°)\nhi")
def test_comics_xkcd_with_id(self): msg = message.Message(body="303") msg.command = "xkcd" result = yield from comics.onCommand(msg) self.assertEqual(type(result), type(msg))
async def onCommand(message_in): # Define. if message_in.command == 'define': # Get the word to define. word = message_in.body.strip() # Check to see if word is empty. if not word: return message.Message('Usage: `{}define [word]`'.format( '!')) # TODO: prefix variable # Get definition. rword = word.replace(" ", "+") msg = 'I couldn\'t find a definition for "{}"...'.format(word) f = caching.json_get( "http://api.urbandictionary.com/v0/define?term={}".format(rword), caller='define', name_custom=rword) #try: # f = urllib.request.urlopen("http://api.urbandictionary.com/v0/define?term={}".format(rword)).read().decode("utf-8") #except urllib.error.URLError as e: # return message.Message(body='There was an issue connecting to UD'.format(message_in.body)) # Decode JSON and format definition. theJSON = json.loads(f)["list"] if len(theJSON): # Build the response. ourWord = theJSON[0] msg = '__**{}:**__\n\n{}'.format(string.capwords(ourWord["word"]), ourWord["definition"]) if ourWord["example"]: msg = '{}\n\n__Example(s):__\n\n*{}*'.format( msg, ourWord["example"]) # Return message. return message.msg_split(msg) # Random define. if message_in.command == 'randefine': # Get random definition. try: f = urllib.request.urlopen( "http://api.urbandictionary.com/v0/random").read().decode( "utf-8") except urllib.error.URLError as e: return message.Message(body='There was an issue connecting to UD'. format(message_in.body)) # Decode JSON and format definition. theJSON = json.loads(f)["list"] if len(theJSON): # Build the response. ourWord = theJSON[0] msg = '__**{}:**__\n\n{}'.format(string.capwords(ourWord["word"]), ourWord["definition"]) if ourWord["example"]: msg = '{}\n\n__Example(s):__\n\n*{}*'.format( msg, ourWord["example"]) # Return message. return message.msg_split(msg)
def test_fun_shrug_msg(self): msg = message.Message(body="hi") msg.command = "shrug" result = yield from fun.onCommand(msg) self.assertEqual(type(result), type(msg)) self.assertEqual(result.body, r"¯\_(ツ)_/¯\nhi")
def test_srcutils_tests(self): msg = message.Message(body="") msg.command = "tests" result = yield from srcutils.onCommand(msg) self.assertEqual(type(result), type(msg))
async def onCommand(message_in): # Initialize Database database.init() OffsetTable = Table('offsets', TableTypes.pGlobal) # Get user. if message_in.server: me = message_in.server.me else: me = message_in.channel.me if message_in.command == 'setoffset': # Normalize offset offsetstr = message_in.body.strip() if offsetstr == "": return message.Message( 'Incorrect Offset format. Has to be in +/-HH:MM!') if offsetstr[0] == '+': prefix = '+' else: prefix = '' try: hours, minutes = map(int, offsetstr.split(':')) except Exception: try: hours = int(offsetstr) minutes = 0 except Exception: return message.Message( 'Incorrect Offset format. Has to be in +/-HH:MM!') normalizedoffset = '{}{}:{}'.format(prefix, hours, minutes) # Set Offset in Database # Try to update Offset if it exists existingOffset = Table.search(OffsetTable, 'id', '{}'.format(message_in.author.id)) if existingOffset != None: existingOffset.edit( dict(id=message_in.author.id, offset=normalizedoffset)) else: # Create new entry Table.insert( OffsetTable, dict(id=message_in.author.id, offset=normalizedoffset)) # Get time right now # Return time along with offset timeutc = datetime.datetime.utcnow() # Apply offset if hours > 0: # Apply positive offset timedelta = datetime.timedelta(hours=hours, minutes=minutes) newTime = timeutc + timedelta elif hours < 0: # Apply negative offset timedelta = datetime.timedelta(hours=(-1 * hours), minutes=(-1 * minutes)) newTime = timeutc - timedelta else: # No offset newTime = timeutc return message.Message( 'Your UTC offset has been set to *{}*, for which the time is {}.'. format(normalizedoffset, newTime.strftime("%I:%M %p"))) if message_in.command == 'time': memberOrOffset = message_in.body.strip() # Check whose time we need (or if we got an offset) if not memberOrOffset: member = message_in.author else: # Try to get a user first member = displayname.memberForName(memberOrOffset, message_in.server, me) if member: existingOffset = Table.search(OffsetTable, 'id', '{}'.format(member.id)) # Check if entry exists try: offset = existingOffset.data[1] except Exception: return message.Message( '*{}* didn\'t set an offset. Set an offset with `!setoffset (offset)`.' .format(displayname.name(member))) else: # Assume input is offset offset = memberOrOffset offset = offset.replace('+', '') # Split time string by : and get hour/minute values try: hours, minutes = map(int, offset.split(':')) except Exception: try: hours = int(offset) minutes = 0 except Exception: return message.Message( 'Invalid offset format. Has to be in +/-HH:MM!') # Get time right now timeutc = datetime.datetime.utcnow() # Apply offset if hours > 0: # Apply positive offset offsetmsg = 'UTC+{}'.format(offset) timedelta = datetime.timedelta(hours=hours, minutes=minutes) newTime = timeutc + timedelta elif hours < 0: # Apply negative offset offsetmsg = 'UTC{}'.format(offset) timedelta = datetime.timedelta(hours=(-1 * hours), minutes=(-1 * minutes)) newTime = timeutc - timedelta else: # No offset newTime = t if member: msg = '{}; where *{}* is, it\'s currently *{}*'.format( offsetmsg, displayname.name(member), newTime.strftime("%I:%M %p")) else: msg = '{} is currently *{}*'.format(offsetmsg, newTime.strftime("%I:%M %p")) # Say message return message.Message(msg)
def test_botutils_cpuinfo(self): msg = message.Message(body="") msg.command = "cpuinfo" result = yield from botutils.onCommand(msg) self.assertEqual(type(result), type(msg))