Browse Source

The start of some refactoring. I fucked up by starting the new setitng system too so i guess that will completed on this branch then merged with dev.

tags/v1.5.0
Roxie Gibson 6 years ago
parent
commit
4b0b0b89ed
21 changed files with 165 additions and 143 deletions
  1. +0
    -0
      Roxbot/__init__.py
  2. +2
    -2
      Roxbot/checks.py
  3. +3
    -3
      Roxbot/cogs/admin.py
  4. +4
    -4
      Roxbot/cogs/customcommands.py
  5. +1
    -1
      Roxbot/cogs/fun.py
  6. +3
    -3
      Roxbot/cogs/gss.py
  7. +1
    -1
      Roxbot/cogs/joinleave.py
  8. +2
    -2
      Roxbot/cogs/nsfw.py
  9. +3
    -2
      Roxbot/cogs/reddit.py
  10. +2
    -2
      Roxbot/cogs/selfassign.py
  11. +1
    -1
      Roxbot/cogs/trivia.py
  12. +3
    -3
      Roxbot/cogs/twitch.py
  13. +0
    -0
      Roxbot/cogs/util.py
  14. +1
    -1
      Roxbot/err_handle.py
  15. +12
    -12
      Roxbot/load_config.py
  16. +0
    -0
      Roxbot/preferences_example.ini
  17. +0
    -0
      Roxbot/settings/blacklist.txt
  18. +114
    -0
      Roxbot/settings/guild_settings.py
  19. +7
    -8
      Roxbot/settings/settings.py
  20. +0
    -92
      config/server_config.py
  21. +6
    -6
      main.py

config/blacklist.txt → Roxbot/__init__.py View File


checks.py → Roxbot/checks.py View File

from discord.ext import commands from discord.ext import commands
import load_config
from config.server_config import ServerConfig
from Roxbot import load_config
from Roxbot.settings.guild_settings import ServerConfig


def is_owner_or_admin(): def is_owner_or_admin():
def predicate(ctx): def predicate(ctx):

cogs/admin.py → Roxbot/cogs/admin.py View File

import datetime import datetime
import time import time
import checks
from Roxbot import checks
import discord import discord
from config.server_config import ServerConfig
from Roxbot.settings.guild_settings import ServerConfig
from discord.ext.commands import bot, group, guild_only, bot_has_permissions from discord.ext.commands import bot, group, guild_only, bot_has_permissions




@warn.command() @warn.command()
async def add(self, ctx, user: discord.User = None, *, warning = ""): async def add(self, ctx, user: discord.User = None, *, warning = ""):
"""Adds a warning to a user.""" """Adds a warning to a user."""
# Warning in the config is a dictionary of user ids. The user ids are equal to a list of dictionaries.
# Warning in the settings is a dictionary of user ids. The user ids are equal to a list of dictionaries.
self.servers = self.con.load_config() self.servers = self.con.load_config()
warning_limit = 2 warning_limit = 2
guild_id = str(ctx.guild.id) guild_id = str(ctx.guild.id)

cogs/customcommands.py → Roxbot/cogs/customcommands.py View File

import discord import discord
import checks
from Roxbot import checks, load_config
from discord.ext.commands import group from discord.ext.commands import group
from config.server_config import ServerConfig
import load_config
from Roxbot.settings.guild_settings import ServerConfig


def blacklisted(user): def blacklisted(user):
with open("config/blacklist.txt", "r") as fp:
with open("settings/blacklist.txt", "r") as fp:
for line in fp.readlines(): for line in fp.readlines():
if user.id+"\n" == line: if user.id+"\n" == line:
return True return True

cogs/fun.py → Roxbot/cogs/fun.py View File

import discord import discord
import random import random
import checks
from Roxbot import checks
import requests import requests
from discord.ext.commands import bot from discord.ext.commands import bot



cogs/gss.py → Roxbot/cogs/gss.py View File

import datetime import datetime
import requests import requests
import load_config
from Roxbot import load_config
from discord import utils from discord import utils
from discord.ext import commands from discord.ext import commands
from discord.ext.commands import bot from discord.ext.commands import bot
from config.server_config import ServerConfig
from Roxbot.settings.guild_settings import ServerConfig




def is_gss(): def is_gss():
def tatsumaki_api_call(self, member): def tatsumaki_api_call(self, member):
base = "https://api.tatsumaki.xyz/" base = "https://api.tatsumaki.xyz/"
url = base + "guilds/" + str(self.guild.id) + "/members/" + str(member.id) + "/stats" url = base + "guilds/" + str(self.guild.id) + "/members/" + str(member.id) + "/stats"
r = requests.get(url,headers={"Authorization":load_config.tat_token})
r = requests.get(url, headers={"Authorization": load_config.tat_token})
return r.json() return r.json()


@is_gss() @is_gss()

cogs/joinleave.py → Roxbot/cogs/joinleave.py View File

import discord import discord
from config.server_config import ServerConfig
from Roxbot.settings.guild_settings import ServerConfig




class JoinLeave(): class JoinLeave():

cogs/nsfw.py → Roxbot/cogs/nsfw.py View File

import random import random
import checks
from Roxbot import checks
import requests import requests
from discord.ext.commands import bot from discord.ext.commands import bot
from config.server_config import ServerConfig
from Roxbot.settings.guild_settings import ServerConfig


class NFSW(): class NFSW():
def __init__(self, bot_client): def __init__(self, bot_client):

cogs/reddit.py → Roxbot/cogs/reddit.py View File

from discord.ext.commands import bot from discord.ext.commands import bot
from config.server_config import ServerConfig
from Roxbot.settings.guild_settings import ServerConfig
from lxml import html from lxml import html
import random import random
import requests import requests
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
import checks
from Roxbot import checks



# Warning, this cog sucks so much but hopefully it works and doesn't break the bot too much. Just lazily edited old code and bodged it into this one. # Warning, this cog sucks so much but hopefully it works and doesn't break the bot too much. Just lazily edited old code and bodged it into this one.
# There is redundant code here that if removed would make it easier. But it might be handy in the future and isn't that bad. # There is redundant code here that if removed would make it easier. But it might be handy in the future and isn't that bad.

cogs/selfassign.py → Roxbot/cogs/selfassign.py View File

import discord import discord
from discord.ext import commands from discord.ext import commands


import load_config
from config.server_config import ServerConfig
from Roxbot import load_config
from Roxbot.settings.guild_settings import ServerConfig




class SelfAssign(): class SelfAssign():

cogs/trivia.py → Roxbot/cogs/trivia.py View File

# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-


import checks
from Roxbot import checks
import discord import discord
import asyncio import asyncio
import requests import requests

cogs/twitch.py → Roxbot/cogs/twitch.py View File

import discord import discord
from discord.ext import commands from discord.ext import commands


import checks
from config.server_config import ServerConfig
from Roxbot import checks
from Roxbot.settings.guild_settings import ServerConfig


def blacklisted(user): def blacklisted(user):
with open("config/blacklist.txt", "r") as fp:
with open("settings/blacklist.txt", "r") as fp:
for line in fp.readlines(): for line in fp.readlines():
if user.id+"\n" == line: if user.id+"\n" == line:
return True return True

cogs/util.py → Roxbot/cogs/util.py View File


err_handle.py → Roxbot/err_handle.py View File

import datetime import datetime
import discord import discord
from discord.ext import commands from discord.ext import commands
from config.server_config import ServerConfig
from Roxbot.settings.guild_settings import ServerConfig


class ErrHandle: class ErrHandle:
def __init__(self, bot_client): def __init__(self, bot_client):

load_config.py → Roxbot/load_config.py View File

import configparser import configparser


settings = configparser.ConfigParser() settings = configparser.ConfigParser()
settings.read("settings/preferences.ini")
settings.read("roxbot/settings/preferences.ini")


command_prefix = settings["Roxbot"]["Command_Prefix"] command_prefix = settings["Roxbot"]["Command_Prefix"]
token = settings["Roxbot"]["Token"] token = settings["Roxbot"]["Token"]
# IF YOU ARE TESTING OR NOT IN THE GSS DISCORD, REMOVE "cogs.gss" FROM THE LIST # IF YOU ARE TESTING OR NOT IN THE GSS DISCORD, REMOVE "cogs.gss" FROM THE LIST


cogs = [ cogs = [
"cogs.admin",
"cogs.fun",
"cogs.customcommands",
"cogs.joinleave",
"cogs.nsfw",
"cogs.reddit",
"cogs.selfassign",
"cogs.trivia",
"cogs.twitch",
"cogs.util",
#"cogs.gss"
"roxbot.cogs.admin",
"roxbot.cogs.fun",
"roxbot.cogs.customcommands",
"roxbot.cogs.joinleave",
"roxbot.cogs.nsfw",
"roxbot.cogs.reddit",
"roxbot.cogs.selfassign",
"roxbot.cogs.trivia",
"roxbot.cogs.twitch",
"roxbot.cogs.util",
#"roxbot.cogs.gss"
] ]

settings/preferences_example.ini → Roxbot/preferences_example.ini View File


+ 0
- 0
Roxbot/settings/blacklist.txt View File


+ 114
- 0
Roxbot/settings/guild_settings.py View File

import json

class GuildSettings(object):

__slots__ = ["settings", "id", "nsfw", "self_assign", "greets", "goodbyes", "twitch", "perm_roles", "custom_commands", "warnings", "is_anal", "gss", "guild_template"]

def __init__(self, guild):
self.id = guild.id
self.guild_template = {
"example": {
"greets": {
"enabled": 0,
"welcome-channel": "",
"member-role": "",
"custom-message": "",
"default-message": "Be sure to read the rules."
},
"goodbyes": {
"enabled": 0,
"goodbye-channel": "",
},
"self_assign": {
"enabled": 0,
"roles": []
},
"twitch": {
"enabled": 0,
"channel": "",
"whitelist": {
"enabled": 0,
"list": []
}
},
"nsfw": {
"enabled": 0,
"channels": [],
"blacklist": []
},
"perm_roles": {
"admin": [],
"mod": []
},
"custom_commands": {
"0": {},
"1": {}
},
"gss": {
"log_channel": "",
"required_days": "",
"required_score": "",
},
"warnings": {},
"is_anal": {"y/n": 0}
}
}
self.get_settings()

def _write_changes(self, config):
with open('settings/servers.json', 'w') as conf_file:
json.dump(config, conf_file)

def _error_check(self):
for server in self.settings:
# Server ID needs to be made a string for this statement because keys have to be strings in JSON. Which is annoying now we use int for ids.
server_id = str(server.id)
if str(server_id) not in self.settings:
self.settings[server_id] = self.guild_template["example"]
self.update_settings(self.settings)
print(
"WARNING: The settings file for {} was not found. A template has been loaded and saved. All cogs are turned off by default.".format(
server.name.upper()))
else:
for cog_setting in self.guild_template["example"]:
if cog_setting not in self.settings[server_id]:
self.settings[server_id][cog_setting] = self.guild_template["example"][
cog_setting]
self.update_settings(self.settings)
print(
"WARNING: The settings file for {} was missing the {} cog. This has been fixed with the template version. It is disabled by default.".format(
server.name.upper(), cog_setting.upper()))
for setting in self.guild_template["example"][cog_setting]:
if setting not in self.settings[server_id][cog_setting]:
self.settings[server_id][cog_setting][setting] = self.guild_template["example"][
cog_setting][setting]
self.update_settings(self.settings)
print(
"WARNING: The settings file for {} was missing the {} setting in the {} cog. This has been fixed with the template version. It is disabled by default.".format(
server.name.upper(), setting.upper(), cog_setting.upper()))

print("")

def get_settings(self):
with open('settings/servers.json', 'r') as config_file:
self.settings = json.load(config_file)
self._error_check()
self.nsfw = self.settings[str(self.id)]["nsfw"]
self.self_assign = self.settings[str(self.id)]["self_assign"]
self.greets = self.settings[str(self.id)]["greets"]
self.goodbyes = self.settings[str(self.id)]["goodbyes"]
self.twitch = self.settings[str(self.id)]["twitch"]
self.perm_roles = self.settings[str(self.id)]["perm_roles"]
self.custom_commands = self.settings[str(self.id)]["custom_commands"]
self.warnings = self.settings[str(self.id)]["warnings"]
self.is_anal = self.settings[str(self.id)]["is_anal"]
# Add custom cog settings loading here
self.gss = self.settings[str(self.id)]["gss"]

def update_settings(self, changed_dict, setting = None):
self.get_settings()
if setting:
self.settings[str(self.id)][setting] = changed_dict
else:
self.settings[str(self.id)] = changed_dict
self._write_changes(self.settings)

config/settings.py → Roxbot/settings/settings.py View File

import aiohttp import aiohttp
import asyncio import asyncio


import checks
import load_config
from config.server_config import ServerConfig
from Roxbot import checks, load_config
from Roxbot.settings.guild_settings import ServerConfig


import discord import discord
from discord.ext.commands import bot, group, is_owner, bot_has_permissions from discord.ext.commands import bot, group, is_owner, bot_has_permissions
mentions.remove(user) mentions.remove(user)


if option in ['+', 'add']: if option in ['+', 'add']:
with open("config/blacklist.txt", "r") as fp:
with open("settings/blacklist.txt", "r") as fp:
for user in mentions: for user in mentions:
for line in fp.readlines(): for line in fp.readlines():
if user.id + "\n" in line: if user.id + "\n" in line:
mentions.remove(user) mentions.remove(user)


with open("config/blacklist.txt", "a+") as fp:
with open("settings/blacklist.txt", "a+") as fp:
lines = fp.readlines() lines = fp.readlines()
for user in mentions: for user in mentions:
if user.id not in lines: if user.id not in lines:
return await ctx.send('{} user(s) have been added to the blacklist'.format(blacklist_amount)) return await ctx.send('{} user(s) have been added to the blacklist'.format(blacklist_amount))


elif option in ['-', 'remove']: elif option in ['-', 'remove']:
with open("config/blacklist.txt", "r") as fp:
with open("settings/blacklist.txt", "r") as fp:
lines = fp.readlines() lines = fp.readlines()
with open("config/blacklist.txt", "w") as fp:
with open("settings/blacklist.txt", "w") as fp:
for user in mentions: for user in mentions:
for line in lines: for line in lines:
if user.id + "\n" != line: if user.id + "\n" != line:
@bot.command() @bot.command()
@checks.is_owner_or_admin() @checks.is_owner_or_admin()
async def printsettings(self, ctx, option=None): async def printsettings(self, ctx, option=None):
"OWNER OR ADMIN ONLY: Prints the servers config file."
"OWNER OR ADMIN ONLY: Prints the servers settings file."
self.serverconfig = self.con.load_config() self.serverconfig = self.con.load_config()
config = self.serverconfig[str(ctx.guild.id)] config = self.serverconfig[str(ctx.guild.id)]
em = discord.Embed(colour=0xDEADBF) em = discord.Embed(colour=0xDEADBF)

+ 0
- 92
config/server_config.py View File

import json

class ServerConfig():
def __init__(self):
# Admin role is how it is because of how I print out settings. Touch it and it will break that command.
self.servers_template = {
"example": {
"greets": {
"enabled": 0,
"welcome-channel": "",
"member-role": "",
"custom-message": "",
"default-message": "Be sure to read the rules."
},
"goodbyes": {
"enabled": 0,
"goodbye-channel": "",
},
"self_assign": {
"enabled": 0,
"roles": []
},
"twitch": {
"enabled": 0,
"channel": "",
"whitelist": {
"enabled": 0,
"list": []
}
},
"nsfw": {
"enabled": 0,
"channels": [],
"blacklist": []
},
"perm_roles": {
"admin": [],
"mod":[]
},
"custom_commands": {
"0": {},
"1": {}
},
"gss":{
"log_channel": "",
"required_days": "",
"required_score": "",
},
"warnings": {},
"is_anal": {"y/n": 0}
}
}
self.servers = self.load_config()
self.delete_after = 20

def load_config(self):
with open('config/servers.json', 'r') as config_file:
return json.load(config_file)

def update_config(self, config):
with open('config/servers.json', 'w') as conf_file:
json.dump(config, conf_file)

def error_check(self, servers):
for server in servers:
# Server ID needs to be made a string for this statement because keys have to be strings in JSON. Which is annoying now we use int for ids.
server_id = str(server.id)
if str(server_id) not in self.servers:
self.servers[server_id] = self.servers_template["example"]
self.update_config(self.servers)
print(
"WARNING: The config file for {} was not found. A template has been loaded and saved. All cogs are turned off by default.".format(
server.name.upper()))
else:
for cog_setting in self.servers_template["example"]:
if cog_setting not in self.servers[server_id]:
self.servers[server_id][cog_setting] = self.servers_template["example"][
cog_setting]
self.update_config(self.servers)
print(
"WARNING: The config file for {} was missing the {} cog. This has been fixed with the template version. It is disabled by default.".format(
server.name.upper(), cog_setting.upper()))
for setting in self.servers_template["example"][cog_setting]:
if setting not in self.servers[server_id][cog_setting]:
self.servers[server_id][cog_setting][setting] = self.servers_template["example"][
cog_setting][setting]
self.update_config(self.servers)
print(
"WARNING: The config file for {} was missing the {} setting in the {} cog. This has been fixed with the template version. It is disabled by default.".format(
server.name.upper(), setting.upper(), cog_setting.upper()))

print("")

+ 6
- 6
main.py View File

import datetime import datetime
import discord import discord
from discord.ext import commands from discord.ext import commands
import load_config
from config.server_config import ServerConfig
from Roxbot import load_config
from Roxbot.settings.guild_settings import ServerConfig




# Sets up Logging that discord.py does on its own # Sets up Logging that discord.py does on its own
) )


def blacklisted(user): def blacklisted(user):
with open("config/blacklist.txt", "r") as fp:
with open("settings/blacklist.txt", "r") as fp:
for line in fp.readlines(): for line in fp.readlines():
if user.id+"\n" == line: if user.id+"\n" == line:
return True return True
"PREFERENCE FILE MISSING. Something has gone wrong. Please make sure there is a file called 'preferences.ini' in the settings folder") "PREFERENCE FILE MISSING. Something has gone wrong. Please make sure there is a file called 'preferences.ini' in the settings folder")
exit(0) exit(0)


if not os.path.isfile("config/servers.json"):
with open("config/servers.json", "w+") as fp:
if not os.path.isfile("settings/servers.json"):
with open("settings/servers.json", "w+") as fp:
fp.write("{}") fp.write("{}")


start_time = time.time() start_time = time.time()
bot.load_extension("config.settings")
bot.load_extension("settings.settings")
bot.load_extension("err_handle") bot.load_extension("err_handle")
bot.run(load_config.token) bot.run(load_config.token)

Loading…
Cancel
Save