async def define_cmd(self, message): # First remove the "define" command new_cmd = utils.remove_command(message.content) # Then parse the new command cmd = utils.get_command(new_cmd) response = utils.remove_command(new_cmd) if response == "": # Don't allow blank responses return "...You didn't specify what that command should do." elif cmd in self.keywords: # Don't allow users to set commands with protected keywords return "`{}` is already in use as a built-in function. Please choose another name.".format( cmd) # Set new command in cache and database self.cmd_dict[cmd] = response db.set_new_custom_cmd(cmd, response) # Format confirmation to the user output_message = "New command added! You can use it like `{}{}`. ".format( CMD_PREFIX, cmd) # If user allows embedding of a ping, list various ways this can be done if "%mention%" in response: author = message.author user_id = author.id user_name = "{}#{}".format(author.name, author.discriminator) output_message += "You can also use it as `{prefix}{cmd} {id}`, `{prefix}{cmd} {name}`, or `{prefix}{cmd} @{name}`".format( prefix=CMD_PREFIX, cmd=cmd, id=user_id, name=user_name) return output_message
async def edit(message): try: payload = utils.remove_command(message.content) edit_id = utils.get_command(payload) edit_message = None for channel in message.guild.channels: try: if type(channel) == discord.TextChannel: edit_message = await channel.fetch_message(int(edit_id)) break except discord.errors.HTTPException as e: if e.code == 10008: pass if edit_message == None: return "I was unable to find a message with that ID." m = utils.remove_command(payload) if m == "": return "You cannot replace a message with nothing." await edit_message.edit(content=m) return "Message edited." except (IndexError, ValueError): return "I was unable to find a message ID in that message. `{prefix}edit MES_ID message`".format( prefix=CMD_PREFIX) except discord.errors.HTTPException as e: if e.code == 50005: return "You cannot edit a message from another user." else: return "Oh god something went wrong, everyone panic! {}".format( str(e))
async def say(message): try: payload = utils.remove_command(message.content) channel_id = utils.get_command(payload) channel = discord.utils.get(message.guild.channels, id=int(channel_id)) m = utils.remove_command(payload) if m == "" and len(message.attachments) == 0: return "You cannot send empty messages." for item in message.attachments: f = await item.to_file() await channel.send(file=f) if m != "": await channel.send(m) return "Message sent." except (IndexError, ValueError): return "I was unable to find a channel ID in that message. `{prefix}say CHAN_ID message`".format( prefix=CMD_PREFIX) except AttributeError: return "Are you sure that was a channel ID?" except discord.errors.HTTPException as e: if e.code == 50013: return "You do not have permissions to post in that channel." else: return "Oh god something went wrong, everyone panic! {}".format( str(e))
async def join(self, ctx): if ctx.message.author.id in MASTERS: channame = remove_command(ctx.message.content) for channel in ctx.message.server.channels: if channel.type == discord.ChannelType.voice and channel.name == channame.strip(): self.voice = await self.bot.join_voice_channel(channel) else: await self.bot.say('You are not my master, {}'.format(ctx.message.author))
async def geolocate(self, ctx): if ctx.message.author.id in MASTERS: ipaddr = remove_command(ctx.message.content) result = subprocess.Popen(['curl', 'freegeoip.net/xml/{}'.format(ipaddr)], stdout=subprocess.PIPE) output = (result.communicate()[0]).decode('utf-8') await self.bot.say(output) else: await self.bot.say('You are not my master, {}'.format(ctx.message.author))
async def dice(self, ctx): if ctx.message.author.id in MASTERS: sides = remove_command(ctx.message.content) try: side = str(random.randrange(1, int(sides) + 1)) except ValueError: side = str(random.randrange(1, 7)) await self.bot.say(side) else: await self.bot.say('You are not my master, {}'.format(ctx.message.author))
async def scan(self, ctx): if ctx.message.author.id in MASTERS: options = remove_command(ctx.message.content) comm = ['nmap'] comm.extend(options.split(' ')) result = subprocess.Popen(comm, stdout=subprocess.PIPE) output = (result.communicate()[0]).decode('utf-8') await self.bot.say(output) else: await self.bot.say('You are not my master, {}'.format(ctx.message.author))
async def play(self, ctx): if ctx.message.author.id in MASTERS: url = remove_command(ctx.message.content) if not self.bot.is_voice_connected(ctx.message.server): await self.bot.say('Must be connected to voice channel') return self.player = await self.voice.create_ytdl_player(url, use_avconv=False) await self.bot.change_presence(game=discord.Game(name='Playing '+self.player.title)) self.player.start() await self.bot.say('Playing {}'.format(self.player.title)) else: await self.bot.say('You are not my master, {}'.format(ctx.message.author))
async def remove_cmd(self, message): # First remove the "define" command new_cmd = utils.remove_command(message.content) # Then parse the command to remove cmd = utils.get_command(new_cmd) # If this command did exists, remove it from cache and database if self.command_available(cmd): del self.cmd_dict[cmd] db.remove_custom_cmd(cmd) return "`{}` removed as a custom command!".format(cmd)
async def ban(self, ctx): if ctx.message.author.id in MASTERS: victim = remove_command(ctx.message.content) try: for member in ctx.message.server.members: if member.name == victim.strip(): await self.bot.ban(member) else: await self.bot.say('Could not find {}'.format(victim)) except discord.Forbidden: await self.bot.say('Do not have proper permissions for that action') else: await self.bot.say('You are not my master, {}'.format(ctx.message.author))
async def add_points(message): mes = utils.remove_command(message.content).split(" ") team = [t for t in TEAMS if t['nick'].upper() == mes[0].upper()] if team: try: found_team = team[0] add_pts = int(mes[1]) db.add_points(found_team['id'], add_pts) return f"{add_pts} points have been added to {found_team['name']}" except (ValueError, IndexError): return "You did not specify how many points to add" else: return "I could not find a team name in that message"
async def add_game(message): game = utils.remove_command(message.content).strip() if len(game) == 0: return "Can't add game: no message provided." games = db.get_games() time_info = get_next_announcement_info() if game in games: return f"That game (and {len(games) - 1} other(s)) is already going to be announced at {time_info}." db.add_game(game) return f"Game added! {len(games) + 1} game(s) will be announced at {time_info}."
def check_id(message): content = remove_command(message.content) try: # If ping is typed out by user using their ID, it doesn't count as a mention # Thus, try and match with regex checkPing = re.search(r"<@!?(\d+)>", content) if checkPing != None: return int(checkPing.group(1)) # Simply verify by attempting to cast to an int. If it doesn't raise an error, return it checkID = content.split()[0] return int(checkID) except (IndexError, ValueError): return None
async def add_xp(self, message): try: payload = utils.remove_command(message.content) # Treat last word as XP to be awarded xp = int(payload.split(" ")[-1]) userid = parse_mention(message) # Incase they didn't give an XP, don't parse ID as XP lol if xp == userid: return "Was unable to find XP value in that message" user = discord.utils.get(message.guild.members, id=userid) if user != None: await self.give_xp(user, xp) return f"{xp} XP given to {user.name}#{user.discriminator}" else: return "Was unable to find that user in the server" except (IndexError, ValueError): return f"`{CMD_PREFIX}addxp XP USER`"
async def askvoice(self, ctx): #if ctx.message.author.id in MASTERS: if not self.bot.is_voice_connected(ctx.message.server): await self.bot.say('Must be connected to voice channel') return question = remove_command(ctx.message.content) answer = cb.query(question) tts = gTTS(text=answer, lang='en-au', slow=False) tts.save(MULTIM_PATH + 'temp.mp3') ttsholder = open(MULTIM_PATH + 'temp.mp3') self.player = self.voice.create_ffmpeg_player(ttsholder.name, use_avconv=False) self.player.start() while self.player.is_playing(): sleep(1) self.player.stop() remove(MULTIM_PATH + 'temp.mp3') ttsholder.close()
async def echovoice(self, ctx): if ctx.message.author.id in MASTERS: if not self.bot.is_voice_connected(ctx.message.server): await self.bot.say('Must be connected to voice channel') return echotext = remove_command(ctx.message.content) tts = gTTS(text=echotext, lang='en-au', slow=False) tts.save(MULTIM_PATH + 'tempecho.mp3') ttsholder = open(MULTIM_PATH + 'tempecho.mp3') self.player = self.voice.create_ffmpeg_player(ttsholder.name, use_avconv=False) self.player.start() while self.player.is_playing(): sleep(1) self.player.stop() remove(MULTIM_PATH + 'tempecho.mp3') ttsholder.close() else: await self.bot.say('You are not my master, {}'.format(ctx.message.author))
def check_username(message): # Usernames can have spaces, so need to throw away the first word (the command), # and then everything after the discriminator testUsername = remove_command(message.content) try: # Some people *coughs* like to put a '@' at beginning of the username. # Remove the '@' if it exists at the front of the message if testUsername[0] == "@": testUsername = testUsername[1:] # Parse out the actual username user = testUsername.split("#") discriminator = user[1].split()[0] userFound = discord.utils.get(message.guild.members, name=user[0], discriminator=discriminator) if userFound != None: return userFound.id except IndexError: return None
async def ask(self, ctx): question = remove_command(ctx.message.content) answer = cb.query(question) await self.bot.say(answer)
async def echo(self, ctx): if ctx.message.author.id in MASTERS: await self.bot.say(remove_command(ctx.message.content)) else: await self.bot.say('You are not my master, {}'.format(ctx.message.author))
async def urbandict(self, ctx): searchtext = remove_command(ctx.message.content) results = urbandict.define(searchtext) await self.bot.say('{}\nExample: {}'.format(results[0]['def'], results[0]['example']))
async def wiki(self, ctx): searchtext = remove_command(ctx.message.content) results = wiki.find(searchtext) article = wiki.get_article(results[0]) await self.bot.say('Wikipedia results:\n\n\n*{}*\n\n{}\n\n{}'.format(article.heading, article.summary, article.image))