Initial commit

This commit is contained in:
Ryonia Coruscare 2019-05-27 18:45:09 +12:00
commit 9441e9c318
Signed by: ryonia
GPG Key ID: 5040C0F02BC53C5A
17 changed files with 3689 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
test/

27
README.md Normal file
View File

@ -0,0 +1,27 @@
# Ryo-Cogs
Cogs for Red-DiscordBot
# WARNING, NOT READY FOR USE
This cog is heavily in development.
# Installation
To install the cogs, Follow the given steps:
**Step 1** - Adding the repo.
> To add the repo, type this into the chat:
>
> ``[p]cog repo add ryo-cogs https://github.com/Ryonez/Ryo-Cogs``
>
> Then type,"I agree".
**Step 2** - Adding the cog.
> To add the cog, type this into the chat:
>
> ``[p]cog install ryo-cogs [cog_name]``
>
> If it has any library dependencies, type ``pip3 install [library_name]`` in git.
>
> Once the module has loaded up, type yes.
# Feature Requests
[![Feature Requests](http://feathub.com/Ryonez/ryo-cogs?format=svg)](http://feathub.com/Ryonez/ryo-cogs)

228
antiraid/antiraid.py Normal file
View File

@ -0,0 +1,228 @@
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from collections import deque, defaultdict
from __main__ import send_cmd_help, settings
from .utils import checks
from datetime import datetime as dt, timedelta
import discord
import os
import copy
default_settings = {
"anti-log" : None,
"slowmode_channels" : []
}
class Antiraid:
'''Antiraid toolkit.'''
def __init__(self, bot):
self.bot = bot
settings = dataIO.load_json("data/antiraid/settings.json")
self.settings = defaultdict(lambda: default_settings.copy(), settings)
self.sm_cache = {}
@commands.group(pass_context=True, no_pm=True)
@checks.serverowner_or_permissions(administrator=True)
async def antiraid(self, ctx):
"""Antiraid settings."""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
@antiraid.group(pass_context=True, no_pm=True)
async def slowmode(self, ctx):
"""Slowmode settings.\nChannels that have slowmode enabled will delete a users messages if they posted less than 5 seconds from their last one. This inculdes messages deleted via slowmode. \nNote, any user who has the "manage_messages" for the channel set to true is exempt from being slowed."""
if ctx.invoked_subcommand is None or \
isinstance(ctx.invoked_subcommand, commands.Group):
await send_cmd_help(ctx)
return
@slowmode.command(name="list", pass_context=True, no_pm=True)
async def _slowmode_list(self, ctx):
"""List the channels currently in slowmode."""
if ctx.invoked_subcommand is None:
server = ctx.message.server
schannels = self.settings[server.id].get("slowmode_channels", [])
schannels = [discord.utils.get(server.channels, id=sc) for sc in schannels]
schannels = [sc.name for sc in schannels if sc is not None]
if schannels:
await self.bot.say("\n:eight_spoked_asterisk: The following channel(s) are in slowmode:\n\n```diff\n+ " + "\n+ ".join(schannels) + "```")
else:
await self.bot.say("There are currently no channels in slowmode.")
@slowmode.command(name="enable", pass_context=True, no_pm=True)
@checks.mod_or_permissions(manage_messages=True)
async def _slowmode_enable(self, ctx, *channel: discord.Channel):
"""Adds channels to the servers slowmode list."""
server = ctx.message.server
serverchannels = [x.id for x in server.channels]
channels = [r for r in channel if str(r.id) in serverchannels]
schannels = self.settings[server.id].get("slowmode_channels", [])
schannels = [discord.utils.get(server.channels, id=sc) for sc in schannels]
schannels = [sc.id for sc in schannels if sc is not None]
ctmp = {
"worked" : [],
"present" : [],
"noperm" : []
}
msg = "\n**Slowmode notices:**\n"
#for schannels in serverchannels:
# ctmp["listed"].append(schannels)
for channel in channels:
if channel.id in schannels:
ctmp["present"].append(channel.name)
elif channel.permissions_for(server.me).manage_messages == True:
self.settings[server.id]["slowmode_channels"].append(channel.id)
ctmp["worked"].append(channel.name)
else:
ctmp["noperm"].append(channel.name)
self.save()
if ctmp["worked"]:
msg += "\n:white_check_mark: The following channel(s) are now in slowmode:\n\n```diff\n+ " + "\n+ ".join(ctmp["worked"]) + "```"
if ctmp["present"]:
msg += "\n:eight_spoked_asterisk: The following channel(s) are already in slowmode:\n\n```diff\n+ " + "\n+ ".join(ctmp["present"]) + "```"
if ctmp["noperm"]:
msg += "\n:anger:I do not have the perms to add the following channel(s) you gave me! These are not in slowmode!:anger:\n\n```diff\n- " + "\n- ".join(ctmp["noperm"]) + "```"
await self.bot.say(msg)
@slowmode.command(name="disable", pass_context=True, no_pm=True)
@checks.mod_or_permissions(manage_messages=True)
async def _slowmode_disable(self, ctx, *channel: discord.Channel):
"""Removes channels from the servers slowmode list."""
server = ctx.message.server
serverchannels = [x.id for x in server.channels]
channels = [r for r in channel if str(r.id) in serverchannels]
schannels = self.settings[server.id].get("slowmode_channels", [])
ctmp = {
"worked" : [],
"cleanupf" : [],
"nodata" : []
}
msg = "\n**Slowmode notices:**\n"
#for schannels in serverchannels:
# ctmp["listed"].append(schannels)
for channel in channels:
try:
self.settings[server.id]["slowmode_channels"].remove(channel.id)
ctmp["worked"].append(channel.name)
except ValueError:
ctmp["nodata"].append(channel.name)
#Check for and clean channals that no longer exist
for c in schannels:
if c not in serverchannels:
try:
self.settings[server.id]["slowmode_channels"].remove(c)
except ValueError:
ctmp["cleanupf"].append(c)
self.save()
if ctmp["worked"]:
msg += "\n:white_check_mark: The following channel(s) are no longer in slowmode:\n\n```diff\n+ " + "\n+ ".join(ctmp["worked"]) + "```"
if ctmp["nodata"]:
msg += "\n:eight_spoked_asterisk: The following channel(s) weren't in slowmode, no changes needed:\n\n```diff\n+ " + "\n+ ".join(ctmp["nodata"]) + "```"
if ctmp["cleanupf"]:
msg += "\n:exclamation: There was and issue cleaning while preforming a self cleanup! This won't affect the anti raid system, but please contact my owner with the follow data so he can take care of it, thank you!\n\n```diff\n- " + "\n- ".join(ctmp["cleanupf"]) + "```"
await self.bot.say(msg)
async def check_slowmode(self, message):
server = message.server
channel = message.channel
author = message.author
ts = message.timestamp
if server.id not in self.settings:
return False
if channel.id in self.settings[server.id]["slowmode_channels"]:
if channel.id not in self.sm_cache:
self.sm_cache[channel.id] = {}
self.sm_cache[channel.id]["npermsc"] = 0
if channel.permissions_for(author).manage_messages == True:
return False
if channel.permissions_for(server.me).manage_messages == False:
if self.sm_cache[channel.id]["npermsc"] == 0:
await self.bot.send_message(channel, "\n**Slowmode notices:**\n:anger: I no longer have the perms to keep this channel in slowmode! Please restore the manage_messages perm to me, or remove this channel from slowmode!:anger:")
self.sm_cache[channel.id]["npermsc"] += 1
return False
elif self.sm_cache[channel.id]["npermsc"] == 10:
self.sm_cache[channel.id]["npermsc"] = 0
return False
else:
self.sm_cache[channel.id]["npermsc"] += 1
return False
if author.id not in self.sm_cache[channel.id]:
self.sm_cache[channel.id][author.id] = {}
data = {}
data["LastMsgTime"] = ts
data["Counter"] = 0
self.sm_cache[channel.id][author.id] = data
return False
data = self.sm_cache[channel.id][author.id]
LastMsgTime = data["LastMsgTime"]
if (ts - data["LastMsgTime"]) < timedelta(seconds = 5):
try:
await self.bot.delete_message(message)
data["Counter"] += 1
if data["Counter"] == 3:
msg = "\n:no_entry:**Slowmode notices**:no_entry: \n ```diff\n Hold your horses!\n- This channel is in slowmode! Please wait 5 seconds between sending messages.\n Thank you!```\n{}".format(author.mention)
await self.bot.send_message(channel, msg)
data["LastMsgTime"] = ts
self.sm_cache[channel.id][author.id] = data
return True
except:
pass
else:
data["LastMsgTime"] = ts
data["Counter"] = 0
self.sm_cache[channel.id][author.id] = data
return False
async def on_message(self, message):
if message.channel.is_private or self.bot.user == message.author \
or not isinstance(message.author, discord.Member):
return
# elif self.is_mod_or_superior(message):
# return
await self.check_slowmode(message)
def save(self):
dataIO.save_json("data/antiraid/settings.json", self.settings)
def check_folder():
if not os.path.exists('data/antiraid'):
print('Creating data/antiraid folder...')
os.makedirs('data/antiraid')
def check_files():
ignore_list = {"SERVERS": [], "CHANNELS": []}
files = {
"settings.json" : {}
}
for filename, value in files.items():
if not os.path.isfile("data/antiraid/{}".format(filename)):
print("Creating empty {}".format(filename))
dataIO.save_json("data/antiraid/{}".format(filename), value)
def setup(bot):
check_folder()
check_files()
n = Antiraid(bot)
bot.add_cog(n)

7
antiraid/info.json Normal file
View File

@ -0,0 +1,7 @@
{
"AUTHOR" : "Ryonez",
"NAME" : "antiraid",
"SHORT" : "antiraid tools.",
"DESCRIPTION" : "Collection of tools to fight against raids.",
"TAGS": ["antiraid", "member", "tools", "slowmode"]
}

358
greeter/greeter.py Normal file
View File

@ -0,0 +1,358 @@
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from __main__ import send_cmd_help, settings
from .utils import checks
import datetime
import discord
import os
import logging
from collections import defaultdict
import asyncio
server_template = {
"greeterroleid" : None,
"memberroleid" : None,
"greetlogchid" : None,
"greetchannelid" : None,
"removetriggercmd" : False,
"enabled" : False
}
class Greeter:
def __init__(self, bot):
self.bot = bot
setpath = os.path.join('data', 'greeter', 'settings.json')
settings = dataIO.load_json(setpath)
self.settings = defaultdict(lambda: server_template.copy(), settings)
@commands.command(pass_context=True, no_pm=True)
async def greet(self, ctx, user: discord.User, user2: discord.User = None):
"""The greeter command, pass a user to greet someone into the server. If you pass a second user, the log shows them as being related accounts.\ni.e `[p]greet @user1 @user2\nYou must has either the greeter role, or manage_roles perm to use this.`"""
server = ctx.message.server
author = ctx.message.author
if self.settings[server.id].get("enabled"):
grole = discord.utils.get(server.roles, id=self.settings[server.id].get("greeterroleid"))
mrole = discord.utils.get(server.roles, id=self.settings[server.id].get("memberroleid"))
greetch = discord.utils.get(server.channels, id=self.settings[server.id].get("greetchannelid"))
clrcmd = self.settings[server.id].get("removetriggercmd")
if greetch is not None and ctx.message.channel is not greetch:
return
if self._hasrole_(author, grole) or ctx.message.channel.permissions_for(author).manage_roles:
timestamp = ctx.message.timestamp
if self._hasrole_(user, mrole):
wtfemoji = discord.utils.get(self.bot.get_all_emojis(), id="330424102915407872").url
embed = discord.Embed()
embed.colour = discord.Colour(0x0F71B5)
embed.description = "What you playing at {}?".format(author.mention)
name = "{} is already a member!".format(user.name)
embed.set_thumbnail(url = wtfemoji)
embed.set_author(name=name)
embed.set_footer(text = "This message will self delete in 30 seconds")
msg = await self.bot.say(embed = embed)
await asyncio.sleep(30)
await self.bot.delete_message(msg)
else:
try:
if user2 is None:
await self.bot.add_roles(user, mrole)
await self._greetlogger_("Success", timestamp, server, author, user, None, mrole)
else:
await self.bot.add_roles(user, mrole)
await self._greetlogger_("Success - Linked", timestamp, server, author, user, user2, mrole)
except discord.Forbidden:
await self._greetlogger_("Forbidden", timestamp, server, author, user, None, mrole)
if clrcmd:
await asyncio.sleep(30)
await self.bot.delete_message(ctx.message)
@commands.group(pass_context=True, no_pm=True)
@checks.admin_or_permissions(administrator=True)
async def greetset(self, ctx):
"""Settings for greeter. Having the greeter role, member role and log channel set is required for greet to work fully."""
if ctx.invoked_subcommand is None:
await send_cmd_help(ctx)
@greetset.command(name="grole", pass_context=True, no_pm=True)
@checks.admin_or_permissions(administrator=True)
async def _grole_(self, ctx, role: discord.Role):
"""Sets the greeter role for the server. You can either mention a role, or give me a role ID.\n [p]greetset mrole @user"""
server = ctx.message.server
self.settings[server.id]["greeterroleid"] = role.id
self.save()
embed = discord.Embed()
embed.colour = discord.Colour.green()
embed.description = "{} has been saved as the greeter role. Please note users with this role will be able to add the specified member role even if they don't have the perms to when greeter is enabled. You've been warned.".format(role.mention)
name = "The greeter role was succesfully set."
embed.set_author(name=name, icon_url="https://i.imgur.com/Kw0C9gK.png")
await self.bot.say(embed = embed)
@greetset.command(name="mrole", pass_context=True, no_pm=True)
@checks.admin_or_permissions(administrator=True)
async def _mrole_(self, ctx, role: discord.Role):
"""Sets the member role for the server. You can either mention a role, or give me a role ID.\n [p]greetset mrole @user"""
server = ctx.message.server
self.settings[server.id]["memberroleid"] = role.id
self.save()
embed = discord.Embed()
embed.colour = discord.Colour.green()
embed.description = "{} has been saved as the member role. Please note users with the greeter role will be able to add the this role to others when greeter is enabled.".format(role.mention)
name = "The member role was succesfully set."
embed.set_author(name=name, icon_url="https://i.imgur.com/Kw0C9gK.png")
await self.bot.say(embed = embed)
@greetset.command(name="cleanupcmd", pass_context=True, no_pm=True)
@checks.admin_or_permissions(administrator=True)
async def _cleanupcmd_(self, ctx):
"""Toggles weather the bot removes successfully triggered greet commands from greeters. Delays 30 seconds before doing so. \n [p]greetset cleanupcmd"""
server = ctx.message.server
clrcmd = self.settings[server.id].get("removetriggercmd")
onemoji = discord.utils.get(self.bot.get_all_emojis(), id="330419505589256192").url
offemoji = discord.utils.get(self.bot.get_all_emojis(), id="330419505563959296").url
embed = discord.Embed()
embed.colour = discord.Colour.green()
if clrcmd is True:
clrcmd = False
embed.description = "Successfully triggered greet commands will not be deleted."
embed.set_author(name="Greet command cleanup has been toggled off.", icon_url=offemoji)
embed.colour = discord.Colour(0xEA2011)
else:
clrcmd = True
embed.description = "Successfully triggered greet commands will be deleted."
embed.set_author(name="Greet command cleanup has been toggled on.", icon_url=onemoji)
embed.colour = discord.Colour.green()
self.settings[server.id]["removetriggercmd"] = clrcmd
self.save()
await self.bot.say(embed = embed)
@greetset.command(name="loggerchannel", pass_context=True, no_pm=True)
@checks.admin_or_permissions(administrator=True)
async def _logggerchannel_(self, ctx, channel: discord.Channel = None):
"""Sets the channel greeter will log to. Mention a channel with this command, or use it's ID to set it.\ni.e: [p]greetset loggerchannel #greeter-logs\n"""
server = ctx.message.server
try:
embed = discord.Embed()
embed.colour = discord.Colour.green()
embed.description = "Testing to see if I can log here. If you see this it worked!"
name = "Testing logging."
embed.set_author(name=name, icon_url="https://i.imgur.com/z4qtYxT.png")
embed.set_footer(text = "This test message will self delete in 30 seconds")
test = await self.bot.send_message(destination = channel, embed = embed)
#Passed
self.settings[server.id]["greetlogchid"] = channel.id
self.save()
embed = discord.Embed()
embed.colour = discord.Colour.green()
embed.description = "{} has been saved as the channel greeter will log to.".format(channel.mention)
name = "The log was succesfully set."
embed.set_author(name=name, icon_url="https://i.imgur.com/Kw0C9gK.png")
await self.bot.say(embed = embed)
await asyncio.sleep(30)
await self.bot.delete_message(test)
except discord.Forbidden:
embed = discord.Embed()
embed.colour = discord.Colour.red()
embed.description = "I do have permission to send messages to that channel (server={}, channel={})".format(server.id, channel.id)
embed.set_thumbnail(url="https://i.imgur.com/zNU3Y9m.png")
name = "The logging channel was not set!"
embed.set_author(name=name, icon_url="https://i.imgur.com/zNU3Y9m.png")
await self.bot.say(embed = embed)
@greetset.command(name="greetchannel", pass_context=True, no_pm=True)
@checks.admin_or_permissions(administrator=True)
async def _greetchannel_(self, ctx, channel: discord.Channel = None):
"""Sets the channel greeters have to greet from, a channel tha `[p]greet` is locked to. Mention a channel with this command, or use it's ID to set it.\ni.e: [p]greetset greetchannel #greeter-logs\nIf no channel is given, the command is unlocked for use anywhere on the server."""
server = ctx.message.server
if channel is None:
self.settings[server.id]["greetchannelid"] = None
self.save()
embed = discord.Embed()
embed.colour = discord.Colour.green()
embed.description = "The greeter channel has been cleared. The greet command can be used anywhere on the server."
name = "The greeter channel was succesfully cleared."
embed.set_author(name=name, icon_url="https://i.imgur.com/Kw0C9gK.png")
await self.bot.say(embed = embed)
return
try:
embed = discord.Embed()
embed.colour = discord.Colour.green()
embed.description = "Testing to see if I can post here. If you see this it worked!"
name = "Testing greet channel."
embed.set_author(name=name, icon_url="https://i.imgur.com/z4qtYxT.png")
embed.set_footer(text = "This test message will self delete in 30 seconds")
test = await self.bot.send_message(destination = channel, embed = embed)
#Passed
self.settings[server.id]["greetchannelid"] = channel.id
self.save()
embed = discord.Embed()
embed.colour = discord.Colour.green()
embed.description = "{} has been saved as the greeter channel.".format(channel.mention)
name = "The greeter channel was succesfully set."
embed.set_author(name=name, icon_url="https://i.imgur.com/Kw0C9gK.png")
await self.bot.say(embed = embed)
await asyncio.sleep(30)
await self.bot.delete_message(test)
except discord.Forbidden:
embed = discord.Embed()
embed.colour = discord.Colour.red()
embed.description = "I do have permission to send messages to that channel (server={}, channel={})".format(server.id, channel.id)
embed.set_thumbnail(url="https://i.imgur.com/zNU3Y9m.png")
name = "The greeter channel was not set!"
embed.set_author(name=name, icon_url="https://i.imgur.com/zNU3Y9m.png")
await self.bot.say(embed = embed)
@greetset.command(name="greeter", pass_context=True, no_pm=True)
@checks.admin_or_permissions(administrator=True)
async def _greeter_(self, ctx, switch):
"""Enable or disable the greeter cog for the server.\n [p]greetset swtich [enabled/disable]"""
server = ctx.message.server
onemoji = discord.utils.get(self.bot.get_all_emojis(), id="330419505589256192").url
offemoji = discord.utils.get(self.bot.get_all_emojis(), id="330419505563959296").url
embed = discord.Embed()
embed.colour = discord.Colour(0xEA2011)
if switch == "enable":
enabled = True
embed.description = "The greeter cog has been enabled for this server."
embed.set_author(name="Greeter has been toggled on.", icon_url=onemoji)
embed.colour = discord.Colour.green()
elif switch == "disable":
enabled = False
embed.description = "The greeter cog has been disabled for this server."
embed.set_author(name="Greeter has been toggled off.", icon_url=offemoji)
embed.colour = discord.Colour(0xEA2011)
self.settings[server.id]["enabled"] = enabled
self.save()
await self.bot.say(embed = embed)
def _hasrole_(self, user, role):
# Check if the given user has a role.
for r in user.roles:
if r is role:
return True
return False
async def _greetlogger_(self, status, timestamp, server, greetuser = None, newuser = None, linkuser = None, mrole = None):
# Logging for the greeter cog.
logch = discord.utils.get(server.channels, id=self.settings[server.id].get("greetlogchid"))
if status == "Success":
embed = discord.Embed()
embed.colour = discord.Colour.green()
embed.description = "{} was given the {} role by {}\n\n {}'s ID: `{}`".format(newuser.mention, mrole.mention, greetuser.mention, newuser.name, newuser.id)
embed.timestamp = timestamp
name = "{} greeted {}".format(greetuser.name, newuser.name)
embed.set_author(name=name, icon_url="https://i.imgur.com/Kw0C9gK.png")
embed.set_thumbnail(url = newuser.avatar_url or newuser.default_avatar_url)
embed.set_footer(text = "Greeter {}'s ID: `{}`".format(greetuser.name, greetuser.id))
try:
await self.bot.send_message(destination = logch, embed = embed)
except discord.Forbidden:
self.bot.logger.warning(
"Did not have permission to send message to logging channel (server={}, channel={})".format(logch.server.id, logch.id)
)
elif status == "Success - Linked":
embed = discord.Embed()
embed.colour = discord.Colour.green()
embed.description = "{} was given the {} role by {}\n\n {}'s ID: `{}`".format(newuser.mention, mrole.mention, greetuser.mention, newuser.name, newuser.id)
embed.timestamp = timestamp
name = "{} greeted {}".format(greetuser.name, newuser.name)
embed.add_field(name="Linked Account:",
value="This Member is related to: {}\n{}'s ID: `{}`".format(linkuser.mention, linkuser.name, linkuser.id),
inline=False)
embed.set_author(name=name, icon_url="https://i.imgur.com/Kw0C9gK.png")
embed.set_thumbnail(url = newuser.avatar_url or newuser.default_avatar_url)
embed.set_footer(text = "Greeter {}'s ID: `{}`".format(greetuser.name, greetuser.id))
try:
await self.bot.send_message(destination = logch, embed = embed)
except discord.Forbidden:
self.bot.logger.warning(
"Did not have permission to send message to logging channel (server={}, channel={})".format(logch.server.id, logch.id)
)
elif status == "Forbidden":
embed = discord.Embed()
embed.colour = discord.Colour(0xEA2011)
embed.description = "I failed to give {} the {} role as requested by {}. Do I still have the mangage_roles perm, and is the member role under my highest role?\n\n {}'s ID: `{}`".format(newuser.mention, mrole.mention, greetuser.mention, newuser.name, newuser.id)
embed.timestamp = timestamp
embed.set_thumbnail(url="https://i.imgur.com/zNU3Y9m.png")
name = "{} attempted to welcome {}.".format(greetuser.name, newuser.name)
embed.set_author(name=name, icon_url="https://i.imgur.com/zNU3Y9m.png")
embed.set_footer(text = "Greeter {}'s ID: `{}`".format(greetuser.name, greetuser.id))
try:
await self.bot.send_message(destination = logch, embed = embed)
except discord.Forbidden:
self.bot.logger.warning(
"Did not have permission to send message to logging channel (server={}, channel={})".format(logch.server.id, logch.id)
)
def save(self):
setpath = os.path.join('data', 'greeter', 'settings.json')
dataIO.save_json(setpath, self.settings)
def check_folder():
path = os.path.join('data', 'greeter')
if not os.path.exists(path):
print('Creating ' + path + '...')
os.makedirs(path)
def check_files():
files = {
"settings.json": {}
}
datapath = os.path.join('data', 'greeter')
for filename, value in files.items():
path = os.path.join(datapath, filename)
if not os.path.isfile(path):
print("Path: {}".format(path))
print("Creating empty {}".format(filename))
dataIO.save_json(path, value)
def setup(bot):
check_folder()
check_files()
n = Greeter(bot)
bot.add_cog(n)

7
greeter/info.json Normal file
View File

@ -0,0 +1,7 @@
{
"AUTHOR" : "Ryonez",
"NAME" : "greeter",
"SHORT" : "greeter",
"DESCRIPTION" : "A greeter system that allows those with a specifed greeter role to give others another specified role ",
"TAGS": ["greeter", "member", "administration"]
}

7
lockdown/info.json Normal file
View File

@ -0,0 +1,7 @@
{
"AUTHOR" : "Ryonez",
"NAME" : "lockdown",
"SHORT" : "lockdown",
"DESCRIPTION" : "Lockdown lets you set channel overides to stop anyone speaking on text or voice channels, and even lockdown the entire server. Only Administrators can speak while a lockdown is in effect.",
"TAGS": ["lockdown", "server", "tools", "crowd control"]
}

195
lockdown/lockdown.py Normal file
View File

@ -0,0 +1,195 @@
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from __main__ import send_cmd_help, settings
from .utils import checks
import datetime
import discord
import os
from collections import defaultdict
server_template = {
"serverlockdown" : False,
"channels" : {}
}
channel_template = {}
channeloverride_template = {
"type": None,
"overrides": {}
}
class Lockdown:
"""Lockdown"""
def __init__(self, bot):
self.bot = bot
setpath = os.path.join('data', 'lockdown', 'locks.json')
locks = dataIO.load_json(setpath)
self.locks = defaultdict(lambda: server_template.copy(), locks)
@commands.group(pass_context=True, no_pm=True)
@checks.admin_or_permissions(administrator=True)
async def lockdown(self, ctx):
"""lockdown."""
if ctx.invoked_subcommand is None:
await ctx.invoke(self._lockdownchannel_, channel=ctx.message.channel)
@lockdown.command(name="channel", pass_context=True, no_pm=True)
@checks.admin_or_permissions(administrator=True)
async def _lockdownchannel_(self, ctx, channel: discord.Channel):
"""Locks the channel so only users with the Administrator perm can talk."""
if channel is None:
channel = ctx.message.channel
server = ctx.message.server
if self.locks[server.id]["channels"].get(channel.id) is None:
status = await self.bot.say("Lockdown initiating, one moment!")
await self._savechanneloverrides_(channel)
await self._lockchannel_(channel)
lockedmsg = discord.Embed(colour=discord.Colour(0xFF0000),
timestamp=datetime.datetime.today(),
description="`{}` has been locked!\n\nOnly Administrators can speak.".format(channel.name))
lockedmsg.set_author(name="Channel Lockdown")
lockedmsg.set_thumbnail(url="https://i.imgur.com/zNU3Y9m.png")
await self.bot.delete_message(status)
if channel != ctx.message.channel and channel.type.name != "voice":
await self.bot.send_message(destination = channel, embed = lockedmsg)
await self.bot.say(embed = lockedmsg)
else:
status = await self.bot.say("Lockdown lifting, one moment!")
await self._unlockchannel_(channel)
unlockedmsg = discord.Embed(colour=discord.Colour(0x2bdb25),
timestamp=datetime.datetime.today(),
description="`{}` has been unlocked!\n\nNormal perms have been restored.".format(channel.name))
unlockedmsg.set_author(name="Channel Lockdown Lifted")
unlockedmsg.set_thumbnail(url="https://i.imgur.com/Kw0C9gK.png")
await self.bot.delete_message(status)
if channel != ctx.message.channel and channel.type.name != "voice":
await self.bot.send_message(destination = channel, embed = unlockedmsg)
await self.bot.say(embed = unlockedmsg)
@lockdown.command(name="server", pass_context=True, no_pm=True)
@checks.admin_or_permissions(administrator=True)
async def _lockdownserver_(self, ctx):
"""Locks the entire server so only users with the Administrator perm can talk."""
server = ctx.message.server
if self.locks[server.id].get("serverlockdown") is False:
status = await self.bot.say("**Server Lockdown** initiating, one moment!")
for c in server.channels:
if self.locks[server.id]["channels"].get(c.id) is None:
await self._savechanneloverrides_(c)
await self._lockchannel_(c)
self.locks[server.id]["serverlockdown"] = True
self.save()
lockedmsg = discord.Embed(colour=discord.Colour(0xFF0000),
timestamp=datetime.datetime.today(),
description="`{}` has been locked!\n\nOnly Administrators can speak on this server.".format(
ctx.message.server.name))
lockedmsg.set_author(name="SERVER LOCKDOWN")
lockedmsg.set_thumbnail(url="https://i.imgur.com/zNU3Y9m.png")
await self.bot.delete_message(status)
await self.bot.say(embed=lockedmsg)
else:
status = await self.bot.say("**Server Lockdown** lifting, one moment!")
for c in server.channels:
await self._unlockchannel_(c)
self.save
unlockedmsg = discord.Embed(colour=discord.Colour(0x2bdb25),
timestamp=datetime.datetime.today(),
description="`{}` has been unlocked!\n\nNormal perms have been restored to all channels.".format(ctx.message.server.name))
unlockedmsg.set_author(name="Server Lockdown Lifted")
unlockedmsg.set_thumbnail(url="https://i.imgur.com/Kw0C9gK.png")
await self.bot.delete_message(status)
await self.bot.say(embed=unlockedmsg)
async def _savechanneloverrides_(self, channel):
#Saves the current channel overrides.
server = channel.server
savedserver = defaultdict(lambda: server_template.copy(),
self.locks[server.id])
savedchannels = defaultdict(lambda: channel_template.copy(),
savedserver["channels"])
savedchannel = defaultdict(lambda: channel_template.copy(), savedchannels[channel.id])
try:
for o in channel.overwrites:
current_overrides = defaultdict(lambda: channeloverride_template.copy(),
savedchannel[o[0].id])
if isinstance(o[0], discord.Role):
current_overrides["type"] = 'Role'
elif isinstance(o[0], discord.Member):
current_overrides["type"] = 'Member'
current_overrides["overrides"] = o[1]._values
savedchannels[channel.id][o[0].id] = current_overrides
except discord.Forbidden:
return "forbidden"
savedserver["channels"] = savedchannels
self.locks[server.id] = savedserver
self.save()
return None
async def _lockchannel_(self, channel):
for o in channel.overwrites:
overwrite = channel.overwrites_for(o[0])
if channel.type.name == 'text':
overwrite.send_messages = False
if channel.type.name == 'voice':
overwrite.speak = False
try:
await self.bot.edit_channel_permissions(channel, o[0], overwrite)
except discord.Forbidden:
return False
return True
async def _unlockchannel_(self, channel):
server = channel.server
for o in channel.overwrites:
soverride = self.locks[server.id]["channels"][channel.id][o[0].id].get("overrides")
overwrite = channel.overwrites_for(o[0])
if soverride is not None:
if channel.type.name == 'text':
setattr(overwrite, "send_messages", soverride.get("send_messages"))
if channel.type.name == 'voice':
setattr(overwrite, "speak", soverride.get("speak"))
try:
await self.bot.edit_channel_permissions(channel, o[0], overwrite)
except discord.Forbidden:
return False
del self.locks[server.id]["channels"][channel.id]
if len(self.locks[server.id]["channels"]) == 0:
del self.locks[server.id]
self.save()
return True
def save(self):
setpath = os.path.join('data', 'lockdown', 'locks.json')
dataIO.save_json(setpath, self.locks)
def check_folder():
path = os.path.join('data', 'lockdown')
if not os.path.exists(path):
print('Creating ' + path + '...')
os.makedirs(path)
def check_files():
files = {
"locks.json": {}
}
datapath = os.path.join('data', 'lockdown')
for filename, value in files.items():
path = os.path.join(datapath, filename)
if not os.path.isfile(path):
print("Path: {}".format(path))
print("Creating empty {}".format(filename))
dataIO.save_json(path, value)
def setup(bot):
check_folder()
check_files()
n = Lockdown(bot)
bot.add_cog(n)

7
lsar/info.json Normal file
View File

@ -0,0 +1,7 @@
{
"AUTHOR" : "Ryonez",
"NAME" : "lsar",
"SHORT" : "lsar",
"DESCRIPTION" : "A pretty way to show self assignable roles.",
"TAGS": ["tools", "roles"]
}

52
lsar/lsar.py Normal file
View File

@ -0,0 +1,52 @@
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from __main__ import send_cmd_help, settings
from .utils import checks
import datetime
import discord
import os
from collections import defaultdict
class lsar:
'''A pretty way to show self assignable roles.'''
def __init__(self, bot):
self.bot = bot
def _get_selfrole_names(self, server):
self._settings = dataIO.load_json('data/admin/settings.json')
self._settable_roles = self._settings.get("ROLES", {})
if server.id not in self._settable_roles:
return None
else:
return self._settable_roles[server.id]
@commands.command(no_pm=True, pass_context=True)
async def lsar(self, ctx):
"""Views all current roles you can assign to yourself.
Configurable using `adminset`"""
server = ctx.message.server
timestamp = datetime.datetime.today()
#The selfrole in admin has a bug. You can remove all roles but the server will remain on the selfrole list. The or check corrects this for us.
if self._get_selfrole_names(ctx.message.server) is None or not self._get_selfrole_names(ctx.message.server):
embedmsg = discord.Embed(title="<:res1error:330424101661442050> No roles are available for you to add to yourself.",
colour=discord.Colour(0xff000),
description="This server is currently offers no roles for you to add to yourself.",
timestamp = timestamp)
else:
selfroles = self._settable_roles[server.id]
embedmsg = discord.Embed(title="<:res1hellyeah:330424103259340800> Roles are available for you to add:",
colour=discord.Colour(0x54d824),
description="You can currently give yourself:\n{}".format("\n".join(selfroles)),
timestamp = timestamp)
await self.bot.say(embed=embedmsg)
def setup(bot: commands.Bot):
bot.add_cog(lsar(bot))

7
massroles/info.json Normal file
View File

@ -0,0 +1,7 @@
{
"AUTHOR" : "Ryonez",
"NAME" : "massroles",
"SHORT" : "massroles",
"DESCRIPTION" : "Lets you give a role to a group of people who have a tageted role, or the remove a role from everyone with it.",
"TAGS": ["massroles", "member", "administration"]
}

96
massroles/massroles.py Normal file
View File

@ -0,0 +1,96 @@
from typing import List
import discord
from discord.ext import commands
from .utils import checks
class MassRoles:
'''Add roles to users in a target role(including everone)'''
def __init__(self, bot):
self.bot = bot
def _member_has_role(self, member: discord.Member, role: discord.Role):
return role in member.roles
def _get_users_with_role(self, server: discord.Server,
role: discord.Role) -> List[discord.User]:
roled = []
for member in server.members:
if self._member_has_role(member, role):
roled.append(member)
return roled
@commands.command(no_pm=True, pass_context=True, name="massaddrole", aliases=["mar"])
@checks.mod_or_permissions(administrator=True)
async def _mar(self, ctx: commands.Context,
*roles: discord.Role):
"""Start the massrole add by providing the role you want **ADDED**, then the role of the users you want it added to.
"""
server = ctx.message.server
sender = ctx.message.author
channel = ctx.message.channel
if not channel.permissions_for(server.me).manage_roles:
await self.bot.say('I don\'t have manage_roles.')
return False
await self.bot.say("Please confirm:\nThe target role is-->`" + roles[0].name + "`\nThe role being added is-->`" + roles[1].name + "`\nSay yes to continue, or aything else to escape.")
answer = await self.bot.wait_for_message(timeout=15,
author=ctx.message.author)
if answer is None:
await self.bot.say("Timed Out")
elif answer.content.lower().strip() == "yes":
addroles = self._get_users_with_role(server, roles[0])
for user in addroles:
try:
await self.bot.add_roles(user, roles[1])
except (discord.Forbidden, discord.HTTPException):
continue
await self.bot.say("Completed")
else:
await self.bot.say("Cancelled")
return False
@commands.command(no_pm=True, pass_context=True, name="massremoverole", aliases=["mrr"])
@checks.mod_or_permissions(administrator=True)
async def _mrr(self, ctx: commands.Context,
role: discord.Role):
"""Removes the traget role from any users who have it.
"""
server = ctx.message.server
sender = ctx.message.author
channel = ctx.message.channel
if not channel.permissions_for(server.me).manage_roles:
await self.bot.say('I don\'t have manage_roles.')
return False
await self.bot.say("Please confirm:\nThe role being removed is-->`" + role.name + "`\nSay yes to continue, or anything else to escape.")
answer = await self.bot.wait_for_message(timeout=15,
author=ctx.message.author)
if answer is None:
await self.bot.say("Timed Out")
elif answer.content.lower().strip() == "yes":
removerole = self._get_users_with_role(server, role)
for user in removerole:
try:
await self.bot.remove_roles(user, role)
except (discord.Forbidden, discord.HTTPException):
continue
await self.bot.say("Completed")
else:
await self.bot.say("Cancelled")
return False
def setup(bot: commands.Bot):
bot.add_cog(MassRoles(bot))

7
seen/info.json Normal file
View File

@ -0,0 +1,7 @@
{
"AUTHOR" : "Ryonez",
"NAME" : "Seen",
"SHORT" : "Check when the user was last active on a server.",
"DESCRIPTION" : "Check when the user was last active on a server.",
"TAGS": ["Seen", "member", "tools"]
}

61
seen/seen.py Normal file
View File

@ -0,0 +1,61 @@
from discord.ext import commands
from cogs.utils.dataIO import dataIO
import discord
import os
class Seen:
'''Check when someone was last seen.'''
def __init__(self, bot):
self.bot = bot
async def _get_channel(self, id):
return discord.utils.get(self.bot.get_all_channels(), id=id)
async def listener(self, message):
if not message.channel.is_private and self.bot.user.id != message.author.id:
server = message.server
channel = message.channel
author = message.author
ts = message.timestamp
filename = 'data/seen/{}/{}.json'.format(server.id, author.id)
if not os.path.exists('data/seen/{}'.format(server.id)):
os.makedirs('data/seen/{}'.format(server.id))
data = {}
data['TIMESTAMP'] = '{} {}:{}:{}'.format(ts.date(), ts.hour, ts.minute, ts.second)
data['MESSAGE'] = message.clean_content
data['NAME'] = author.display_name
data['CHANNEL'] = channel.id
dataIO.save_json(filename, data)
@commands.command(pass_context=True, no_pm=True, name='seen')
async def _seen(self, context, username: discord.Member):
'''seen <@username>'''
server = context.message.server
author = username
filename = 'data/seen/{}/{}.json'.format(server.id, author.id)
if dataIO.is_valid_json(filename):
data = dataIO.load_json(filename)
ts = data['TIMESTAMP']
last_message = data['MESSAGE']
channel = await self._get_channel(data['CHANNEL'])
em = discord.Embed(color=discord.Color.green())
#em = discord.Embed(description='\nMessage:\n```{}```'.format(last_message), color=discord.Color.green())
avatar = author.avatar_url if author.avatar else author.default_avatar_url
em.set_author(name='{} was last seen on {} UTC in #{}'.format(author.display_name, ts, channel.name), icon_url=avatar)
await self.bot.say(embed=em)
else:
message = 'I haven\'t seen {} yet.'.format(author.display_name)
await self.bot.say('{}'.format(message))
def check_folder():
if not os.path.exists('data/seen'):
print('Creating data/seen folder...')
os.makedirs('data/seen')
def setup(bot):
check_folder()
n = Seen(bot)
bot.add_listener(n.listener, 'on_message')
bot.add_cog(n)

79
seen/seen_dev.py Normal file
View File

@ -0,0 +1,79 @@
from discord.ext import commands
from cogs.utils.dataIO import dataIO
import discord
import os
import asyncio
class Seen:
'''Check when someone was last seen.'''
def __init__(self, bot):
self.bot = bot
self.seen = dataIO.load_json("data/seen/seen.json")
self.new_data = False
async def _get_channel(self, id):
return discord.utils.get(self.bot.get_all_channels(), id=id)
async def data_writer(self):
while self == self.bot.get_cog("Seen"):
if self.new_data:
await asyncio.sleep(60)
dataIO.save_json("data/seen/seen.json", self.seen)
self.new_data = False
else:
await asyncio.sleep(30)
@commands.command(pass_context=True, no_pm=True, name='seen')
async def _seen(self, context, username: discord.Member):
'''seen <@username>'''
server = context.message.server
author = username
print(True if author.id in self.seen[server.id] else False if server.id in self.seen else False)
if True if author.id in self.seen[server.id] else False if server.id in self.seen else False:
data = self.seen[server.id][author.id]
ts = data['TIMESTAMP']
channel = await self._get_channel(data['CHANNEL'])
em = discord.Embed(color=discord.Color.green())
avatar = author.avatar_url if author.avatar else author.default_avatar_url
em.set_author(name='{} was last seen on {} UTC in #{}'.format(author.display_name, ts, channel.name), icon_url=avatar)
await self.bot.say(embed=em)
else:
message = 'I haven\'t seen {} yet.'.format(author.display_name)
await self.bot.say('{}'.format(message))
async def listener(self, message):
if not message.channel.is_private and self.bot.user.id != message.author.id:
server = message.server
channel = message.channel
author = message.author
ts = message.timestamp
data = {}
data['TIMESTAMP'] = '{} {}:{}:{}'.format(ts.date(), ts.hour, ts.minute, ts.second)
data['CHANNEL'] = channel.id
if server.id not in self.seen:
self.seen[server.id] = {}
self.seen[server.id][author.id] = data
self.new_data = True
def check_folder():
if not os.path.exists('data/seen'):
print('Creating data/seen folder...')
os.makedirs('data/seen')
def check_file():
if not dataIO.is_valid_json("data/seen/seen.json"):
print("Creating seen.json...")
dataIO.save_json("data/seen/seen.json", {})
def setup(bot):
check_folder()
check_file()
n = Seen(bot)
bot.add_listener(n.listener, 'on_message')
loop = asyncio.get_event_loop()
loop.create_task(n.data_writer())
bot.add_cog(n)

7
servermerge/info.json Normal file
View File

@ -0,0 +1,7 @@
{
"AUTHOR" : "Ryonez",
"NAME" : "servermerge",
"SHORT" : "servermerge",
"DESCRIPTION" : "A cog designed to merge a sub server into a host server, For those wanting to combine servers. Can only be used if you own both servers.",
"TAGS": ["servermerge", "server", "tools", "automation"]
}

2543
servermerge/servermerge.py Normal file

File diff suppressed because it is too large Load Diff