Exemplo n.º 1
0
def check_file():
    weather = {}
    weather['WEATHER_API_KEY'] = False
    f = "data/weather/weather.json"
    if not dataIO.is_valid_json(f):
        print("Creating default weather.json...")
        dataIO.save_json(f, weather)
Exemplo n.º 2
0
 async def role(self, ctx, *, role: str):
     """Allows you to set the role that will have access to the command.
        If a role has spaces, just write it as is.
        Examples:
        the100 set role man gler
        the100 set role barbell"""
     role = role.lower()
     server = ctx.message.server
     if server.id not in self.db:
         self.db[server.id] = {"token": None, "role": None}
     else:
         if self.db[server.id]["role"]:
             await self.bot.say("Are you sure you want to overwrite the current access role? Yes/No")
             answer = await self.bot.wait_for_message(timeout=15,
                                                      author=ctx.message.author)
             if answer is None:
                 await self.bot.say("Action cancelled")
                 return
             elif answer.content.lower().strip() == "yes":
                 self.db[server.id]["role"] = role
                 await self.bot.say("role overwritten")
                 dataIO.save_json(self.json, self.db)
                 return
             else:
                 await self.bot.say("Action cancelled")
                 return
         else:
             self.db[server.id]["role"] = role
     dataIO.save_json(self.json, self.db)
     await self.bot.say("Access role {} has been set".format(role))
Exemplo n.º 3
0
 def _update_name(self, old, new):  # Change the 'name' variable in the role ID. Since we don't pull names dynamicly in the table
     if new.server.id in self.json:
         if old.name != new.name:
             if new.id in self.json[new.server.id]:
                 self.json[new.server.id][new.id]['name'] = new.name
                 log.debug('Written new name to {}'.format(new.id))
                 dataIO.save_json(self.location, self.json)
Exemplo n.º 4
0
 async def _del(self, ctx, channel: discord.Channel=None):
     """Lists regexes used to filter messages"""
     server = ctx.message.server
     self.regexen = dataIO.load_json(JSON_PATH)
     if not self._re_present(server):
         await self.bot.say('There are no filter patterns set for this server.')
         return
     re_list = {}
     i = 1
     table = ' | '.join(['#'.ljust(4), 'mode', 'pattern']) + '\n'  # header
     for c in self.regexen[server.id]:
         if c == ALL_CHANNELS or (channel and channel.id == c) or not channel:
             if c == ALL_CHANNELS:
                 if self._re_present(ALL_CHANNELS):
                     table += '\nServer-wide:\n'
             else:
                 if not channel:
                     channel = self.bot.get_channel(c)
                 if self._re_present(channel):
                     table += '\n#' + channel.name + '\n'
         for regex, mode in self.regexen[server.id][c].items():
             table += ' | '.join([str(i).ljust(4), mode, regex]) + '\n'
             re_list[str(i)] = (server.id, c, regex)
             i += 1
     prompt = 'Choose the number of the pattern to delete:\n'
     await self.bot.say(prompt + '```py\n' + table + '```')
     msg = await self.bot.wait_for_message(author=ctx.message.author, timeout=15)
     if msg is None:
         return
     msg = msg.content.strip()
     if msg in re_list:
         sid, cid, regex = re_list[msg]
         del(self.regexen[sid][cid][regex])
         await self.bot.say('Pattern removed.')
     dataIO.save_json(JSON_PATH, self.regexen)
Exemplo n.º 5
0
def check_files():
    if not os.path.exists('data/sentryio/config.json'):
        try:
            os.mkdir('data/sentryio')
        except FileExistsError:
            pass
        dataIO.save_json('data/sentryio/config.json', {})
Exemplo n.º 6
0
 async def removegoal(self, level : int, *name : str):
     """removes a goal from chat goals"""
     actual_name = " ".join(name)
     self.tracker.remove_goal(DiscordAchievement, level, actual_name)
     to_save = {}
     to_save['goals'] = DiscordAchievement.goals
     dataIO.save_json("data/loyalty/settings.json", to_save)
Exemplo n.º 7
0
 async def buy(self, ctx, stock_name, amount : int):
     """Buy *amount* shares of *stock_name* stock"""
     user = ctx.message.author
     economy = self.bot.get_cog("Economy")
     if economy is not None:
         bank = economy.bank
         if user.id not in self.portfolios:
             self.portfolios[user.id] = {}
         if stock_name in self.stocks:
             if amount > 0:
                 cost = self.stocks[stock_name]['price'] * amount
                 if bank.can_spend(user, cost):
                     bank.withdraw_credits(user, cost)
                     if stock_name in self.portfolios[user.id]:
                         self.portfolios[user.id][stock_name] += amount
                     else:
                         self.portfolios[user.id][stock_name] = amount
                     self.stocks[stock_name]['bought'] += amount
                     dataIO.save_json('data/stocks/portfolios.json', self.portfolios)
                     dataIO.save_json('data/stocks/stocks.json', self.stocks)
                     await self.bot.say("You bought {1} stocks of {0}".format(stock_name, amount))
                 else:
                     await self.bot.say("You don't have enough bank credits to purchase {0} of {1}".format(amount, stock_name))
             else:
                 await self.bot.say("You know better than to try to trick me")
         else:
             await self.bot.say("{0} isn't a valid stock".format(stock_name))
     else:
         await self.bot.say("Couldn't find the Economy cog, please load it before trying to use Stocks")
Exemplo n.º 8
0
def check_files():
    if not os.path.exists('data/stats/settings.json'):
        try:
            os.mkdir('data/stats')
        except:
            pass
        dataIO.save_json('data/stats/settings.json', {})
Exemplo n.º 9
0
def check_file():
    data = {}
    data['API_KEY'] = ''
    f = "data/goodreads/settings.json"
    if not dataIO.is_valid_json(f):
        dataIO.save_json(f, data)
        print("Creating default settings.json...")
Exemplo n.º 10
0
 async def sell(self, ctx, stock_name, amount : int):
     """Sell *amount* shares of *stock_name* stock"""
     user = ctx.message.author
     economy = self.bot.get_cog("Economy")
     if economy is not None:
         bank = economy.bank
         if user.id not in self.portfolios:
             self.portfolios[user.id] = {}
         if stock_name in self.stocks and stock_name in self.portfolios[user.id]:
             if amount > 0:
                 if self.portfolios[user.id][stock_name] >= amount:
                     price = self.stocks[stock_name]['price'] * amount
                     bank.deposit_credits(user, price)
                     self.portfolios[user.id][stock_name] -= amount
                     self.stocks[stock_name]['sold'] += amount
                     if self.portfolios[user.id][stock_name] == 0:
                         del self.portfolios[user.id][stock_name]
                     dataIO.save_json('data/stocks/portfolios.json', self.portfolios)
                     dataIO.save_json('data/stocks/stocks.json', self.stocks)
                     await self.bot.say("You sold {1} stocks of {0}".format(stock_name, amount))
                 else:
                     await self.bot.say("You don't have enough {0} stocks to sell {1}".format(stock_name, amount))
             else:
                 await self.bot.say("You know better than to try to trick me")
         else:
             await self.bot.say("{0} isn't a valid stock or you don't have any".format(stock_name))
     else:
         await self.bot.say("Couldn't find the Economy cog, please load it before trying to use Stocks")
Exemplo n.º 11
0
 async def paydaytime(self, ctx, seconds: int):
     """Seconds between each payday"""
     server = ctx.message.server
     self.settings[server.id]["PAYDAY_TIME"] = seconds
     await self.bot.say("Value modified. At least {} seconds must pass "
                        "between each payday.".format(seconds))
     dataIO.save_json(self.file_path, self.settings)
Exemplo n.º 12
0
 async def paydaycredits(self, ctx, credits: int):
     """Credits earned each payday"""
     server = ctx.message.server
     self.settings[server.id]["PAYDAY_CREDITS"] = credits
     await self.bot.say("Every payday will now give {} credits."
                        "".format(credits))
     dataIO.save_json(self.file_path, self.settings)
Exemplo n.º 13
0
def check_files():
    if not os.path.exists('data/logger/saved_levels.json'):
        try:
            os.mkdir('data/logger')
        except FileExistsError:
            pass
        dataIO.save_json('data/logger/saved_levels.json', {})
Exemplo n.º 14
0
 async def token(self, ctx, token: str):
     """Allows you to set the API Token for retrieving information.
        Warning, please do this through PM with the bot.
        Another way is to create a channel that only the bot and you can access."""
     server = ctx.message.server
     if server.id not in self.db:
         self.db[server.id] = {"token": None, "role": None}
     else:
         if self.db[server.id]["token"]:
             await self.bot.say("Are you sure you want to overwrite the current token? Yes/No")
             answer = await self.bot.wait_for_message(timeout=15,
                                                      author=ctx.message.author)
             if answer is None:
                 await self.bot.say("Action cancelled")
                 return
             elif answer.content.lower().strip() == "yes":
                 self.db[server.id]["token"] = token
                 await self.bot.say("Token overwritten")
                 dataIO.save_json(self.json, self.db)
                 return
             else:
                 await self.bot.say("Action cancelled")
                 return
         else:
             self.db[server.id]["token"] = token
     dataIO.save_json(self.json, self.db)
     await self.bot.say("Token successfully set")
Exemplo n.º 15
0
 async def registercredits(self, ctx, credits: int):
     """Credits given on registering an account"""
     server = ctx.message.server
     if credits < 0:
         credits = 0
     self.settings[server.id]["REGISTER_CREDITS"] = credits
     await self.bot.say("Registering an account will now give {} credits.".format(credits))
     dataIO.save_json(self.file_path, self.settings)
Exemplo n.º 16
0
 async def replset_print_pm(self, ctx, number_of_pages: int=20):
     """send pages to pm. Defaults to 20"""
     number_of_pages = max(number_of_pages, 1)
     self.settings["OUTPUT_REDIRECT"] = "pm"
     self.settings["PM_PAGES"] = number_of_pages
     dataIO.save_json("data/repl/settings.json", self.settings)
     await self.bot.say("repl overflow will now go to pm with a maximum of "
                        "{} messages".format(number_of_pages))
Exemplo n.º 17
0
def check_files():
    if not dataIO.is_valid_json(JSON):
        defaults = {
            'everything': False,
            'attachments': False,
            'default': False
        }
        dataIO.save_json(JSON, defaults)
Exemplo n.º 18
0
 async def unpunish(self, ctx, user: discord.Member):
     """Unpunishes a punished user"""
     if user.id in self.json[ctx.message.server.id]:
         r = discord.utils.get(ctx.message.server.roles, name='Punished')
         del self.json[ctx.message.server.id][user.id]
         await self.bot.remove_roles(user, r)
         dataIO.save_json(self.location, self.json)
         await self.bot.say('``{}`` is now unpunished.'.format(user.display_name))
Exemplo n.º 19
0
def check_files():
    if not os.path.exists('data/admin/settings.json'):
        try:
            os.mkdir('data/admin')
        except FileExistsError:
            pass
        else:
            dataIO.save_json('data/admin/settings.json', {})
Exemplo n.º 20
0
 async def addgoal(self, level : int, name : str, *description : str):
     """adds a goal to chat goals"""
     actual_name = name
     desc = " ".join(description)
     self.tracker.add_goal(DiscordAchievement, level, actual_name, desc)
     to_save = {}
     to_save['goals'] = DiscordAchievement.goals
     dataIO.save_json("data/loyalty/settings.json", to_save)
Exemplo n.º 21
0
def check_files():
    defaults = {
        'HOST': '127.0.0.1',
        'INTERVAL': 5
    }
    if not dataIO.is_valid_json(JSON):
        print("Creating empty %s" % JSON)
        dataIO.save_json(JSON, defaults)
Exemplo n.º 22
0
 def _load_perms(self):
     try:
         ret = dataIO.load_json("data/permissions/perms.json")
     except:
         ret = {}
         os.mkdir("data/permissions")
         dataIO.save_json("data/permissions/perms.json", ret)
     return ret
Exemplo n.º 23
0
def check_file():
    data = {}
    data['LASTFM_API_KEY'] = ''
    data['USERS'] = {}
    f = "data/lastfm/lastfm.json"
    if not dataIO.is_valid_json(f):
        print("Creating default lastfm.json...")
        dataIO.save_json(f, data)
Exemplo n.º 24
0
 async def _api(self, context, key: str):
     """Set an API key for this cog. Get one at: """
     data = dataIO.load_json(self.settings_file)
     data['API_KEY'] = key
     self.key = key
     message = 'API Key set'
     dataIO.save_json(self.settings_file, data)
     await self.bot.say('*{}*'.format(message))
Exemplo n.º 25
0
 async def message(self, ctx, *, text):
     """Set the message for when the user sends a illegal discord link"""
     serverid = ctx.message.server.id
     self.json[serverid]['message'] = text
     dataIO.save_json(self.location, self.json)
     await self.bot.say('Message is set')
     if self.json[serverid]['dm'] is False:
         await self.bot.say('Remember: Direct Messages on removal is disabled!\nEnable it with ``antilinkset toggledm``')
Exemplo n.º 26
0
def check_files():
    repos = \
        {'community': {'url': "https://github.com/Twentysix26/Red-Cogs.git"}}

    f = "data/downloader/repos.json"
    if not dataIO.is_valid_json(f):
        print("Creating default data/downloader/repos.json")
        dataIO.save_json(f, repos)
Exemplo n.º 27
0
def load_cogs():
    try:
        if sys.argv[1] == "--no-prompt":
            no_prompt = True
        else:
            no_prompt = False
    except:
        no_prompt = False

    try:
        registry = dataIO.load_json("data/red/cogs.json")
    except:
        registry = {}

    bot.load_extension('cogs.owner')
    owner_cog = bot.get_cog('Owner')
    if owner_cog is None:
        print("You got rid of the damn OWNER cog, it has special functions"
              " that I require to run.\n\n"
              "I can't start without it!")
        print()
        print("Go here to find a new copy:\n{}".format(
            "https://github.com/Twentysix26/Red-DiscordBot"))
        exit(1)

    failed = []
    extensions = owner_cog._list_cogs()
    for extension in extensions:
        if extension.lower() == "cogs.owner":
            continue
        in_reg = extension in registry
        if not (in_reg or no_prompt):
            print("\nNew extension: {}".format(extension))
            print("Load it?(y/n)")
            if not get_answer():
                registry[extension] = False
                continue
            registry[extension] = True
        if not registry[extension]:
            continue
        try:
            owner_cog._load_cog(extension)
        except Exception as e:
            print("{}: {}".format(e.__class__.__name__, str(e)))
            logger.exception(e)
            failed.append(extension)
            registry[extension] = False

    if extensions:
        dataIO.save_json("data/red/cogs.json", registry)

    if failed:
        print("\nFailed to load: ", end="")
        for m in failed:
            print(m + " ", end="")
        print("\n")

    return owner_cog
Exemplo n.º 28
0
 async def toggledm(self, ctx):
     serverid = ctx.message.server.id
     if self.json[serverid]['dm'] is False:
         self.json[serverid]['dm'] = True
         await self.bot.say('Enabled DMs on removal of invite links')
     elif self.json[serverid]['dm'] is True:
         self.json[serverid]['dm'] = False
         await self.bot.say('Disabled DMs on removal of invite links')
     dataIO.save_json(self.location, self.json)
Exemplo n.º 29
0
 def _save_loyalty(self):
     to_save = {}
     for key_server, value_server in self.accounts.items():
         to_save[key_server] = {}
         for key_user, value_user in value_server.items():
             to_save[key_server][key_user] = {}
             for key_achievement, value_achievement in value_user.items():
                 to_save[key_server][key_user][key_achievement] = key_achievement[0]
     dataIO.save_json(self.file_path, to_save)
Exemplo n.º 30
0
def check_file():
    data = {}
    data['applist'] = {}
    data['applist']['apps'] = {}
    data['applist']['apps']['app'] = []
    f = 'data/steam/games.json'
    if not dataIO.is_valid_json(f):
        print('Creating default games.json...')
        dataIO.save_json(f, data)
Exemplo n.º 31
0
def check_files():
    defaults = {'HOST': '127.0.0.1', 'INTERVAL': 5}
    if not dataIO.is_valid_json(JSON):
        print("Creating empty %s" % JSON)
        dataIO.save_json(JSON, defaults)
Exemplo n.º 32
0
 def save_json(self):
     dataIO.save_json("data/serverwhitelist/settings.json", self.settings)
     dataIO.save_json("data/serverwhitelist/list.json", self.whitelist)
Exemplo n.º 33
0
 def save(self):
     dataIO.save_json(JSON, self.settings)
Exemplo n.º 34
0
def check_files():
    if not os.path.exists("data/giveme/settings.json"):
        print("Creating data/giveme/settings.json file...")
        dataIO.save_json("data/giveme/settings.json", {})
Exemplo n.º 35
0
def check_file():
    f = 'data/staffapp/settings.json'
    if dataIO.is_valid_json(f) is False:
        dataIO.save_json(f, {})
Exemplo n.º 36
0
 def _set_default(self, id):
     self.settings[id] = {
         "ROLES": [],
         "ENABLED": False
     }
     dataIO.save_json(self.path, self.settings)
Exemplo n.º 37
0
def check_file():
    data = {}
    f = "data/url/url.json"
    if not dataIO.is_valid_json(f):
        print("url.json 파일생성을 완료하였습니다!")
        dataIO.save_json(f, data)
Exemplo n.º 38
0
 async def quoteset_edit(self, ctx, name, *, quote):
     """Edit a quote."""
     server = ctx.message.server
     self.settings[server.id][name] = quote
     dataIO.save_json(JSON, self.settings)
     await self.bot.say("Quote saved.")
Exemplo n.º 39
0
def check_files():
    if not os.path.exists("data/adkillr/adkillr.json"):
        print("Creating data/adkillr/adkillr.json file...")
        dataIO.save_json("data/adkillr/adkillr.json", {})
Exemplo n.º 40
0
def check_file():
    f = 'data/away/away.json'
    if not dataIO.is_valid_json(f):
        dataIO.save_json(f, {})
        print('Creating default away.json...')
Exemplo n.º 41
0
 def _save_leaderboard(self):
     dataIO.save_json("data/armorsmith/leaderboard.json", self.leaderboard)
Exemplo n.º 42
0
 def save_repos(self):
     dataIO.save_json(self.file_path, self.repos)
Exemplo n.º 43
0
def set_cog(cog, value):  # TODO: move this out of red.py
    data = dataIO.load_json("data/red/cogs.json")
    data[cog] = value
    dataIO.save_json("data/red/cogs.json", data)
Exemplo n.º 44
0
 def save(self):
     dataIO.save_json("data/antiraid/settings.json", self.settings)
Exemplo n.º 45
0
 def save_json(self):
     dataIO.save_json(path + 'settings.json', self.settings)
Exemplo n.º 46
0
 async def _save_settings(self):
     dataIO.save_json(self.settings_file, self.settings)
Exemplo n.º 47
0
def check_files():
    f = "data/requester/settings.json"
    if not dataIO.is_valid_json(f):
        print("Creating default requester's settings.json...")
        dataIO.save_json(f, {})
Exemplo n.º 48
0
def check_file():
    f = 'data/married/married.json'
    if not dataIO.is_valid_json(f):
        dataIO.save_json(f, {})
        print('Creating default married.json...')
Exemplo n.º 49
0
def check_file():
    f = 'data/punish/settings.json'
    if dataIO.is_valid_json(f) is False:
        log.debug('Creating json: settings.json')
        dataIO.save_json(f, {})
Exemplo n.º 50
0
 async def _divorce(self, server, ctx, user):
     author = ctx.message.author.name
     del self.data[server.id]["user"][author]["married_to"][user.name]
     del self.data[server.id]["user"][user.name]["married_to"][author]
     dataIO.save_json(self.JSON, self.data)
Exemplo n.º 51
0
def check_file():
    """Check files."""
    if not dataIO.is_valid_json(JSON):
        dataIO.save_json(JSON, {})
Exemplo n.º 52
0
 def save_settings(self):
     dataIO.save_json("data/wordfilter/settings.json", self.settings)
Exemplo n.º 53
0
 def _save(self):
     dataIO.save_json('data/mod_log.json', self.db)
Exemplo n.º 54
0
 async def _ignore_save(self):
     dataIO.save_json(self.ignore_file, self.ignore)
Exemplo n.º 55
0
 async def reactionpoll_init(self, ctx):
     """Initialize server settings."""
     self.settings[ctx.message.server.id]["messages"] = {}
     dataIO.save_json(JSON, self.settings)
     await self.bot.say("Server setttings initialized.")
Exemplo n.º 56
0
 def save_json(self):
     dataIO.save_json("data/staffapp/settings.json", self.settings)
Exemplo n.º 57
0
 def _save_inventory(self):
     dataIO.save_json("data/armorsmith/inventory.json", self.accounts)
Exemplo n.º 58
0
def check_file():
    """Check files."""
    defaults = {}
    if not dataIO.is_valid_json(JSON):
        dataIO.save_json(JSON, defaults)
Exemplo n.º 59
0
 def save_settings(self):
     dataIO.save_json("data/giveme/settings.json", self.settings)
Exemplo n.º 60
0
def check_files():
    f = "data/downloader/repos.json"
    if not dataIO.is_valid_json(f):
        print("Creating default data/downloader/repos.json")
        dataIO.save_json(f, {})