Example #1
0
async def createDatabases(server_id=None):
    '''Creates the databases for all servers (if not already existent)'''
    try:
        async with await aiomysql.connect(
                host=global_vars.mysql_data['host'],
                port=global_vars.mysql_data['port'],
                user=global_vars.mysql_data['user'],
                password=global_vars.mysql_data['password'],
                autocommit=True,
                charset='utf8') as conn:
            async with await conn.cursor() as cur:
                if server_id != None:
                    try:
                        if len(server_id) > 0 and not "*" in server_id:
                            server_id = str(server_id).replace("'", "\'")
                            server_id = str(server_id).replace('"', '\"')
                            await cur.execute(
                                "CREATE DATABASE IF NOT EXISTS srv_" +
                                server_id + ";")
                    except:
                        logger.PrintException()
                else:
                    for server in global_vars.client.servers:
                        try:
                            if len(server.id) > 0 and not "*" in server.id:
                                server.id = str(server.id).replace("'", "\'")
                                server.id = str(server.id).replace('"', '\"')
                                await cur.execute(
                                    "CREATE DATABASE IF NOT EXISTS srv_" +
                                    server.id + ";")
                        except:
                            logger.PrintException()
    except:
        logger.PrintException()
Example #2
0
async def init(bot):
    try:
        if len(bot.args) < 1:
            await bot.sendMessage(
                'Which module should be reloaded? (Waiting 10 Seconds)')
            reply = await bot.client.wait_for_message(
                timeout=10.0, author=bot.message.author)
            if reply is not None:
                module = reply.content
            else:
                return False
        else:
            module = " ".join(bot.args)
        try:
            func = importlib.import_module(module)
            importlib.reload(func)
            await bot.sendMessage("Reloaded \"{}\"".format(module))
        except Exception as e:
            if "No module named '{}'".format(module) in str(e):
                await bot.sendMessage(
                    "Can't find a module named \"{}\"".format(module))
            else:
                logger.PrintException(bot.message)
                await bot.sendMessage(
                    "Can't reload \"{}\" due to a error.".format(module))

    except:
        logger.PrintException(bot.message)
Example #3
0
async def init(bot):
    chat=bot.message.channel
    user=str(bot.message.author.name)
    try:
        #await logger.print_to_file(str(type(bot.message.author)))
        if bot.message.channel.is_private:
            await botfunc.autoDelete(10, await bot.sendMessage( "This is a private chat."),bot.message)
            return False
        if await config.getConf(bot.message.server.id, "music_bot") == False:
            await botfunc.autoDelete(10, await bot.sendMessage( "Music bots are disabled on this server."),bot.message)
            return False
        if bot.message.author.voice_channel is None:
            await botfunc.autoDelete(10, await bot.sendMessage( "You have to be in a voice channel."),bot.message)
            return False
        if bot.message.attachments is not None and len(bot.message.attachments)==1:
            if bot.message.attachments[0] is not None:
                bot.args = []
                bot.args.append(bot.message.attachments[0]['url'])
                if not bot.args[0].endswith(".mp3") and not bot.args[0].endswith(".wav"):
                    await botfunc.autoDelete(10, await bot.sendMessage( "The attachment has to be an MP3 file!"),bot.message)
                    return False
        if len(bot.args)==0:
            await botfunc.autoDelete(10, await bot.sendMessage( "You have to enter a link or attach a file."),bot.message)
            return False
        server_id = bot.message.server.id
        if not server_id in global_vars.music_bots or not await global_vars.music_bots[server_id].is_playing():
            await botfunc.autoDelete(10,bot.message) # Auto-Delete
            if not server_id in global_vars.music_bots or not await global_vars.music_bots.get(server_id).is_connected():
                global_vars.music_bots[server_id] = MusicPlayer(bot)
                try:
                    await global_vars.music_bots[server_id].connect()
                except:
                    await global_vars.music_bots[server_id].disconnect()
                    return False
                    logger.PrintException(bot.message)

            if "http://" in bot.args or "https://" in bot.args:
                url = "%20".join(bot.args)
            else:
                url = " ".join(bot.args)
            await global_vars.music_bots[server_id].play(Music(bot.message.author, "ytdl", url))
        else:
            try:
                func = importlib.import_module('commands.queue')
                importlib.reload(func)
                await func.init(bot)
            except Exception as e:
                if "No module named" in str(e):
                    return False
                logger.PrintException(bot.message)
                return
    except:
        logger.PrintException(bot.message)
Example #4
0
async def delete(time, messages):
    try:
        await asyncio.sleep(time)
        for message in messages:
            try:
                await global_vars.client.delete_message(message)
            except discord.NotFound:
                pass
            except discord.Forbidden:
                print("I'm not allowed to delete message.")
            except:
                logger.PrintException(message)
    except:
        logger.PrintException()
Example #5
0
async def init(bot):
    chat = bot.message.channel
    #user=str(bot.message.author.name)
    try:
        if len(bot.args) > 0:
            if len(bot.message.raw_mentions) > 0:
                user = await search.user(chat, bot.message.raw_mentions[0])
            else:
                user = "******".join(bot.args)
                if user.startswith("@"):
                    user = user[1:]
                user = await search.user(chat, user)
            if user is None:
                uid = ''.join(bot.args)
                if re.match("\d+", uid):
                    user = discord.Object(id=uid)
                    user.server = bot.message.server
                else:
                    await bot.sendMessage(
                        ":x: {} is not a valid User or ID".format(uid))
            try:
                if user is not None:
                    for admin in global_vars.botadmins:
                        if str(admin[0]) == str(user.id):
                            await bot.sendMessage(
                                ":x: No.... just no!".format(user))
                            return
                    await bot.client.ban(user, delete_message_days=1)
                    #if not hasattr(user, 'display_name'):
                    await bot.sendMessage(
                        ":white_check_mark:  Banned <@{0.id}> (**ID:** {0.id})"
                        .format(user))

            except discord.Forbidden:
                await bot.sendMessage(
                    ':x: The bot does not have permissions to ban members or this user got higher rank than the bot.'
                )
            except discord.NotFound:
                await bot.sendMessage(
                    ':x: This user doesn\'t exist or (s)he deleted this account.'
                )
            except:
                logger.PrintException(bot.message)
        else:
            await bot.sendMessage("I can't ban nothing.")
    except Exception:
        logger.PrintException(bot.message)
        return False
Example #6
0
async def init(bot):
    if not bot.message.channel.is_private:
        prefix = await config.getConf(bot.message.server.id, "prefix")
    else:
        prefix = "!"
    try:
        if len(bot.args) > 0:
            command = " ".join(bot.args)
            wl = False
            if not bot.channel.is_private:
                needed_level = await groups.needed_level(
                    bot.message.server.id, command)
                if needed_level > 0:
                    if bot.access_level < needed_level:
                        await bot.sendMessage("You can't use this command!")
                        return
            else:
                await bot.sendMessage("You can't use this command!")
                return
            cmd_class = 'commands.' + command
            try:
                func = importlib.import_module(cmd_class)
            except ImportError:
                return False
            if func.USAGE is not None:
                msg = "**Access Level:** `{}`\n**Usage:** `{}{}`\n**Description:** `{}`".format(
                    needed_level, prefix, func.USAGE, func.DESC)
                await bot.sendMessage(msg)
        else:
            await bot.sendMessage("`Usage:` {}how [command]".format(prefix))
    except:
        logger.PrintException(bot.message)
        return None
Example #7
0
async def get(server_id, cmd):
    try:
        async with await aiomysql.connect(
                host=global_vars.mysql_data['host'],
                port=global_vars.mysql_data['port'],
                user=global_vars.mysql_data['user'],
                password=global_vars.mysql_data['password'],
                db="srv_" + server_id,
                charset='utf8') as con:
            async with await con.cursor() as cur:
                await cur.execute(
                    "CREATE TABLE IF NOT EXISTS disabledCmds (cmd VARCHAR(100) NOT NULL, PRIMARY KEY (cmd));"
                )
                await con.commit()
                await cur.execute(
                    "SELECT cmd FROM disabledCmds WHERE LOWER(cmd)=LOWER(%s);",
                    (str(cmd), ))
                data = await cur.fetchone()
                if data != None:
                    return True
                else:
                    return False
    except:
        logger.PrintException()
    return None
Example #8
0
async def init(bot):
    chat = bot.message.channel
    user = str(bot.message.author.name)
    try:
        answer = [
            "Signs point to yes.", "Yes.", "Reply hazy, try again.",
            "Without a doubt.", "My sources say no.", "As I see it, yes.",
            "You may rely on it.", "Concentrate and ask again.",
            "Outlook not so good.", "It is decidedly so.",
            "Better not tell you now.", "Very doubtful.", "Yes - definitely.",
            "It is certain.", "Cannot predict now.", "Most likely.",
            "Ask again later.", "My reply is no.", "Outlook good.",
            "Don\'t count on it."
        ]
        if len(bot.args) > 0:
            await bot.sendMessage("{}".format(random.choice(answer)))
        else:
            await bot.sendMessage(
                'What do you want to ask? (Waiting 10 Seconds)')
            reply = await bot.client.wait_for_message(
                timeout=10.0, author=bot.message.author)
            if reply is not None:
                await bot.sendMessage("{}".format(random.choice(answer)))
            else:
                return False
    except Exception:
        logger.PrintException(bot.message)
Example #9
0
async def init(bot):
    chat = bot.message.channel
    user = str(bot.message.author.name)
    try:
        user = bot.message.author
        if len(bot.args) > 0:
            if len(bot.message.raw_mentions) > 0:
                user = await search.user(chat, bot.message.raw_mentions[0])
            else:
                user = await search.user(chat, " ".join(bot.args))
            if user is not None:
                if user == bot.message.author:
                    await bot.sendMessage("Your access level is `{}`".format(
                        bot.access_level))
                else:
                    access_level = await groups.getLevel(
                        bot.message.server.id, user)
                    await bot.sendMessage("`{}'s` access level is `{}`".format(
                        user.display_name, access_level))
            else:
                await bot.sendMessage(
                    "Could not find any user like \"`{}`\"".format(" ".join(
                        bot.args)))
        else:
            level = await groups.getLevel(bot.message.server.id, user)
            if user == bot.message.author:
                await bot.sendMessage("Your access level is `{}`".format(
                    bot.access_level))
    except Exception:
        logger.PrintException(bot.message)
        return False
Example #10
0
async def defaultLevels(server_id=None):
    ''' Sets all the default access levels in all servers'''
    try:
        async with await aiomysql.connect(
                host=global_vars.mysql_data['host'],
                port=global_vars.mysql_data['port'],
                user=global_vars.mysql_data['user'],
                password=global_vars.mysql_data['password'],
                autocommit=True,
                charset='utf8') as con:
            async with await con.cursor(aiomysql.cursors.DictCursor) as cur:
                if server_id != None:
                    server_id = "srv_" + server_id
                    await cur.execute("USE " + server_id + ";")
                    await cur.execute(
                        "CREATE TABLE IF NOT EXISTS command_levels (command VARCHAR(100) NOT NULL, level SMALLINT, PRIMARY KEY (command));"
                    )
                    for val in global_vars.default_access:
                        await cur.execute(
                            "INSERT IGNORE INTO command_levels (`command`, `level`) VALUES (%s, %s);",
                            (val[0], val[1]))
                else:
                    for server in global_vars.client.servers:
                        server_id = "srv_" + server.id
                        await cur.execute("USE " + server_id + ";")
                        await cur.execute(
                            "CREATE TABLE IF NOT EXISTS command_levels (command VARCHAR(100) NOT NULL, level SMALLINT, PRIMARY KEY (command));"
                        )
                        for val in global_vars.default_access:
                            await cur.execute(
                                "INSERT IGNORE INTO command_levels (`command`, `level`) VALUES (%s, %s);",
                                (val[0], val[1]))
    except:
        logger.PrintException()
Example #11
0
async def init(bot):
    try:
        if len(bot.args) > 0:
            user = None
            if len(bot.message.raw_mentions) > 0:
                user = await search.user(bot.message.channel,
                                         bot.message.raw_mentions[0])
            else:
                user = await search.user(bot.message.channel, bot.args[0])
            bot.args.pop(0)
            if user is not None:
                try:
                    oldname = user.display_name
                    name = " ".join(bot.args)
                    print(name)
                    if name.casefold() == "none":
                        name = None
                    # Bot needs permissions for this!
                    await bot.client.change_nickname(user, name)
                    await bot.sendMessage(
                        ":white_check_mark: {} has been renamed to {}".format(
                            oldname, name))
                except discord.Forbidden:
                    await bot.sendMessage(
                        ":x: Sorry but I can't change {}'s name.".format(
                            oldname))
            else:
                await bot.sendMessage(":x: Can't find the specified user.")
    except:
        logger.PrintException(bot.message)
Example #12
0
async def init(bot):
    try:
        channels = 0
        members = 0
        for srv in bot.client.servers:
            channels = channels + len(srv.channels)
            members = members + srv.member_count
        stats = "Name: {}\r\nUID: {}\r\n".format(bot.client.user.name, bot.client.user.id)
        stats += "Running music bots: {}\r\n".format(len(global_vars.music_bots))
        stats += "Servers: {} **|** Channels: {} **|** Users: {}\r\n".format(len(bot.client.servers), channels, members)
        if global_vars.started is not None:
            secs = time.time()-global_vars.started
            hours = math.floor(secs/3600)
            mins = math.floor((secs-(hours*3600))/60)
            secs = math.floor(secs-(hours*3600)-(mins*60))
            stats += "Uptime: {} hours {} minutes {} seconds\r\n".format(hours, mins, secs)
        process = psutil.Process(os.getpid())
        mem = process.memory_info()[0]
        memp = process.memory_percent()
        for child in process.children(recursive=True):
            mem += child.memory_info()[0]
            memp += child.memory_percent()
        mem = mem / float(2 ** 20)
        stats += "Memory usage: {:.2f} MiB, {:.2f} %\r\nCPU usage: {:.2f} %".format(mem, memp, psutil.cpu_percent())
        await bot.sendMessage( stats)
    except Exception:
        logger.PrintException(bot.message)
Example #13
0
async def on_member_remove(member):
    try:
        if await config.getConf(member.server.id, "left_notification") == True:

            def replace(*key_values):
                replace_dict = dict(key_values)
                replacement_function = lambda match: replace_dict[match.group(
                    0)]
                pattern = re.compile(
                    "|".join([re.escape(k) for k, v in key_values]), re.M)
                return lambda string: pattern.sub(replacement_function, string)

            replacements = (u"{mention}", member.mention), (
                u"{name}", member.display_name), (
                    u"{server}", member.server.name), (u"{discriminator}",
                                                       member.discriminator)
            channel = await config.getConf(member.server.id,
                                           "announcement_channel")
            channel = await search.channel(member.server, channel)
            if channel != None:
                try:
                    await client.send_message(
                        channel,
                        replace(*replacements)(await config.getConf(
                            member.server.id, "quit_message")))
                except discord.Forbidden:
                    return
    except:
        logger.PrintException()
Example #14
0
async def init(bot):
    chat = bot.message.channel
    user = str(bot.message.author.name)
    try:
        user = bot.message.author
        if bot.args[0] == "off":
            await config.setConf(bot.message.server.id, "ban_log_channel",
                                 None)
            await bot.sendMessage("Logs has been turned OFF!")
        elif len(bot.args) > 0:
            channel = " ".join(bot.args)
            channel = await search.channel(bot.message.server, channel)
            if channel is not None:
                await config.setConf(bot.message.server.id, "ban_log_channel",
                                     channel.name)
                await bot.sendMessage("Channel set!")
            else:
                await bot.sendMessage("Such channel doesn't exist!")

        else:
            await bot.sendMessage(
                "Not enough arguments! Current channel: {}").format(
                    config.getConf(message.server.id, "ban_log_channel"))
    except Exception:
        logger.PrintException(bot.message)
        return False
Example #15
0
async def init(bot):
    user=str(bot.message.author.name)
    level = await groups.getLevel(bot.message.server.id, bot.message.author)
    try:
        server_id = bot.message.server.id
        if server_id in global_vars.music_bots and await global_vars.music_bots.get(server_id).is_connected():
            if await global_vars.music_bots[server_id].is_playing():
                await botfunc.autoDelete(10,bot.message)
                if global_vars.music_bots[server_id].sender.id == bot.message.author.id:
                    # if await global_vars.music_bots[server_id].remaining()<=0:
                        # await botfunc.autoDelete(10,await bot.sendMessage( "Nothing left in queue. Stopping playback."),bot.message)
                    await global_vars.music_bots[server_id].playNext()
                    return True
                elif bot.access_level >= await groups.needed_level(server_id, "skip_admin"):
                    message = await bot.sendMessage( "You have rights to skip it instantly. Do you want to bypass voting? Answer: `yes` or `no`")
                    reply = await bot.client.wait_for_message(timeout=10.0, author=bot.message.author)
                    if reply is not None:
                        if reply.content.casefold() == "yes":
                            await global_vars.music_bots[server_id].playNext()
                            return True
                        else:
                            return await global_vars.music_bots[server_id].voteSkip(bot.message.author)
                        await botfunc.autoDelete(10, message, reply)
                else:
                    return await global_vars.music_bots[server_id].voteSkip(bot.message.author)
            else:
                await botfunc.autoDelete(10,await bot.sendMessage( "There is no song playing."),bot.message)
                #del global_vars.music_bots[server_id]
        await botfunc.autoDelete(10,await bot.sendMessage( "There's no active player."),bot.message)
    except:
        logger.PrintException(bot.message)
Example #16
0
async def on_server_join(server):
    try:
        await startup.createDatabases(server.id)
        await logger.print_to_file('[BOT] Setting default access levels')
        await startup.defaultLevels(server.id)
        await logger.print_to_file('[BOT] Setting bot administrators')
        await startup.setAdmins(server.id)
        await logger.print_to_file('[BOT] Setting default config values')
        await startup.defaultConfig(server.id)
        await logger.print_to_file(
            "[BOT] Setting \"\" to access level 5".format(
                server.owner.display_name))
        await groups.setLevel(server.id, server.owner.id, 5)

        await client.send_message(
            server.default_channel, """Hello there. :wave:
My name is `{}` and I'm a bot.
`{}` added me to this server so (s)he's my master on this server at the moment.
If you want to see the avaiable commands, just type `{}help`.
I will then PM you with all commands that you are able to use.
I'm looking forward being with you :slight_smile:

**Information for Server Owner:**
If this bot collides with another bot mention me and type
`config prefix "prefix"`
to change the command prefix.""".format(
                client.user.name, server.owner.display_name, await
                config.getConf(server.id, "prefix")))
    except:
        logger.PrintException()
async def on_member_update(before, after):
    try:
        if after.id != client.user.id:
            channel = await config.getConf(before.server.id, "log_channel")
            channel = await search.channel(before.server, channel)
            if channel != None:
                if before.display_name != after.display_name:
                    await client.send_message(
                        channel, "`{}` is now known as `{}`".format(
                            before.display_name, after.display_name))
                elif before.roles != after.roles:
                    if len(after.roles) - len(before.roles) > 0:
                        roles = list(set(after.roles) - set(before.roles))
                        for role in roles:
                            await client.send_message(
                                channel, "`{}` received `{}` role!".format(
                                    after.display_name, role))
                    else:
                        roles = list(set(before.roles) - set(after.roles))
                        for role in roles:
                            await client.send_message(
                                channel, "`{}` lost `{}` role!".format(
                                    after.display_name, role))
    except:
        logger.PrintException()
Example #18
0
async def init(bot):
    # Generate Help document
    help = await generateHelp(bot)
    # Only try if help has been generated
    if help is not None:
        try:
            try:
                await bot.sendMessage("```{}```".format(help),
                                      bot.message.author)
                await bot.sendMessage(
                    "```diff\n{}```".format(await generateRest(bot)),
                    bot.message.author)
                await bot.sendMessage(
                    "I've PM'd you the available commands to reduce spam. :upside_down:"
                )
            except discord.Forbidden:
                # Let's check if we have cached a previous generated pastebin url.
                if len(
                        global_vars.pastebin_url
                ) == 0 or global_vars.pastebin_date is None or global_vars.pastebin_date + datetime.timedelta(
                        days=1) <= dt.now():
                    # No pastebin url found or too old (older than 1 Day)
                    # Generate a new Pastebin URL
                    data = {
                        "api_dev_key": global_vars.pastebin_api_key,
                        "api_user_key": '',
                        "api_paste_name": 'LLSG-Bot Help',
                        "api_paste_format": 'text',
                        "api_paste_private": '1',
                        "api_paste_expire_date": '1D',
                        "api_option": 'paste',
                        "api_paste_code": help
                    }
                    with aiohttp.ClientSession() as session:
                        async with session.post(
                                "http://pastebin.com/api/api_post.php",
                                data=data) as r:
                            url = await r.text()
                    if url is not None:
                        global_vars.pastebin_url = url
                        global_vars.pastebin_date = dt.now()
                        # Send the newly generated link to the chat
                        await bot.sendMessage(
                            'Here\'s the lastest help:\r\n{}'.format(url))
                    else:
                        # Could not generate pastebin url. Sorry.
                        await bot.sendMessage(
                            'Sorry. I failed pushing the help to pastebin.:sob:\r\nPlease report us this occurence using !bug \"message\".'
                        )
                else:
                    # We have a cached URL which is not older than one day. Take this one.
                    await bot.sendMessage(
                        'Here\'s the help as of {}-{}-{}.\r\n{}'.format(
                            global_vars.pastebin_date.year,
                            global_vars.pastebin_date.month,
                            global_vars.pastebin_date.day,
                            global_vars.pastebin_url))
        except:
            logger.PrintException(bot.message)
Example #19
0
async def init(bot):
    try:
        await bot.sendMessage("Brb. Killing myself.")
        await bot.client.logout()
    except Exception:
        logger.PrintException(bot.message)
    finally:
        sys.exit(1337)
Example #20
0
async def init(bot):
    chat = bot.message.channel
    user = str(bot.message.author.name)
    try:
        idk = random.choice(list(open('idk.txt')))
        await bot.sendMessage('{}'.format(idk))
    except Exception:
        logger.PrintException(bot.message)
Example #21
0
async def getURLTitle(url):
    try:
        with aiohttp.ClientSession() as session:
            async with session.get(url) as r:
                parser = BeautifulSoup(await r.text(), "html.parser")
                return parser.title.string
    except:
        logger.PrintException()
    return None
Example #22
0
async def init(bot):
    try:
        await bot.sendMessage("Shutting down. Good night. :wave:")
        await bot.client.logout()
    except Exception:
        logger.PrintException(bot.message)
        return False
    finally:
        sys.exit(0)
Example #23
0
async def init(bot):
    try:
        if len(bot.args) == 0:
            await bot.sendMessage("You have to specify a domain!")
            return False
        if len(bot.args) > 1:
            if not bot.args[0].upper() in types:
                await bot.sendMessage("Unknown DNS entry type.")
                return False
            type = bot.args[0].upper()
            domain = bot.args[1]
        else:
            domain = bot.args[0]
            type = "A"
        try:
            resolver = aiodns.DNSResolver()
            f = await resolver.query(domain, type)
        except Exception as e:
            if "answer with no data" in str(e):
                await bot.sendMessage(
                    "There are no NS entries for {} with type {}".format(
                        domain, type))
                return False
            if "name not found" in str(e):
                await bot.sendMessage(
                    "Can't resolve the domain {}".format(domain))
                return False
            logger.PrintException(bot.message)
        result = ""
        for item in f:
            if type == "MX":
                result += "{}.     {}     IN     {}     {} {}\r\n".format(
                    domain, item.ttl, type, item.priority, item.host)
            else:
                if type == "NS":
                    result += "{}.     IN     {}     {}\r\n".format(
                        domain, type, item.host)
                else:
                    result += "{}.     {}     IN     {}     {}\r\n".format(
                        domain, item.ttl, type, item.host)
        await bot.sendMessage(result)
    except:
        logger.PrintException(bot.message)
Example #24
0
async def on_member_unban(server, user):
    try:
        channel = await config.getConf(server.id, "ban_log_channel")
        channel = await search.channel(server, channel)
        if channel != None:
            await client.send_message(
                channel,
                ":rainbow: **{0.name}#{0.discriminator}** is unbanned. (**ID:** {0.id})"
                .format(user))
    except:
        logger.PrintException()
Example #25
0
async def init(bot):
    chat = bot.message.channel
    try:
        if bot.message.channel.is_private:
            await bot.sendMessage("This command is disabled in private chats!")
            return False
        if len(bot.args) == 0:
            alias_list = await aliases.getAliases(bot.message.server.id)
            response = ""
            if alias_list is not None:
                for alias in alias_list:
                    response += "{0}{1} -> {0}{2}\r\n".format(
                        await config.getConf(bot.message.server.id, "prefix"),
                        alias['alias'], alias['command'])
            else:
                response = "No aliases found."
            await bot.sendMessage("```{}```".format(response))
        elif len(bot.args) == 1:
            alias = await aliases.getAlias(bot.message.server.id,
                                           str(bot.args[0]))
            if alias is not None:
                response = "{0}{1} -> {0}{2}".format(
                    await config.getConf(bot.message.server.id, "prefix"),
                    bot.args[0], alias)
            else:
                response = "Alias \"{}\" couldn't be found".format(bot.args[0])
            await bot.sendMessage("`{}`".format(response))
        else:
            prefix = await config.getConf(bot.message.server.id, "prefix")
            alias = bot.args[0]
            bot.args.pop(0)
            value = " ".join(bot.args)
            if value is not None:
                if value.casefold() == "delete" or value.casefold(
                ) == "remove" or value.casefold() == "null" or value.casefold(
                ) == "none":
                    if await aliases.deleteAlias(bot.message.server.id, alias):
                        response = "Alias \"{0}{1}\" has been deleted!".format(
                            prefix, alias)
                    else:
                        response = "Alias \"{0}{1}\" could not be deleted!".format(
                            prefix, alias)
                else:
                    if await aliases.setAlias(bot.message.server.id, alias,
                                              value):
                        response = "Alias \"{0}{1}\" set to \"{0}{2}\"!".format(
                            prefix, alias, value)
                    else:
                        response = "Alias \"{0}{1}\" could not be set!".format(
                            prefix, alias)
                await bot.sendMessage("`{}`".format(response))
    except Exception:
        logger.PrintException(bot.message)
        return False
Example #26
0
async def fetch_rss(url):
    try:
        with aiohttp.ClientSession() as session:
            async with session.get(url) as resp:
                if resp.status == 200:
                    return await resp.text()
                else:
                    return None
    except:
        logger.PrintException()
        return None
Example #27
0
 async def disconnect(self):
     ''' Stops the current music player and disconnects the client '''
     try:
         self.shutting_down = True
         self.__queue = None
         await self.stop()
         if self.VC is not None and self.VC.is_connected():
             await self.VC.disconnect()
         self.VC = None
         del global_vars.music_bots[self.id]
     except:
         logger.PrintException()
Example #28
0
async def set(server_id, user_id, tag, text, creation_date):
    '''Sets a new text for a tag'''
    try:
        async with await aiomysql.connect(host=global_vars.mysql_data['host'], port=global_vars.mysql_data['port'], user=global_vars.mysql_data['user'], password=global_vars.mysql_data['password'], db="srv_"+server_id, autocommit=True, charset='utf8') as con:
            async with await con.cursor() as cur:
                await cur.execute("CREATE TABLE IF NOT EXISTS tags (user_id VARCHAR(100) NOT NULL, tag VARCHAR(100) NOT NULL, text VARCHAR(1000) NOT NULL, creation_date VARCHAR(100) NOT NULL, PRIMARY KEY (tag));")
                await con.commit()
                await cur.execute("INSERT IGNORE INTO tags VALUES(%s,%s,%s,%s);", (str(user_id), str(tag), str(text), str(creation_date)))
                return cur.rowcount
    except:
        logger.PrintException()
        return False
Example #29
0
async def delete(server_id, tag):
    '''Deletes an spefic alias from a server'''
    try:
        async with await aiomysql.connect(host=global_vars.mysql_data['host'], port=global_vars.mysql_data['port'], user=global_vars.mysql_data['user'], password=global_vars.mysql_data['password'], db="srv_"+server_id, autocommit=True, charset='utf8') as con:
            async with await con.cursor() as cur:
                await cur.execute("CREATE TABLE IF NOT EXISTS tags (user_id VARCHAR(100) NOT NULL, tag VARCHAR(100) NOT NULL, text VARCHAR(1000) NOT NULL, creation_date VARCHAR(100) NOT NULL, PRIMARY KEY (tag));")
                await con.commit()
                await cur.execute("DELETE FROM tags WHERE LOWER(tag)=LOWER(%s);", (str(tag),))
                return cur.rowcount
    except:
        logger.PrintException()
        return False
Example #30
0
async def init(bot):
    chat=bot.message.channel
    try:
        if len(bot.args)>0:
            uid = ' '.join(bot.args)
            banned = []
            notfound = 0
            forbidden = []
            user = None
            for line in uid.split():
                if re.match("\d+",line):
                    user = discord.Object(id=line)
                    user.server = bot.message.server
                else:
                    await bot.sendMessage( ":x: {} is not a valid User or ID".format(line))
                try:
                    if user is not None:
                        await bot.client.ban(user, delete_message_days=1)
                        if not hasattr(user, 'display_name'):
                            banned.append("<@{}>".format(user.id))
                except discord.Forbidden:
                    #await bot.sendMessage( ':x: The bot does not have permissions to ban members or this user got highter rank than the bot.')
                    forbidden.append("<@{}>".format(user.id))
                except discord.NotFound:
                    notfound =+ 1
                except:
                    logger.PrintException(bot.message)
            if banned:
                if forbidden:
                    await bot.sendMessage( ":x: I couldn't ban: {}.".format(" ".join(forbidden)))
                if notfound:
                    await bot.sendMessage( ":rainbow: Banned users: {}\r\n Not found: {} user(s).\r\nForbidden: {}".format(" ".join(banned), notfound, forbidden))
                else:
                    await bot.sendMessage( ":rainbow: Banned users: {}.".format(" ".join(banned)))
        else:
            await bot.sendMessage( "I can't ban nothing.")
    except Exception:
        logger.PrintException(bot.message)
        return False