Skip to content
This repository has been archived by the owner on Mar 15, 2022. It is now read-only.

Commit

Permalink
updates and skyblock intergration!
Browse files Browse the repository at this point in the history
  • Loading branch information
jake committed Jul 29, 2021
1 parent 99d160e commit 5ae396a
Show file tree
Hide file tree
Showing 16 changed files with 1,388 additions and 138 deletions.
59 changes: 42 additions & 17 deletions cogs/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
import logging
import time
import aiohttp
from discord.ext.commands import ExtensionNotLoaded
from jishaku.models import copy_context_with

import discord
import importlib
import os
Expand All @@ -11,16 +14,33 @@
from utils import permissions, default, http
from io import BytesIO
from cogs.mod import BanUser, MemberID

on = False


class Admin(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.config = default.config()
self._last_result = None

@commands.command()
@commands.check(permissions.is_owner)
async def update(self, ctx):
sh = "jsk sh"

git = f"{sh} git pull"
update = f"{sh} make update"

git_command_ctx = await copy_context_with(
ctx, content=ctx.prefix + git
)
update_command_ctx = await copy_context_with(
ctx, content=ctx.prefix + update
)

await git_command_ctx.command.invoke(git_command_ctx)
await update_command_ctx.command.invoke(update_command_ctx)
await self.shutdown()

@commands.command()
@commands.check(permissions.is_owner)
async def change_config_value(self, value: str, changeto: str):
Expand Down Expand Up @@ -57,6 +77,13 @@ async def users(self, ctx):
data = BytesIO(allusers.encode("utf-8"))
await ctx.send(content=f"Users", file=discord.File(data, filename=f"{default.timetext('Users')}"))

@users.error
async def users_error(self, ctx: commands.Context, error: commands.CommandError):
# if the conversion above fails for any reason, it will raise `commands.BadArgument`
# so we handle this in this error handler:
if isinstance(error, commands.BadArgument):
return await ctx.send("Couldn\'t find that user.")

@commands.command() # idk i wanted this
@commands.check(permissions.is_owner)
async def print(self, what_they_said: str):
Expand All @@ -70,13 +97,12 @@ async def say(self, ctx, *, what_to_say: str):
await ctx.send(f'{what_to_say}')

@commands.command()
@permissions.has_permissions(Manage_Server=True)
@permissions.has_permissions(manage_guild=True)
async def prefix(self, ctx, next_prefix: str):
await ctx.send("this command currently does not exist its just a placeholder")
"""
Create a new project into the projects table
:param conn:
:param project:
:return: project id
Change the value of prefix for the guild and insert it into the guilds table
@param next_prefix:
"""
"""guildid = ctx.guild.id
prefixchange = ''' INSERT INTO guilds(name,begin_date,end_date)
Expand Down Expand Up @@ -126,7 +152,7 @@ async def file_write(self, ctx, filename: str, *, everythin_else):
@commands.command(aliases=["bban"])
@commands.check(permissions.is_owner or permissions.is_mod)
async def botban(self, ctx, userid: MemberID, *, reason: str):
BanUser(ctx, userid, reason)
await BanUser(ctx, userid, reason)
await ctx.send(f"banned {userid} for {reason}")

@commands.command()
Expand Down Expand Up @@ -159,7 +185,7 @@ async def reload(self, ctx, name: str):
return await ctx.send(default.traceback_maker(e))
await ctx.send(f"Reloaded extension **{name}.py**")

@commands.command()
@commands.command(aliases=["ra"])
@commands.check(permissions.is_owner)
async def reloadall(self, ctx):
""" Reloads all extensions. """
Expand All @@ -183,7 +209,7 @@ async def reloadall(self, ctx):

await ctx.send("Successfully reloaded all extensions")

@commands.command()
@commands.command(aliases=["ru"])
@commands.check(permissions.is_owner)
async def reloadutils(self, ctx, name: str):
""" Reloads a utils module. """
Expand All @@ -209,16 +235,16 @@ async def shutdown(self, ctx):
filemode='w+')
logging.warning('Shutting down now')
await asyncio.sleep(2)
sys.exit(0)
sys.exit("Bot shut down")

@commands.command()
@commands.check(permissions.is_owner)
async def todoadd(self, ctx, *, message: str):
"""Dumps the message into todo.txt"""
todofile = open("todo.txt", "a")
todofile.write(f"\n \n **{message}** \n~ {ctx.author} ~ {ctx.message.created_at}")
await ctx.send(f'Dumping "***{message}*** " Into {todofile.name}')
todofile.close
await ctx.send(f'Dumping "**{message}** " Into {todofile.name}')
todofile.close()

@commands.command(hidden=True)
@commands.guild_only()
Expand Down Expand Up @@ -275,11 +301,11 @@ async def role(self, ctx, *, role: discord.Role = None):

if role not in ctx.message.author.roles:
await ctx.message.author.add_roles(role)
return await ctx.send("{} role has been added to {}.".format(role, ctx.message.author.mention))
return await ctx.send("**{}** role has been added to {}.".format(role, ctx.message.author.mention))

if role in ctx.message.author.roles:
await self.bot.remove_roles(role)
return await ctx.send("{} role has been removed from {}."
return await ctx.send("**{}** role has been removed from {}."
.format(role, ctx.message.author.mention))

@commands.command()
Expand Down Expand Up @@ -365,12 +391,11 @@ async def change_avatar(self, ctx, url: str = None):
except aiohttp.InvalidURL:
await ctx.send("The URL is invalid...")
except discord.InvalidArgument:
await ctx.send("This URL does not contain a useable image")
await ctx.send("This URL does not contain a usable image")
except discord.HTTPException as err:
await ctx.send(err)
except TypeError:
await ctx.send("You need to either provide an image URL or upload one with the command")


def setup(bot):
bot.add_cog(Admin(bot))
1 change: 1 addition & 0 deletions cogs/coolstuff.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from utils import default
import psutil
import os
#import dsc

class CoolStuff(commands.Cog):
def __init__(self, bot):
Expand Down
106 changes: 49 additions & 57 deletions cogs/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
from cogs.mod import BannedUsers, BannedU
from utils import default
from lib.db import db

import os
import psutil
import logging
from datetime import datetime
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from utils.vars import *

owners = default.config()["owners"]

Expand All @@ -24,19 +24,48 @@ def __init__(self, bot):
self.scheduler = AsyncIOScheduler()
self.owner_commands = 0
self.normal_commands = 0
self.logs_channel = self.bot.get_channel(self.config["edoc_logs"])
self.update_db()

def update_db(self):
db.multiexec("INSERT OR IGNORE INTO guilds (GuildID) VALUES (?)",
((guild.id,) for guild in self.bot.guilds))
for guilds in self.bot.guilds:
for users in guilds:
db.execute("INSERT OR IGNORE INTO users (UserID) VALUES (?)", users.id)
@commands.Cog.listener()
async def on_guild_join(self, guild, member):
"""guild thingos """
general = find(lambda x: x.name == 'general' or 'General', guild.text_channels)
if general and general.permissions_for(guild.me).send_messages:
wlcmchannel = general
else:
wlcmchannel = None
channel = self.bot.get_channel(wlcmchannel.id)
await channel.send("Thank you for inviting me to the server")
await channel.send("Please do ~help to get started")
annoy = member

def update_db(self):
members = self.bot.get_all_members()
for member in members:
db.execute("INSERT OR IGNORE INTO User (UserID) VALUES (?)", member.id)
for server in self.bot.guilds:
admins = None # {}
#for member in guild.members:
# if
# admins += members
inthings = [server.id, self.config["default_prefix"], server.name, admins]
db.execute("INSERT OR IGNORE INTO guilds (GuildID, Prefix, GuildName, GuildAdmins) VALUES (?, ?, ?, ?);", (tuple(inthings)))
db.commit()
print("updated db")

@commands.Cog.listener()
async def on_command_error(self, ctx, err):
if isinstance(err, commands.CommandNotFound):
embed = discord.Embed(
title='**Error!**',
description=f'The command you have requested is not found. \nPlease make sure you typed it out right',
color=colors["red"],
timestamp=ctx.message.created_at
)
embed.set_author(name='edoC')
await ctx.send(embed=embed)

if isinstance(err, errors.MissingRequiredArgument) or isinstance(err, errors.BadArgument):
helper = str(ctx.invoked_subcommand) if ctx.invoked_subcommand else str(ctx.command)
await ctx.send_help(helper)
Expand Down Expand Up @@ -64,65 +93,33 @@ async def on_command_error(self, ctx, err):
elif isinstance(err, errors.CommandNotFound):
pass

@commands.Cog.listener()
async def on_guild_join(self, guild):
"""guild thingos """
general = find(lambda x: x.name == 'general' or 'General', guild.text_channels)
if general and general.permissions_for(guild.me).send_messages:
wlcmchannel = general
else:
wlcmchannel = None
channel = self.bot.get_channel(wlcmchannel.id)
await channel.send("Thank you for inviting me to the server")
await channel.send("Please do ~help to get started")
logs = find(lambda x: x.name == 'logs', guild.text_channels)
if logs and logs.permissions_for(guild.me).send_messages:
logschannel = logs
else:
logschannel = None
admins = {}
for members in guild.members:
if members.has_permission(administrator=True):
admins += members
db.execute(
"INSERT INTO guilds VALUES (GuildID, Prefix, GuildName, LogChannel, GuildMods, GuildAdmins, WelcomeMessage, WelcomeChannel);",
(
guild.id,
self.config["default_prefix"],
guild.name,
logschannel,
None,
admins,
None,
wlcmchannel))

@commands.Cog.listener()
async def on_guild_remove(self, guild):
print(f"edoc has left {guild.name} it had {len(guild.members)}")
print(f"edoc has left {guild.name} it had {len(guild.members)} members")
# todo add a thing to remove said guild from the database after an hour

@commands.Cog.listener()
async def on_member_join(self, guild, member):
channel = guild.sys
#if not self.config[f"join_message"]:
# if not self.config[f"join_message"]:
# return
#
#try:
# try:
# to_send = sorted([chan for chan in guild.channels if
# chan.permissions_for(guild.me).send_messages and isinstance(chan, discord.TextChannel)],
# key=lambda x: x.position)[0]
#except IndexError:
# except IndexError:
# pass
#else:
# else:
# join_msg = self.config[f"join_message"]
# await to_send.send(f"{join_msg} {user.mention}")

@commands.Cog.listener()
async def on_command(self, ctx):
self.bot.check(BannedU)
self.normal_commands += 1
self.normal_commands + 1
if ctx.message.author.id in self.config[f"owners"]:
self.owner_commands += 1
self.owner_commands + 1
if ctx.author.id in BannedUsers:
blocked = True
else:
Expand All @@ -133,7 +130,7 @@ async def on_command(self, ctx):
logging.basicConfig(filename="log.log",
format='%(asctime)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p',
level=logging.DEBUG,
level=logging.INFO,
filemode='w+')
logging.info(f'{ctx.guild.name} > ') # {ctx.author} > {ctx.message.clean_content}
except AttributeError:
Expand All @@ -147,7 +144,6 @@ async def on_ready(self):
if not self.ready:
self.ready = True
self.scheduler.start()
self.update_db()

if not hasattr(self.bot, "uptime"):
self.bot.uptime = datetime.utcnow()
Expand All @@ -171,26 +167,23 @@ async def on_ready(self):
print(
f"Ready: {self.bot.user} | Total members {totalmembers} | Guild count: {len(self.bot.guilds)} | Guilds")
guilds = {}
for x in self.bot.guilds:
field = db.field("SELECT GuildId FROM 'guilds'")
field2 = db.field("SELECT GuildName FROM 'guilds'")
guilds[field2] = field
for Server in self.bot.guilds:
try:
to_send = sorted([chan for chan in Server.channels if
chan.permissions_for(Server.me).send_messages and isinstance(chan,
discord.TextChannel)],
key=lambda x: x.position)[0]
key=lambda z: z.position)[0]
except IndexError:
pass
else:
invite_link = await to_send.create_invite(max_uses=1, unique=False, temporary=True)
if Server.id in guilds:
verified: bool = True
else:
verified = False
verified: bool = False
gprefix = db.field('SELECT Prefix FROM guilds WHERE GuildID = ?', Server.id)
print(
f"{Server.id} ~ {Server} ~ {Server.owner} ~ {Server.member_count} ~ {invite_link} ~ System broken rn")
f"{Server.id} ~ {Server} ~ {Server.owner} ~ {Server.member_count} ~ {invite_link} ~ Prefix {gprefix}")
else:
print(f"{self.bot.user} Reconnected")
logging.log("Bot reconnected")
Expand All @@ -211,7 +204,6 @@ async def on_voice_state_update(self, member, prev, cur):
async def premium_guild_subscription(self, ctx):
await ctx.send(f"{ctx.auther} just boosted the server :party:")


def setup(bot):
bot.add_cog(Events(bot))


Loading

0 comments on commit 5ae396a

Please sign in to comment.