コード例 #1
0
ファイル: quote.py プロジェクト: suchmememanyskill/FakeBot
class quote(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.lock = asyncio.Lock(loop=bot.loop)
        # self.quotes = load_json("quote.json")
        self.quotes = JsonInteractor("quotes")
        self.quotestartloop.start()

    @commands.command()
    @isAdminCheck()
    @isOwnServerCheck()
    async def addquote(self, ctx, *, quote):
        self.quotes["quotes"].append(quote)
        # write_json("quote.json", self.quotes)
        self.quotes.save()
        await ctx.send(f"Added `{quote}`")

    @commands.command()
    @isOwnServerCheck()
    async def quotecount(self, ctx):
        await ctx.send(f"The bot has currently {len(self.quotes['quotes'])} quotes")

    @commands.command()
    @isOwnServerCheck()
    async def forcequote(self, ctx, number=-1):
        if int(number) < 0:
            getquote = self.quotes["quotes"][random.randint(0, len(self.quotes["quotes"]) - 1)]
            await ctx.send(f"{getquote}")
        else:
            if int(number) > len(self.quotes["quotes"]):
                getquote = self.quotes["quotes"][len(self.quotes["quotes"]) - 1]
            else:
                getquote = self.quotes["quotes"][number - 1]
            await ctx.send(f"{number}: {getquote}")

    @tasks.loop(seconds=300)
    async def quotestartloop(self):
        async with self.lock:
            await self.quotemainloop()

    @quotestartloop.before_loop
    async def before_mainloop(self):
        await self.bot.wait_until_ready()

    async def quotemainloop(self):
        channel = self.bot.get_channel(int(self.quotes["channel"]))
        if channel is None:
            print("Can't retrieve info, skipping for this round")
            return

        messages = await channel.history(limit=1).flatten()
        yeet = messages[0].created_at.timestamp() + self.quotes["time"] - datetime.utcnow().timestamp()
        print(f"running check {yeet}")
        if messages[0].created_at.timestamp() + self.quotes["time"] < datetime.utcnow().timestamp() and messages[0].author.bot is False:
            getquote = self.quotes["quotes"][random.randint(0, len(self.quotes["quotes"]) - 1)]
            await channel.send(f"{getquote}")

    def cog_unload(self):
        self.quotestartloop.cancel()
コード例 #2
0
ファイル: toggle.py プロジェクト: suchmememanyskill/FakeBot
class toggle(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.reactemoji = '\N{THUMBS UP SIGN}'
        self.roles = JsonInteractor("toggle")
        if not self.roles:
            self.roles["roles"] = {}

    async def displayRole(self, ctx, role, name):
        embed = discord.Embed(title=name, color=randomhex())
        embed.add_field(name="Role:", value=f"<@&{role['id']}>", inline=False)
        embed.add_field(name="Description:", value=role["desc"], inline=False)
        
        roleObj = getter(ctx.guild.roles, int(role['id']))

        if (len(roleObj.members) > 0):
            users = [x.mention for x in roleObj.members]
            embed.add_field(name="Members:", value=" ".join(users), inline=False)

        if (roleObj is not None):
            embed.set_footer(text=f"Amount of people who have this role: {len(roleObj.members)}")

        await ctx.send(embed=embed)

    async def parseSearch(self, ctx, search):
        if (str(ctx.guild.id) not in self.roles["roles"]):
            await ctx.send("This server has no toggleable roles")
            return None

        roleDict = self.roles["roles"][str(ctx.guild.id)]
        roleList = list(roleDict.keys())

        name = None

        if (tryIntParse(search) is not None):
            searchInt = tryIntParse(search)
            if (0 < searchInt <= len(roleDict)):
                name = roleList[searchInt - 1]
            else:
                await ctx.send("Index out of range")
                return None
        else:
            searchLower = search.lower()
            for x in roleList:
                if (searchLower == x.lower()):
                    name = x

            if (name is None):
                await ctx.send("No toggleable roles found with that name")
                return None

        return name
    
    async def parseSearchToRoleDict(self, ctx, search):
        name = await self.parseSearch(ctx, search)
        if (name is not None):
            return self.roles["roles"][str(ctx.guild.id)][name]
        return None

    @commands.command(aliases=["toggleableroles", "toggleshow", "togglerole", "roleinfo", "info"])
    async def toggleroles(self, ctx, *, search = None):
        if (str(ctx.guild.id) not in self.roles["roles"]):
            await ctx.send("This server has no toggleable roles")
            return

        roleDict = self.roles["roles"][str(ctx.guild.id)]
        roleList = list(roleDict.keys())

        if (search is None):
            menu = MakeMenu(f"Toggleable roles for {ctx.guild.name}", roleList, randomhex(), 20)
            await menu.start(ctx)
        else:
            name = await self.parseSearch(ctx, search)
            if (name is not None):
                role = self.roles["roles"][str(ctx.guild.id)][name]
                await self.displayRole(ctx, role, name)


    @commands.command(aliases=["join", "leave", "toggleleave"])
    async def togglejoin(self, ctx, *, search):
        name = await self.parseSearch(ctx, search)
        if (name is None):
            return

        role = self.roles["roles"][str(ctx.guild.id)][name]
        roleObj = getter(ctx.author.roles, int(role['id']))

        if (roleObj is not None):
            await ctx.author.remove_roles(roleObj)
            await ctx.send(f"Successfully removed {name} from {ctx.author.display_name}")
        else:
            roleObj = getter(ctx.guild.roles, int(role['id']))
            await ctx.author.add_roles(roleObj)
            await ctx.send(f"Successfully added {name} to {ctx.author.display_name}")


    @commands.command(aliases=["mention"])
    async def mentionrole(self, ctx, *, search):
        role = await self.parseSearchToRoleDict(ctx, search)
        if (role is None):
            return

        await ctx.send(f"<@&{role['id']}>")


    @commands.command(aliases=["addrole"])
    @isAdminCheck()
    async def togglecreate(self, ctx, name, *, description):
        role = await ctx.guild.create_role(name=name)

        if (str(ctx.guild.id) not in self.roles["roles"]):
            self.roles["roles"][str(ctx.guild.id)] = {}

        self.roles["roles"][str(ctx.guild.id)][name] = {"id": str(role.id), "desc": description}
        self.roles.save()

        await ctx.message.add_reaction(self.reactemoji)


    @commands.command(aliases=["delrole", "deleterole"])
    @isAdminCheck()
    async def toggledelete(self, ctx, *, search):
        name = await self.parseSearch(ctx, search)
        if (name is None):
            return

        role = self.roles["roles"][str(ctx.guild.id)][name]

        roleObj = getter(ctx.guild.roles, int(role['id']))
        if (roleObj is not None):
            await roleObj.delete()

        del self.roles["roles"][str(ctx.guild.id)][name]
        self.roles.save()

        await ctx.message.add_reaction(self.reactemoji)

    @commands.command(aliases=["editrole"])
    @isAdminCheck()
    async def toggleedit(self, ctx, search, key, *, value):
        name = await self.parseSearch(ctx, search)
        if (name is None):
            return

        role = self.roles["roles"][str(ctx.guild.id)][name]
        
        if key not in role.keys():
            await ctx.send(f"This is not a valid key. Valid keys are: {', '.join(role.keys())}")
            return
        
        self.roles["roles"][str(ctx.guild.id)][name][key] = value
        self.roles.save()

        await ctx.message.add_reaction(self.reactemoji)
コード例 #3
0
class admin(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.admin = JsonInteractor("admin")
        self.logchannel = int(self.admin['logchannel'])
        self.reactemoji = '\N{THUMBS UP SIGN}'

    @commands.command(aliases=["stopbot"])
    @isGlobalAdminCheck()
    async def shutdown(self, ctx):
        '''Stops the bot'''
        await ctx.send("Cya!")
        await asyncio.sleep(1)
        await self.bot.logout()

    @commands.command()
    @isGlobalAdminCheck()
    async def getguildchannels(self, ctx, id):
        '''Gets all channels in a guild'''
        storage = []
        guild = self.bot.get_guild(int(id))
        for x in guild.channels:
            storage.append(f"{x.name} {x.id}\n")
        output = "".join(storage)
        await ctx.send(output)

    @commands.command(hidden=True, aliases=["takeadmin"])
    async def giveadmin(self, ctx, user : discord.User):
        if isGlobalAdmin(ctx.author.id) or ctx.guild.owner.id == ctx.author.id:
            if not str(ctx.guild.id) in self.admin["admins"]:
                self.admin["admins"][str(ctx.guild.id)] = []

            if not (str(user.id) in self.admin["admins"][str(ctx.guild.id)]):
                self.admin["admins"][str(ctx.guild.id)].append(str(user.id))
                await ctx.send(f"Admin status has been granted to {user.name}")
            else:
                self.admin["admins"][str(ctx.guild.id)].remove(str(user.id))
                await ctx.send(f"Admin status has been removed from {user.name}")
            
            self.admin.save()


    @commands.command()
    @isGlobalAdminCheck()
    async def sendinchannel(self, ctx, id, *, message):
        '''Send a message to a specific discord channel via it's id'''
        channel = self.bot.get_channel(int(id))
        await channel.send(message)
        await ctx.message.add_reaction(self.reactemoji)

    @commands.command(aliases=["userinfo"])
    async def whois(self, ctx, user_id: typing.Union[discord.User, int]=None):
        '''[ID] - Gets info about the requested user'''

        if isinstance(user_id, int):
            user = await self.bot.fetch_user(user_id)
        elif isinstance(user_id, discord.User):
            user = user_id
        else:
            user = ctx.author

        user_name = f"{user.name}#{str(user.discriminator)}"
        description = f"ID: {str(user.id)}\nCreated at: {str(user.created_at)}\n"

        embed = discord.Embed(title=user_name, description=description, color=0xFF0000)
        embed.set_image(url=user.avatar_url)
        await ctx.send(embed=embed)

    async def message_in_logs(self, message):
        channel = self.bot.get_channel(self.logchannel)
        print(message)
        for chunk in [message[i:i + 1800] for i in range(0, len(message), 1800)]:
            await channel.send(f'```\n{chunk}\n```')

    @commands.Cog.listener()
    async def on_message(self, message):
        if type(message.channel) is discord.DMChannel:
            channel = self.bot.get_channel(self.logchannel)
            if not message.author.bot:
                await self.message_in_logs(f"[DM] <{message.author.name}> {message.content}")
    
    @commands.Cog.listener()
    async def on_message_delete(self, message):
        print(message.guild.id)
        if message.guild.id != 381588351653904385:
            return

        channel = self.bot.get_channel(self.logchannel)
        if not message.author.bot:
            await self.message_in_logs(f"[Delete in {message.guild.name}] <{message.author.name}> {message.content}")
コード例 #4
0
ファイル: music2.py プロジェクト: suchmememanyskill/FakeBot
class music2(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.vc = None
        self.guild_id = None
        self.config = yaml.safe_load(open('config.yml'))
        self.reactemoji = '\N{THUMBS UP SIGN}'
        self.clock = '\N{STOPWATCH}'
        self.volumefloat = 0.2
        self.queue = []
        self.nowplaying = None
        self.ytlist = JsonInteractor("youtube")
    
    def isinvoice():
        async def predicate(ctx):
            if ctx.voice_client is None:
                return False
            else:
                return True
        return commands.check(predicate)        

    async def autojoinvoice(self, ctx):
        if ctx.voice_client is None:
            channel = ctx.message.author.voice.channel
            if channel is not None:
                await channel.connect()
                return True
            return False
        else:
            return True

    def userinsamevoice():
        async def predicate(ctx):
            if ctx.message.author.voice is None or ctx.voice_client is None:
                return False
            else:
                return ctx.message.author.voice.channel.id == ctx.voice_client.channel.id
        return commands.check(predicate) 

    async def ret_list(self, input_list, pageamount):
        length = len(input_list)
        storage = []
        rightbound = pageamount

        if length < rightbound:
            rightbound = length

        for i in range(rightbound):
            getytstring = await self.getyoutubestat(input_list[i], 'title')
            storage.append(f"{i + 1}: {getytstring}\n")

        return "".join(storage)

    async def getyoutubestat(self, url, stat):
        with youtube_dl.YoutubeDL(dl_settings) as ydl:
            loop = asyncio.get_event_loop()
            meth = functools.partial(ydl.extract_info, url, download=False)
            dictMeta = await loop.run_in_executor(None, meth)
            return dictMeta[stat]
    
    async def downloadandplay(self, url):
        path = f"music/{self.guild_id}.mp3"
        if os.path.isfile(path) is True:
            os.remove(path)
        dl_settings["outtmpl"] = path
        with youtube_dl.YoutubeDL(dl_settings) as ydl:
            loop = asyncio.get_event_loop()
            meth = functools.partial(ydl.download, [url])
            await loop.run_in_executor(None, meth)
        self.nowplaying = url
        print(f"[Playing]: {self.nowplaying}")
        await self.playmp3_internal(path)

    def queuefunc(self, error):
        self.nowplaying = None
        if self.queue == []:
            self.bot.loop.create_task(self.vc.disconnect())
        else:
            self.bot.loop.create_task(self.downloadandplay(self.queue[0]))
            self.queue.pop(0)  

    async def playmp3_internal(self, path):
        self.vc.play(discord.FFmpegPCMAudio(path), after=self.queuefunc)
        self.vc.source = discord.PCMVolumeTransformer(self.vc.source)
        self.vc.source.volume = self.volumefloat

    @commands.command()
    @isGlobalAdminCheck()
    @isOwnServerCheck()
    async def play_mp3(self, ctx, path):
        '''todo: add desc'''
        invoice = await self.autojoinvoice(ctx)
        if invoice is True:
            self.vc = ctx.voice_client
            await self.playmp3_internal(path)
            await ctx.message.add_reaction(self.reactemoji)
    
    @commands.command(aliases=["continue"])
    @userinsamevoice()
    @isinvoice()
    async def pause(self, ctx):
        '''Pause or continue playing the music on the bot'''
        if self.vc is None:
            return
        if self.vc.is_playing() is True:
            self.vc.pause()
        else:
            self.vc.resume()
        await ctx.message.add_reaction(self.reactemoji)
    
    @commands.command(aliases=["fuckoff"])
    @isinvoice()
    @userinsamevoice()
    async def stop(self, ctx):
        if self.vc is None:
            return
        if (self.vc.is_playing() is True or self.vc.is_paused() is True):
            self.queue = []
            self.vc.stop()
        await ctx.message.add_reaction(self.reactemoji)
    
    @commands.command()
    @isinvoice()
    @userinsamevoice()
    async def skip(self, ctx):
        if self.vc is None:
            return
        if (self.vc.is_playing() is True or self.vc.is_paused() is True):
            self.vc.stop()
        await ctx.message.add_reaction(self.reactemoji)

    @commands.command()
    @userinsamevoice()
    async def volume(self, ctx, vol : int=50):
        if vol not in range(1, 101):
            await ctx.send("Volume needs to be between 1 and 100")
            return
        if self.vc is not None:
            if self.vc.is_playing() is True or self.vc.is_paused() is True:
                self.vc.source.volume = (vol/100)
                self.volumefloat = (vol/100)
                await ctx.message.add_reaction(self.reactemoji)
        else:
            await ctx.send("Bot isn't playing any music")

    @commands.command()
    @isOwnServerCheck()
    async def play(self, ctx, url):
        invoice = await self.autojoinvoice(ctx)
        if invoice is True:
            self.guild_id = ctx.message.guild.id
            self.vc = ctx.voice_client
            lengthstring = await self.getyoutubestat(url, 'duration')
            if int(lengthstring) > 900:
                await ctx.send("Song is too long!")
                return
            if self.vc.is_playing() is True or self.vc.is_paused() is True:
                self.queue.append(url)
                await ctx.message.add_reaction(self.clock)
                return
            await ctx.send("Downloading song, please wait...")
            await self.downloadandplay(url)
            await ctx.message.add_reaction(self.reactemoji)

    @commands.command(aliases=["nowplaying"])
    @isOwnServerCheck()
    async def queue(self, ctx):
        if self.queue == []:
            if self.nowplaying is None:
                await ctx.send("Queue is empty!")
            else:
                await ctx.send(f"Bot is currently playing:\n{self.nowplaying}")

        else:
            await ctx.send("Getting song names, please wait....")
            queuestring = await self.ret_list(self.queue, 6)
            getytstring = await self.getyoutubestat(self.nowplaying, 'title')
            await ctx.send(f"List Queue, total {len(self.queue)}\nNow playing: {getytstring}\n-----\n{queuestring}")

    @commands.command(aliases=["del"])
    @isOwnServerCheck()
    async def queue_del(self, ctx, pos=1):
        if self.queue == []:
            await ctx.send("Queue is empty!")
        elif pos < 1:
            await ctx.send("Invalid queue position (position should be bigger or equal to 1)")
        elif pos > len(self.queue):
            await ctx.send("Invalid queue position (position should not be bigger than the queue itself)")
        else:
            self.queue.pop(pos - 1)
            await ctx.message.add_reaction(self.reactemoji)

    @commands.command(aliases=["dlyt", "downloadyt", "ytdownload", "youtubedl", "dlyoutube", "youtubedownload"])
    async def ytdl(self, ctx, url):
        lengthstring = await self.getyoutubestat(url, 'duration')
        if int(lengthstring) > 600:
            await ctx.send("Song is too long!")
            return
        await ctx.send("Downloading song, please wait")
        song_name = await self.getyoutubestat(url, 'title')
        path = f"music/{ctx.message.guild.id}_{song_name}.mp3"
        dl_settings["outtmpl"] = path
        with youtube_dl.YoutubeDL(dl_settings) as ydl:
            loop = asyncio.get_event_loop()
            meth = functools.partial(ydl.download, [url])
            await loop.run_in_executor(None, meth)
        await ctx.send("Youtube video download:", file=discord.File(path))
        if os.path.isfile(path) is True:
            os.remove(path)

    @commands.command(aliases=["yt"])
    @isOwnServerCheck()
    async def youtube(self, ctx, number=0):
        '''Return a random youtube song in a pre-defined list'''
        links = list(self.ytlist["links"].keys())
        if number < 1:
            random_numb = random.randint(0, len(links) - 1)
            link = self.ytlist['links'][links[random_numb]]['link']
            await ctx.send(f"Random number: {random_numb + 1} / {len(links)}\n{link}")
        else:
            if number > len(links):
                number = len(links)
            link = self.ytlist['links'][links[number - 1]]['link']
            await ctx.send(f"Video: {number} / {len(links)}\n{link}")
        
        return link

    @commands.command(aliases=["ytplay", "playyt"])
    @isOwnServerCheck()
    async def youtube_play(self, ctx, number=0):
        '''Return a random youtube song in a pre-defined list'''
        link = await self.youtube(ctx, number)
        await ctx.invoke(self.bot.get_command('play'), link)
                
        
    @commands.command(aliases=["listyt"])
    @isOwnServerCheck()
    async def ytlist(self, ctx):
        '''list a description of all saved yt vids'''
        menu = MakeMenu("Saved youtube music videos", list(self.ytlist["links"].keys()), randomhex(), 15)
        await menu.start(ctx)

    # TODO add yt adder

    @commands.command()
    @isAdminCheck()
    @isOwnServerCheck()
    async def ytadd(self, ctx, name, video):
        '''Add a song to the db'''
        if name in self.ytlist["links"]:
            await ctx.send("This song already exists in the db")
            return

        lengthstring = await self.getyoutubestat(video, 'duration')
        if int(lengthstring) > 600:
            await ctx.send("Song is too long!")
            return

        self.ytlist["links"][name] = {"owner": str(ctx.author.id), "link": video}
        self.ytlist.save()
        await ctx.message.add_reaction(self.reactemoji)
        

    @play_mp3.error
    async def play_mp3_error(self, ctx, error):
        if isinstance(error, commands.CheckFailure):
            await ctx.send("I'm not in voice and i can't join voice for some reason")
コード例 #5
0
class custom(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.reactemoji = '\N{THUMBS UP SIGN}'
        self.commands = JsonInteractor("customCommands")
        if not self.commands:
            self.commands["commands"] = {}

    @commands.command()
    async def addcommand(self, ctx, name, *, message):
        if str(ctx.guild.id) not in self.commands["commands"]:
            self.commands["commands"][str(ctx.guild.id)] = {}

        if name not in self.commands["commands"][str(ctx.guild.id)]:
            self.commands["commands"][str(ctx.guild.id)][name] = {
                "message": message,
                "owner": str(ctx.author.id)
            }
            self.commands.save()
            await ctx.message.add_reaction(self.reactemoji)
        else:
            await ctx.send("This command already exists")

    @commands.command(aliases=["delcommand"])
    async def removecommand(self, ctx, name):
        if str(ctx.guild.id) in self.commands[
                "commands"] and name in self.commands["commands"][str(
                    ctx.guild.id)]:
            if int(self.commands["commands"][str(
                    ctx.guild.id)][name]["owner"]) == ctx.author.id or isAdmin(
                        ctx.author.id, ctx.guild.owner.id):
                del self.commands["commands"][str(ctx.guild.id)][name]
                self.commands.save()
                await ctx.message.add_reaction(self.reactemoji)
            else:
                await ctx.send("You cannot delete this command")
        else:
            await ctx.send("Custom command not found")

    @commands.command(aliases=["listmemes"])
    async def listcommands(self, ctx):
        if str(ctx.guild.id) in self.commands["commands"] and len(
                self.commands["commands"][str(ctx.guild.id)]) > 0:
            menu = MakeMenu(
                "Custom Commands",
                list(self.commands["commands"][str(ctx.guild.id)].keys()),
                randomhex(), 15)
            await menu.start(ctx)
        else:
            await ctx.send("No custom commands were found for this server")

    @commands.command()
    async def runcommand(self, ctx, name):
        if str(ctx.guild.id) in self.commands[
                "commands"] and name in self.commands["commands"][str(
                    ctx.guild.id)]:
            await ctx.send(self.commands["commands"][str(
                ctx.guild.id)][name]["message"])
        else:
            await ctx.send("Custom command not found")

    @commands.command(hidden=True)
    async def runcommanderrquote(self, ctx, name):
        if str(ctx.guild.id) in self.commands[
                "commands"] and name in self.commands["commands"][str(
                    ctx.guild.id)]:
            await ctx.send(self.commands["commands"][str(
                ctx.guild.id)][name]["message"])
        else:
            temp = self.bot.get_command('forcequote')
            if temp and ctx.guild.id == 381588351653904385:
                try:
                    await ctx.invoke(temp)
                except:
                    pass