├── FUNDING.yml ├── src ├── cogs │ ├── error_handler.py │ ├── utils │ │ ├── exceptions.py │ │ ├── data.py │ │ ├── database.py │ │ ├── customdatas.py │ │ ├── time.py │ │ ├── timer.py │ │ ├── rep.py │ │ ├── main_info.py │ │ └── mod.py │ ├── report.py │ ├── reputation.py │ ├── timer_task.py │ ├── info.py │ ├── main_logs.py │ ├── moderation.py │ ├── logs.py │ ├── general.py │ └── configuration.py ├── settings.ini ├── art_h43.txt └── main.py ├── README.md └── LICENSE /FUNDING.yml: -------------------------------------------------------------------------------- 1 | custom: ["https://www.paypal.me/octocat" 2 | -------------------------------------------------------------------------------- /src/cogs/error_handler.py: -------------------------------------------------------------------------------- 1 | '''Error handler for Missing Permisisons Bot Moderation '''' 2 | -------------------------------------------------------------------------------- /src/settings.ini: -------------------------------------------------------------------------------- 1 | [Main] 2 | Guild_ID= 3 | Prefix= 4 | Token= 5 | 6 | [Database] 7 | User= 8 | Password= 9 | Database= 10 | Host=127.0.0.1 11 | 12 | [Roles_IDs] 13 | ADM= 14 | STAFF= 15 | PREMIUM= 16 | OWNER= 17 | 18 | [Roles_Emojis] 19 | PREMIUM=1F911 20 | STAFF=1F6E0 21 | ADM=1F621 22 | OWNER=1F4A3 23 | 24 | [Roles_Levels] 25 | ADM=3 26 | STAFF=2 27 | PREMIUM=1 28 | OWNER=4 29 | 30 | [Channels_IDs] 31 | Commands= 32 | Servers= 33 | Status= 34 | Moderation= 35 | 36 | 37 | 38 | 39 | ; Levels 40 | ; 0 -> Standard 41 | ; 1 -> Premium 42 | ; 2 -> Moderator 43 | ; 3 -> Administrator 44 | ; 4 -> Owner 45 | -------------------------------------------------------------------------------- /src/cogs/utils/exceptions.py: -------------------------------------------------------------------------------- 1 | class NotFound(Exception): 2 | pass 3 | 4 | 5 | class GuildNotFound(NotFound): 6 | pass 7 | 8 | 9 | class ChannelNotFound(NotFound): 10 | pass 11 | 12 | 13 | class MemberNotFound(NotFound): 14 | pass 15 | 16 | 17 | class MuteRoleNotFound(NotFound): 18 | pass 19 | 20 | 21 | class MaximumRoles(Exception): 22 | pass 23 | 24 | 25 | class PluginError(Exception): 26 | pass 27 | 28 | 29 | class PluginDisabled(PluginError): 30 | pass 31 | 32 | 33 | class NoMessage(PluginError): 34 | pass 35 | 36 | 37 | class WrongGuild(Exception): 38 | pass 39 | -------------------------------------------------------------------------------- /src/art_h43.txt: -------------------------------------------------------------------------------- 1 | 2 | ,--, ,--, .--,-``-. 3 | ,--.'| ,--.'| / / '. 4 | ,--, | : ,--, | : / ../ ; 5 | ,---.'| : ' ,---.'| : ' \ ``\ .`- ' 6 | | | : _' | ; : | | ; \___\/ \ : 7 | : : |.' | | | : _' | \ : | 8 | | ' ' ; : : : |.' | / / / 9 | ' | .'. | | ' ' ; : \ \ \ 10 | | | : | ' \ \ .'. | ___ / : | 11 | ' : | : ; `---`: | ' / /\ / : 12 | | | ' ,/ ' ; | / ,,/ ',- . -> Made by: Fytex#4389 (Portugal) 13 | ; : ;--' | : ; \ ''\ ; Discord ID: 321346463148015626 14 | | ,/ ' ,/ \ \ .' 15 | '---' '--' `--`-,,-' -------------------------------------------------------------------------------- /src/cogs/utils/data.py: -------------------------------------------------------------------------------- 1 | from cogs.utils.database import DB 2 | 3 | 4 | class Data(DB): 5 | def __init__(self, client, record): 6 | super().__init__(client) 7 | self.enabled = record['enabled'] 8 | self.colour = record['colour'] # if no colour then it wont embed 9 | try: # avatar doesn't have title neither description 10 | self.title = record['title'] 11 | self.description = record['description'] 12 | except KeyError: 13 | pass 14 | 15 | channel_id = record['channel'] 16 | guild_id = record['guild'] 17 | 18 | self.guild = guild = client.get_guild(guild_id) 19 | 20 | self.channel = channel_id and guild.get_channel(channel_id) 21 | 22 | async def set_enabled(self, enabled: bool): 23 | self.enabled = enabled 24 | await self._send_to_db('enabled', enabled) 25 | 26 | async def set_channel(self, channel): 27 | self.channel = channel 28 | await self._send_to_db('channel', channel.id) 29 | 30 | async def set_colour(self, colour): 31 | self.colour = colour 32 | await self._send_to_db('colour', colour) 33 | 34 | async def set_title(self, title): 35 | self.title = title 36 | await self._send_to_db('title', title) 37 | 38 | async def set_description(self, description): 39 | self.description = description 40 | await self._send_to_db('description', description) 41 | -------------------------------------------------------------------------------- /src/cogs/utils/database.py: -------------------------------------------------------------------------------- 1 | class DB: 2 | def __init__(self, client): 3 | self.client = client 4 | 5 | @classmethod 6 | async def get_Data(cls, client, guild_id): 7 | query_fetch = f'SELECT * FROM {cls.db_table} WHERE guild=$1;' 8 | 9 | async with client.db.acquire() as con: 10 | record = await con.fetchrow(query_fetch, guild_id) 11 | 12 | if not record: # if no record.... just create one 13 | query_insert = f'INSERT INTO {cls.db_table} (guild) VALUES ($1)' 14 | await con.execute(query_insert, guild_id) 15 | record = await con.fetchrow(query_fetch, guild_id) 16 | 17 | return cls(client, record) 18 | 19 | async def _send_to_db(self, column, value): 20 | 21 | ''' 22 | Since each connections' query is simliar to the next one (Just change the column and the value to update) 23 | ''' 24 | 25 | query = f'UPDATE {self.db_table} SET {column}=$1 WHERE guild=$2' 26 | 27 | async with self.client.db.acquire() as con: 28 | await con.execute(query, value, self.guild.id) 29 | 30 | async def _get_from_db(self, column): 31 | 32 | ''' 33 | Since each connections' query is simliar to the next one (Just change the column to get the value) 34 | ''' 35 | 36 | query = f'SELECT {column} FROM {self.db_table} WHERE guild=$2' 37 | 38 | async with self.client.db.acquire() as con: 39 | value = await con.fetchval(query, self.guild.id) 40 | 41 | return value 42 | -------------------------------------------------------------------------------- /src/cogs/report.py: -------------------------------------------------------------------------------- 1 | import discord 2 | from discord.ext import commands 3 | from cogs.utils.customdatas import ReportLogData 4 | from cogs.utils.main_info import UserInfo 5 | from itertools import chain 6 | 7 | 8 | class Report(commands.Cog): 9 | 10 | def __init__(self, client): 11 | self.client = client 12 | 13 | async def cog_check(self, ctx): 14 | if not ctx.guild: 15 | return False 16 | admin_roles = [role for role in ctx.guild.roles if role.permissions.administrator] 17 | admin_members = {member for member in chain.from_iterable( 18 | [role.members for role in admin_roles])} 19 | 20 | return any(UserInfo(ctx.bot, user).premium for user in admin_members) 21 | 22 | async def cog_before_invoke(self, ctx): 23 | ctx.report_data = None 24 | send_msg_perm = ctx.channel.permissions_for(ctx.me).send_messages 25 | ctx.dest = ctx.channel if send_msg_perm else ctx.author 26 | 27 | @commands.command() 28 | async def report(self, ctx, member: discord.Member, *, reason): 29 | 30 | data = await ReportLogData.get_Data(self.client, ctx.guild.id) 31 | 32 | if not data.enabled or not data.description or not data.channel: 33 | return await ctx.dest.send('`Denúncias` está desativado neste servidor') 34 | 35 | if member == ctx.author: 36 | return await ctx.dest.send('Você não se pode denunciar a si próprio') 37 | 38 | logs = self.client.get_cog('Logs') 39 | 40 | await logs.report_log(member, ctx.author, reason, data=data) 41 | await ctx.author.send(f'**Denúncia**\n```Membro: {member}\nMotivo: {reason}```') 42 | 43 | 44 | def setup(client): 45 | client.add_cog(Report(client)) 46 | -------------------------------------------------------------------------------- /src/cogs/utils/customdatas.py: -------------------------------------------------------------------------------- 1 | 2 | from cogs.utils.data import Data 3 | 4 | 5 | class WelcomeData(Data): 6 | 7 | db_table = 'welcome' 8 | 9 | def __init__(self, client, record): 10 | super().__init__(client, record) 11 | 12 | 13 | class GoodbyeData(Data): 14 | db_table = 'goodbye' 15 | 16 | def __init__(self, client, record): 17 | super().__init__(client, record) 18 | 19 | 20 | class MuteLogData(Data): 21 | db_table = 'mute_log' 22 | 23 | def __init__(self, client, record): 24 | super().__init__(client, record) 25 | 26 | 27 | class KickLogData(Data): 28 | db_table = 'kick_log' 29 | 30 | def __init__(self, client, record): 31 | super().__init__(client, record) 32 | 33 | 34 | class BanLogData(Data): 35 | db_table = 'ban_log' 36 | 37 | def __init__(self, client, record): 38 | super().__init__(client, record) 39 | 40 | 41 | class RepLogData(Data): 42 | db_table = 'rep_log' 43 | 44 | def __init__(self, client, record): 45 | super().__init__(client, record) 46 | 47 | 48 | class AvatarLogData(Data): 49 | db_table = 'avatar_log' 50 | 51 | def __init__(self, client, record): 52 | super().__init__(client, record) 53 | 54 | 55 | class ReportLogData(Data): 56 | db_table = 'report_log' 57 | 58 | def __init__(self, client, record): 59 | super().__init__(client, record) 60 | 61 | @classmethod 62 | async def get_Data_From_Mutual_Guilds(cls, client, guilds): 63 | guilds_to_str = ', '.join(map(str, guilds)) 64 | query = f'SELECT * FROM avatar_log WHERE guild IN ({guilds_to_str})' 65 | 66 | async with client.db.acquire() as con: 67 | records = await con.fetch(query) 68 | 69 | datas = [cls(client, record) for record in records] 70 | 71 | return datas 72 | -------------------------------------------------------------------------------- /src/cogs/utils/time.py: -------------------------------------------------------------------------------- 1 | import re 2 | import datetime 3 | from discord.ext import commands 4 | 5 | 6 | class TimeConverter(commands.Converter): 7 | 8 | async def convert(self, ctx, argument): 9 | 10 | if not argument: # forever 11 | return 0 12 | 13 | time_regex = re.compile(r'(?:([0-9]{1,5})\s?(d|h|m))+?') 14 | time_dict = {"d": 1440, "h": 60, "m": 1} 15 | 16 | args = argument.lower() 17 | 18 | matches = re.findall(time_regex, args) 19 | 20 | minutes = sum(time_dict[v]*int(k) for k, v in matches) 21 | 22 | if not minutes: # not found 23 | return None 24 | 25 | now_ts = datetime.datetime.utcnow().replace( 26 | tzinfo=datetime.timezone.utc) 27 | 28 | future_ts = now_ts + datetime.timedelta(minutes=minutes) 29 | 30 | return future_ts 31 | 32 | 33 | class SecondsConverter(commands.Converter): 34 | 35 | async def convert(self, ctx, argument): 36 | 37 | if not argument: # forever 38 | return 0 39 | 40 | time_regex = re.compile(r'(?:([0-9]{1,5})\s?(d|h|m|s))+?') 41 | time_dict = {"d": 86400, "h": 3600, "m": 60, 's': 1} 42 | 43 | args = argument.lower() 44 | 45 | matches = re.findall(time_regex, args) 46 | 47 | seconds = sum(time_dict[v]*int(k) for k, v in matches) 48 | 49 | return seconds 50 | 51 | 52 | ''' 53 | 54 | Return timestamp in future 55 | 56 | 57 | ''' 58 | 59 | 60 | def get_string_time(time): 61 | 62 | now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc) 63 | total_seconds = int((time - now).total_seconds()) 64 | days, remaining = divmod(total_seconds, 60*60*24) 65 | hours, remaining = divmod(remaining, 60*60) 66 | minutes, seconds = divmod(remaining, 60) 67 | time_dict = {'d': days, 'h': hours, 'm': minutes, 's': seconds} 68 | time_list = [f'{v}{k}' for k, v in time_dict.items() if v] 69 | return ' '.join(time_list) 70 | -------------------------------------------------------------------------------- /src/cogs/utils/timer.py: -------------------------------------------------------------------------------- 1 | import cogs.utils.exceptions as exc 2 | from cogs.utils.mod import ModData 3 | 4 | 5 | class TimerData(ModData): 6 | def __init__(self, client, record_timer, record_mod): 7 | self._args = (client, record_timer, record_mod) 8 | 9 | super().__init__(client, record_mod) 10 | 11 | self.member_id = member_id = record_timer['member'] # member_id for unban hack 12 | 13 | self.time = record_timer['time'] 14 | 15 | self.event = record_timer['event'] 16 | 17 | if self.event == 'mute': 18 | 19 | if self.mute_role is None: 20 | raise exc.MuteRoleNotFound('Role doesn\'t exist anymore') 21 | 22 | member = self.member = self.guild.get_member(member_id) 23 | if member is None: # don't remove from db 24 | raise exc.MemberNotFound('Member not in guild but can rejoin with roles...') 25 | 26 | @classmethod 27 | async def get_Data(cls, client, last_timestamp=None): 28 | 29 | query_timer = 'SELECT * FROM timers ORDER BY time LIMIT 1;' if last_timestamp is None else 'SELECT * FROM timers WHERE time > $1 ORDER BY time LIMIT 1;' 30 | query_mod = '''SELECT * FROM config_mod WHERE guild=$1;''' 31 | 32 | async with client.db.acquire() as con: 33 | if last_timestamp is None: 34 | record_timer = await con.fetchrow(query_timer) 35 | else: 36 | record_timer = await con.fetchrow(query_timer, last_timestamp) 37 | 38 | if record_timer is None: 39 | return None 40 | 41 | guild_id = record_timer['guild'] 42 | 43 | record_mod = await con.fetchrow(query_mod, guild_id) 44 | 45 | return cls(client, record_timer, record_mod) 46 | 47 | async def restart_TimerData(self): 48 | ''' 49 | I want to get values from the instance and returns a new one similar 50 | ''' 51 | return self.__class__(*self._args) 52 | 53 | async def unmute(self): 54 | 55 | return await super().unmute(self.member) 56 | 57 | async def unban(self): 58 | return await super().unban_by_id(self.member_id) 59 | 60 | async def remove_from_db(self): 61 | return await super().remove_time_from_db(id=self.member_id, event=self.event) 62 | 63 | async def bot_can_unmute(self): 64 | return self._bot_can_do_action(self.member) 65 | -------------------------------------------------------------------------------- /src/cogs/reputation.py: -------------------------------------------------------------------------------- 1 | import discord 2 | import datetime 3 | 4 | from discord.ext import commands 5 | from cogs.utils.rep import MemberRepData 6 | from cogs.utils.time import get_string_time 7 | import cogs.utils.exceptions as exc 8 | 9 | 10 | class Reputation(commands.Cog): 11 | def __init__(self, client): 12 | self.client = client 13 | 14 | async def cog_check(self, ctx): 15 | return ctx.guild is not None 16 | 17 | async def cog_before_invoke(self, ctx): 18 | send_msg_perm = ctx.channel.permissions_for(ctx.me).send_messages 19 | ctx.dest = ctx.channel if send_msg_perm else ctx.author 20 | 21 | @commands.command() 22 | async def rep(self, ctx, member: discord.Member): 23 | 24 | if ctx.author == member or member.bot: 25 | return await ctx.dest.send('Não é permitido reputar a você mesmo nem a um bot.') 26 | 27 | try: 28 | data = await MemberRepData.get_Data(self.client, ctx.guild.id, member.id) 29 | except exc.PluginDisabled: 30 | return await ctx.dest.send('`Reputação` está desabilitada neste servidor pois não há nenhum cargo reputável') 31 | 32 | if not data.has_rep_role(member): 33 | return await ctx.dest.send(f'`{member}` não tem cargo de reputação.') 34 | 35 | now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc) 36 | 37 | if data.time and data.cooldown: 38 | min_time = data.time + datetime.timedelta(seconds=data.cooldown) 39 | 40 | if min_time > now: 41 | str_time = get_string_time(min_time) 42 | return await ctx.dest.send(f'Você está em coolown durante `{str_time}`') 43 | 44 | reps_count = await data.rep(member) 45 | 46 | await ctx.dest.send(f'Obrigado pelo seu voto de reputação a `{member}`') 47 | 48 | logs = self.client.get_cog('Logs') 49 | 50 | await logs.rep_log(member, ctx.author, reps_count) 51 | 52 | @commands.command() 53 | async def topreps(self, ctx): 54 | query = 'SELECT member, reps FROM rep_count WHERE guild=$1 ORDER BY reps DESC LIMIT 5' 55 | 56 | async with self.client.db.acquire() as con: 57 | record = await con.fetch(query, ctx.guild.id) 58 | 59 | top_reps = [f"{ctx.guild.get_member(row['member'])} -> {row['reps']} reputaç{'ões' if row['reps'] > 1 else 'ão'}" 60 | for row in record] 61 | 62 | msg = '\n'.join(top_reps) if top_reps else 'Top Reps inexistente' 63 | await ctx.dest.send(msg) 64 | 65 | 66 | def setup(client): 67 | client.add_cog(Reputation(client)) 68 | -------------------------------------------------------------------------------- /src/main.py: -------------------------------------------------------------------------------- 1 | import asyncpg 2 | import discord 3 | import os 4 | from discord.ext import commands 5 | from cogs.utils.main_info import get_command_channel 6 | from cogs.utils.main_info import PREFIX, TOKEN, db_credentials 7 | 8 | extensions = ['moderation', 'timer_task', 'configuration', 9 | 'logs', 'info', 'reputation', 'report', 'general', 'main_logs'] 10 | 11 | 12 | async def bot_db_startup(client): 13 | query_prefixes = 'SELECT * FROM prefixes' 14 | query_user_blacklist = 'SELECT * FROM user_blacklist' 15 | query_guild_blacklist = 'SELECT * FROM guild_blacklist' 16 | async with client.db.acquire() as con: 17 | record_prefixes = await con.fetch(query_prefixes) 18 | record_user_blacklist = await con.fetch(query_user_blacklist) 19 | record_guild_blacklist = await con.fetch(query_guild_blacklist) 20 | 21 | client.prefixes = {row['guild']: row['prefix'] for row in record_prefixes} 22 | client.blacklist = {row['_user'] for row in record_user_blacklist} 23 | client.record_guild_blacklist = record_guild_blacklist 24 | 25 | 26 | def get_prefix(client, message): 27 | return client.prefixes.get(message.guild.id, client.prefix) 28 | 29 | 30 | class Bot(commands.AutoShardedBot): 31 | 32 | def __init__(self, *args, **kwargs): 33 | 34 | super().__init__(*args, **kwargs) 35 | 36 | self.prefix = PREFIX # default 37 | 38 | self.restart = False 39 | 40 | self.db = self.loop.run_until_complete(asyncpg.create_pool(**db_credentials)) 41 | 42 | self.loop.run_until_complete(bot_db_startup(self)) 43 | 44 | 45 | client = Bot(command_prefix=get_prefix, case_insensitive=True) 46 | 47 | 48 | @client.event 49 | async def on_ready(): 50 | 51 | for row in client.record_guild_blacklist: 52 | guild = client.get_guild(row['guild']) 53 | if guild: 54 | await guild.leave() 55 | 56 | del client.record_guild_blacklist 57 | 58 | with open('art_h43.txt', 'r') as file: 59 | image = file.read() 60 | 61 | print(image) 62 | 63 | 64 | @client.after_invoke 65 | async def after_invoke(ctx): 66 | if not client.is_closed(): # restarts doesn't pass here 67 | cog = client.get_cog('MainLogs') 68 | await cog._commands_log(ctx) 69 | 70 | 71 | @client.check_once 72 | async def bot_check_once(ctx): 73 | return ctx.author.id not in client.blacklist 74 | 75 | 76 | if __name__ == "__main__": 77 | for extension in extensions: 78 | client.load_extension('cogs.' + extension) 79 | ''' 80 | try: 81 | client.load_extension(extension) 82 | print(f"Extension executed: {extension}") 83 | except Exception as error: 84 | print(f"The extension {extension} failed. Error = {error}") 85 | ''' 86 | 87 | client.run(TOKEN) 88 | 89 | if client.restart: 90 | os.system('main.py') 91 | -------------------------------------------------------------------------------- /src/cogs/utils/rep.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import cogs.utils.exceptions as exc 3 | from cogs.utils.database import DB 4 | 5 | 6 | class GuildRepData(DB): 7 | 8 | db_table = 'config_rep' 9 | 10 | def __init__(self, client, record): 11 | super().__init__(client) 12 | 13 | roles = record['roles'] 14 | guild_id = record['guild'] 15 | self.cooldown = record['cooldown'] 16 | 17 | # this is just used by the guild so there is no need to check 18 | self.guild = client.get_guild(guild_id) 19 | self.roles = set(roles) if roles is not None else set() 20 | 21 | def has_rep_role(self, member): 22 | return any(role.id in self.roles for role in member.roles) 23 | 24 | async def set_cooldown(self, time): 25 | await self._send_to_db('cooldown', time) 26 | 27 | async def set_roles(self, roles): 28 | roles = [role.id for role in roles] 29 | await self._send_to_db('roles', roles) 30 | 31 | 32 | class MemberRepData(GuildRepData): 33 | 34 | def __init__(self, client, record_config, record_cooldown): 35 | super().__init__(client, record_config) 36 | 37 | # this is just used by the member so there is no need to check 38 | self.time = record_cooldown and record_cooldown['time'] 39 | 40 | @property 41 | def member(self): 42 | return self.guild.get_member(self.member_id) 43 | 44 | @classmethod 45 | async def get_Data(cls, client, guild_id, member_id): 46 | 47 | # this will take member_id as a parameter since it searches for the member 48 | 49 | query_config = 'SELECT * FROM config_rep WHERE guild=$1' 50 | query_cooldown = 'SELECT * FROM rep_cooldown WHERE guild=$1 AND member=$2' 51 | 52 | async with client.db.acquire() as con: 53 | record_config = await con.fetchrow(query_config, guild_id) 54 | record_cooldown = await con.fetchrow(query_cooldown, guild_id, member_id) 55 | 56 | if not record_config: 57 | raise exc.PluginDisabled('Reputation Plugin is not enabled in this server') 58 | 59 | data_cls = cls(client, record_config, record_cooldown) 60 | data_cls.member_id = member_id # if no row is found at least we got member 61 | 62 | return data_cls 63 | 64 | async def rep(self, member): 65 | if self.time: 66 | query_time = 'UPDATE rep_cooldown SET time=$3 WHERE guild=$1 AND member=$2' 67 | else: 68 | query_time = 'INSERT INTO rep_cooldown (guild, member, time) VALUES ($1, $2, $3)' 69 | query_get_count = 'SELECT reps FROM rep_count WHERE guild=$1 AND member=$2' 70 | query_create_count = 'INSERT INTO rep_count (guild, member, reps) VALUES ($1, $2, $3)' 71 | query_update_count = 'UPDATE rep_count SET reps=$3 WHERE guild=$1 AND member=$2' 72 | 73 | now_ts = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc) 74 | 75 | async with self.client.db.acquire() as con: 76 | await con.execute(query_time, self.guild.id, self.member.id, now_ts) 77 | reps_count = await con.fetchval(query_get_count, self.guild.id, member.id) 78 | 79 | if reps_count is None: 80 | await con.execute(query_create_count, self.guild.id, member.id, 1) 81 | else: 82 | await con.execute(query_update_count, self.guild.id, member.id, reps_count + 1) 83 | 84 | return (reps_count and reps_count + 1) or 1 85 | -------------------------------------------------------------------------------- /src/cogs/timer_task.py: -------------------------------------------------------------------------------- 1 | from discord.ext import commands 2 | from cogs.utils.timer import TimerData 3 | 4 | import datetime 5 | import cogs.utils.exceptions as exc 6 | import asyncio 7 | 8 | 9 | class Timer_Task(commands.Cog): 10 | 11 | def __init__(self, client): 12 | self.client = client 13 | self.pending_unmutes = {} 14 | self.pending_unbans = {} 15 | self.skip_timestamp = None 16 | self._current_timer = None 17 | self._task = None 18 | 19 | self._task = self.run_task() 20 | 21 | @commands.Cog.listener() 22 | async def on_guild_role_update(self, before, after): 23 | guild = before.guild 24 | before_perms = before.guild.me.guild_permissions 25 | after_perms = after.guild.me.guild_permissions 26 | manage_roles_changed = not before_perms.manage_roles and after_perms.manage_roles 27 | ban_members_changed = not before_perms.ban_members and after_perms.ban_members 28 | 29 | if manage_roles_changed: 30 | 31 | pending_unmutes = self.pending_unmutes.get(guild.id) 32 | 33 | if pending_unmutes is not None: 34 | 35 | for timer_data in pending_unmutes[:]: 36 | if await timer_data.bot_can_unmute(): 37 | await timer_data.unmute() 38 | else: 39 | await timer_data.remove_from_db() 40 | pending_unmutes.remove(timer_data) 41 | 42 | if ban_members_changed: 43 | 44 | pending_unbans = self.pending_unbans.get(guild.id) 45 | 46 | if pending_unbans is not None: 47 | for timer_data in pending_unbans[:]: 48 | await timer_data.unban() 49 | pending_unmutes.remove(timer_data) 50 | 51 | async def task(self): 52 | 53 | await self.client.wait_until_ready() 54 | 55 | while not self.client.is_closed(): 56 | 57 | try: 58 | 59 | if self._current_timer is None: 60 | timer_data = await TimerData.get_Data(self.client, self.skip_timestamp) 61 | else: 62 | # restarts the class without calling database (performance) returning a new class 63 | timer_data = await timer_data.restart_TimerData() 64 | 65 | except (exc.MuteRoleNotFound, exc.GuildNotFound): 66 | await timer_data.remove_from_db() 67 | except exc.MemberNotFound: 68 | pass # they can join later so we have to add the role back to him again 69 | 70 | 71 | if timer_data is None: 72 | return None 73 | 74 | self._current_timer = timer_data 75 | 76 | now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc) 77 | 78 | interval = (timer_data.time - now).total_seconds() 79 | 80 | if interval > 0: 81 | await asyncio.sleep(interval) 82 | continue # after this time, bot/member could leave the server 83 | 84 | self._current_timer = None # timer finishes 85 | 86 | if timer_data.event == 'mute': 87 | 88 | if not timer_data.guild.me.guild_permissions.manage_roles: # we will unmute later if we don't have permission 89 | # use a set because if we have to restart the task it will reset the skip_timestamp variable 90 | self.pending_unmutes.setdefault(timer_data.guild.id, set()).add(timer_data) 91 | self.skip_timestamp = timer_data.time 92 | continue 93 | 94 | if await timer_data.bot_can_unmute(): 95 | await timer_data.unmute() 96 | 97 | else: 98 | await timer_data.remove_from_db() 99 | 100 | if timer_data.event == 'ban': 101 | if not timer_data.guild.me.guild_permissions.ban_members: # we will unban later if we don't have permission 102 | # use a set because if we have to restart the task it will reset the skip_timestamp variable 103 | self.pending_unbans.setdefault(timer_data.guild.id, set()).add(timer_data) 104 | self.skip_timestamp = timer_data.time 105 | continue 106 | await timer_data.unban() 107 | 108 | def run_task(self): 109 | 110 | if self._task is not None: 111 | self._current_timer = None 112 | self._task.cancel() 113 | 114 | return self.client.loop.create_task(self.task()) 115 | 116 | 117 | def setup(client): 118 | client.add_cog(Timer_Task(client)) 119 | -------------------------------------------------------------------------------- /src/cogs/utils/main_info.py: -------------------------------------------------------------------------------- 1 | from configparser import ConfigParser 2 | from discord.ext import commands 3 | from cogs.utils.exceptions import WrongGuild 4 | 5 | PREMIUM_CH = 585638963683917845 6 | UNBAN_CH = 585640026952564736 7 | 8 | _ROLES_ = [] 9 | _CHANNELS_ = {} 10 | parser = ConfigParser() 11 | parser.read('settings.ini') 12 | 13 | GUILD = parser.getint('Main', 'Guild_ID') 14 | PREFIX = parser.get('Main', 'Prefix', fallback='!') 15 | TOKEN = parser.get('Main', 'Token', fallback=None) 16 | 17 | db_credentials = {} 18 | 19 | for name in parser.options('Database'): 20 | db_credentials[name] = parser.get('Database', name) 21 | 22 | for name in parser.options('Roles_IDs'): # since ID is required 23 | role = {} 24 | role['name'] = name 25 | role['id'] = parser.getint('Roles_IDs', name) 26 | 27 | emoji = parser.get('Roles_Emojis', name, fallback=None) 28 | role['level'] = parser.getint('Roles_Levels', name, fallback=0) 29 | role['emoji'] = emoji and (r'\U000' + emoji).encode('UTF-8').decode('unicode-escape') 30 | _ROLES_.append(role) 31 | 32 | for channel in parser.options('Channels_IDs'): 33 | _CHANNELS_[channel] = parser.getint('Channels_IDs', channel) 34 | 35 | 36 | def _get_channel(client, ch_type): 37 | guild = client.get_guild(GUILD) 38 | channel = guild and guild.get_channel(_CHANNELS_.get(ch_type)) 39 | return channel 40 | 41 | 42 | def get_command_channel(client): 43 | return _get_channel(client, 'commands') 44 | 45 | 46 | def get_servers_channel(client): 47 | return _get_channel(client, 'servers') 48 | 49 | 50 | def get_status_channel(client): 51 | return _get_channel(client, 'status') 52 | 53 | 54 | def get_moderation_channel(client): 55 | return _get_channel(client, 'moderation') 56 | 57 | 58 | class IRoleObj: 59 | 60 | __slots__ = ('name', 'id', 'emoji', 'level') 61 | 62 | def __init__(self, role): 63 | self.name = role.get('name') 64 | self.id = role.get('id') 65 | self.emoji = role.get('emoji') 66 | self.level = role.get('level') 67 | 68 | 69 | Iroles = [IRoleObj(role) for role in _ROLES_] 70 | 71 | Iroles_find = {role.id: role for role in Iroles} 72 | 73 | 74 | class UserInfo: 75 | def __init__(self, client, user): 76 | self.client = client 77 | self.user = user 78 | 79 | @property 80 | def guild(self): 81 | return self.client.get_guild(GUILD) 82 | 83 | @property 84 | def member(self): 85 | guild = self.guild 86 | return guild and guild.get_member(self.user.id) 87 | 88 | @property 89 | def iroles(self): 90 | if not self.member: 91 | return [] 92 | member_roles_Roles = [role.id for role in self.member.roles] 93 | 94 | member_iroles = [Iroles_find[id] for id in member_roles_Roles if id in Iroles_find] 95 | 96 | return member_iroles 97 | 98 | @property 99 | def premium(self): 100 | return any(role.level == 1 for role in self.iroles) 101 | 102 | @property 103 | def mod(self): 104 | return any(role.level == 2 for role in self.iroles) 105 | 106 | @property 107 | def admin(self): 108 | return any(role.level == 3 for role in self.iroles) or self.mod 109 | 110 | @property 111 | def owner(self): 112 | return any(role.level == 4 for role in self.iroles) or self.admin 113 | 114 | 115 | class MemberInfo(UserInfo): 116 | ''' 117 | 118 | This is used for checking before and after member update (premium status!) 119 | 120 | ''' 121 | 122 | def __init__(self, client, member): 123 | self._member = member 124 | super().__init__(client, member) 125 | if member.guild != self.guild: 126 | raise WrongGuild('Member\'s guild isn\'t the main one') 127 | 128 | @property 129 | def member(self): 130 | return self._member 131 | 132 | 133 | def is_admin(): 134 | async def predicate(ctx): 135 | user_info = UserInfo(ctx.bot, ctx.author) 136 | return user_info.admin 137 | return commands.check(predicate) 138 | 139 | 140 | def is_owner(): 141 | async def predicate(ctx): 142 | user_info = UserInfo(ctx.bot, ctx.author) 143 | return user_info.owner 144 | return commands.check(predicate) 145 | 146 | 147 | def is_mod(): 148 | async def predicate(ctx): 149 | user_info = UserInfo(ctx.bot, ctx.author) 150 | return user_info.mod 151 | return commands.check(predicate) 152 | 153 | 154 | def is_premium(): 155 | async def predicate(ctx): 156 | user_info = UserInfo(ctx.bot, ctx.author) 157 | return user_info.premium 158 | return commands.check(predicate) 159 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BotDiscord 2 | Abandonned Bot for discord made by me :D June 2019 - July 2019 3 | 4 | Just to be clear you can't run this bot since you would need the database. The only way would be figuring it out and creating your own. This code is just to help those who want to know how to do or have a better understanding. 5 | 6 | Decided to post the script along some info that I wrote when I was developing: 7 | 8 | Some features may be in portuguese because I was doing it in english and I was going to translate it later. 9 | 10 | 11 | 12 | 13 | Configuration commands: 14 | 15 | ?config 16 | 17 | - mod 18 | - ban_roles (mencionar cargos) 19 | - kick_roles (mencionar cargos) 20 | - mute_roles (mencionar cargos) 21 | 22 | - rep 23 | - cooldown (tempo ex: 1h 5m) 24 | - roles (mencionar cargos que podem ter reputação) 25 | 26 | -log 27 | - avatar 28 | - enable 29 | - channel #channel 30 | - colour vermelho/verde/dourado/etc. 31 | - ban 32 | - title (texto) 33 | - description (texto) 34 | - enable 35 | - channel #channel 36 | - colour vermelho/verde/dourado/etc. 37 | - join 38 | - title (texto) 39 | - description (texto) 40 | - enable 41 | - channel #channel 42 | - colour vermelho/verde/dourado/etc. 43 | - kick 44 | - title (texto) 45 | - description (texto) 46 | - enable 47 | - channel #channel 48 | - colour vermelho/verde/dourado/etc. 49 | - leave 50 | - title (texto) 51 | - description (texto) 52 | - enable 53 | - channel #channel 54 | - colour vermelho/verde/dourado/etc. 55 | - mute 56 | - title (texto) 57 | - description (texto) 58 | - enable 59 | - channel #channel 60 | - colour vermelho/verde/dourado/etc. 61 | - rep 62 | - title (texto) 63 | - description (texto) 64 | - enable 65 | - channel #channel 66 | - colour vermelho/verde/dourado/etc. 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | Info: Title and description : 85 | 86 | - {membro} = Membro#0000 87 | - {membro|menção} = @Membro 88 | - {membro|id} = 321346463148015626 89 | - {servidor} = Servidor 90 | - {membro|nome} = Membro 91 | - {tempo|atual} = Horário de momento 92 | - {tempo|estimado} = Tempo estimado [ban/mute] 93 | - {autor} = Autor#0000 [ban/kick/rep/report/mute] 94 | - {autor|nome} = Autor [ban/kick/rep/report/mute] 95 | - {autor|menção} = @Autor [ban/kick/rep/report/mute] 96 | - {autor|id} = 321346463148015626 [ban/kick/rep/report/mute] 97 | - {reputações} = Contagem de Reputações [rep] 98 | - {denúncia} = Texto de denúncia [report] 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | Help 108 | Configuration: 109 | config 110 | 111 | General: 112 | colour 113 | remove_guild 114 | reset_prefix 115 | restart 116 | serverban 117 | serverunban 118 | show_guilds 119 | userban 120 | userunban 121 | 122 | Info: 123 | info 124 | serverinfo 125 | 126 | Moderation: 127 | ban 128 | kick 129 | mute 130 | unmute 131 | 132 | Report: 133 | report 134 | 135 | Reputation: 136 | rep 137 | topreps 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | If you use this bot or some code please give me some credits. 148 | And notify me if you want. 149 | -------------------------------------------------------------------------------- /src/cogs/info.py: -------------------------------------------------------------------------------- 1 | import discord 2 | 3 | from discord.ext import commands 4 | from cogs.utils.main_info import UserInfo 5 | 6 | 7 | class Info(commands.Cog): 8 | 9 | def __init__(self, client): 10 | self.client = client 11 | 12 | def cog_check(self, ctx): 13 | if ctx.guild is None: 14 | return False 15 | return True 16 | 17 | async def cog_before_invoke(self, ctx): 18 | perms = ctx.channel.permissions_for(ctx.me) 19 | send_msg_perm = perms.send_messages 20 | ctx.to_embed = perms.embed_links or not send_msg_perm 21 | ctx.dest = ctx.channel if send_msg_perm else ctx.author 22 | 23 | @commands.command() 24 | async def serverinfo(self, ctx): 25 | members = len(ctx.guild.members) 26 | bots = sum(1 for member in ctx.guild.members if member.bot) 27 | humans = members - bots 28 | embed = None 29 | msg = '' 30 | 31 | fields = (('🔖 -> Nome', ctx.guild.name), 32 | ('👑-> Dono', ctx.guild.owner), 33 | ('👥-> Membros', len(ctx.guild.members)), 34 | ('🤖-> Robôs', bots), 35 | ('👨-> Humanos', humans), 36 | ('😁-> Emojis', len(ctx.guild.emojis)), 37 | ('🕤 -> Criado em', ctx.guild.created_at.strftime('%d %b %Y às %H:%M')), 38 | ('🌎 -> Região', str(ctx.guild.region).title()) 39 | ) 40 | if ctx.to_embed: 41 | embed = discord.Embed(colour=discord.Colour.gold(), title='**Informações do Servidor **', 42 | timestamp=ctx.message.created_at) 43 | embed.set_thumbnail(url=ctx.guild.icon_url) 44 | 45 | for name, value in fields: 46 | embed.add_field(name=name, value=value) 47 | 48 | embed.set_footer(text='Executado por: {}'.format( 49 | ctx.author), icon_url=ctx.author.avatar_url) 50 | else: 51 | _list = [] 52 | 53 | for name, value in fields: 54 | _list.append(f'**{name}** -> {value}') 55 | 56 | msg = '\n'.join(_list) 57 | 58 | await ctx.dest.send(msg, embed=embed) 59 | 60 | @commands.command() 61 | async def info(self, ctx, member: discord.Member = None): 62 | 63 | member = member or ctx.author 64 | user_info = UserInfo(self.client, member) 65 | embed = None 66 | msg = '' 67 | Status = discord.Status 68 | status_translation = { 69 | Status.online: 'Online', 70 | Status.offline: 'Offline', 71 | Status.idle: 'Ausente', 72 | Status.dnd: 'Ocupado', 73 | } 74 | 75 | ActivityType = discord.ActivityType 76 | type_translation = { 77 | ActivityType.unknown: 'Desconhecido', 78 | ActivityType.playing: 'Jogando', 79 | ActivityType.streaming: 'Transmitindo', 80 | ActivityType.listening: 'Ouvindo', 81 | ActivityType.watching: 'Visualizando' 82 | } 83 | 84 | activity = (member.activity and member.activity.name) or 'Nada' 85 | activity_type = (member.activity and type_translation.get( 86 | member.activity.type)) or 'Fazendo' 87 | 88 | # alguns cargos podem ter os mesmos emojis 89 | emojis = {role.emoji for role in user_info.iroles if role.emoji} 90 | 91 | fields = (('🔖-> Nome', member.name), 92 | ('😄 -> Emojis', 'Nenhum' if not emojis else ''.join(emojis)), 93 | ('🏷️-> Tag', member.discriminator), 94 | ('📋 -> Nick', member.display_name), 95 | ('🆔-> ID', member.id), 96 | ('👀-> Estado', status_translation.get(member.status)), 97 | (f'💤-> {activity_type.capitalize()}', activity), 98 | ('📄-> Cargo Maior', member.top_role), 99 | ('⌛ -> Entrou', member.joined_at.strftime('%d %b %Y às %H:%M')), 100 | ('🕤 -> Criado', member.created_at.strftime('%d %b %Y às %H:%M')), 101 | ) 102 | 103 | if ctx.to_embed: 104 | embed = discord.Embed(title=f"**Informações do Utilizador**", 105 | colour=discord.Colour.blue(), timestamp=ctx.message.created_at) 106 | embed.set_thumbnail(url=member.avatar_url) 107 | 108 | for name, value in fields: 109 | embed.add_field(name=name, value=value) 110 | 111 | embed.set_footer(text='Executado por: {}'.format( 112 | ctx.author), icon_url=ctx.author.avatar_url) 113 | 114 | else: 115 | _list = [] 116 | 117 | for name, value in fields: 118 | _list.append(f'**{name}** -> {value}') 119 | 120 | msg = '\n'.join(_list) 121 | 122 | await ctx.dest.send(msg, embed=embed) 123 | 124 | 125 | def setup(client): 126 | client.add_cog(Info(client)) 127 | -------------------------------------------------------------------------------- /src/cogs/main_logs.py: -------------------------------------------------------------------------------- 1 | import discord 2 | 3 | from discord.ext import commands 4 | from cogs.utils import main_info 5 | from datetime import datetime 6 | from cogs.utils.exceptions import WrongGuild 7 | 8 | 9 | class MainLogs(commands.Cog): 10 | 11 | def __init__(self, client): 12 | self.client = client 13 | 14 | async def _log(self, channel, title, description, icon=None, colour=None): 15 | if not channel: 16 | return 17 | 18 | perms = channel.permissions_for(channel.guild.me) 19 | 20 | if not perms.send_messages: 21 | return 22 | 23 | msg = None 24 | embed = None 25 | 26 | if perms.embed_links: 27 | embed = discord.Embed(title=title, description=description, 28 | colour=colour, timestamp=datetime.utcnow()) 29 | embed.set_thumbnail(url=icon) 30 | else: 31 | msg = f'**{title}**\n\n{description}' 32 | 33 | await channel.send(msg, embed=embed) 34 | 35 | @commands.Cog.listener() 36 | async def on_guild_join(self, guild): 37 | params = {'channel': main_info.get_servers_channel(self.client), 38 | 'title': 'Servidores', 39 | 'description': f'Entrei no servidor: {guild.name}\nID: {guild.id}', 40 | 'colour': discord.Colour.green(), 41 | 'icon': guild.icon_url} 42 | await self._log(**params) 43 | 44 | @commands.Cog.listener() 45 | async def on_guild_remove(self, guild): 46 | params = {'channel': main_info.get_servers_channel(self.client), 47 | 'title': 'Servidores', 48 | 'description': f'Saí no servidor: {guild.name}\nID: {guild.id}', 49 | 'colour': discord.Colour.red(), 50 | 'icon': guild.icon_url} 51 | await self._log(**params) 52 | 53 | async def _commands_log(self, ctx): 54 | params = {'channel': main_info.get_command_channel(self.client), 55 | 'title': 'Commando', 56 | 'description': f'Autor: {ctx.author}\nServidor: {ctx.guild.name}\n\n{ctx.message.content}', 57 | 'colour': discord.Colour.blurple(), 58 | 'icon': ctx.author.avatar_url} 59 | await self._log(**params) 60 | 61 | async def _blacklist_user_log(self, user, author, ban=True): 62 | if ban: 63 | description = f'Utilizador `{user}` foi proibido de utilizar o bot\nAção executada por {author}' 64 | colour = discord.Colour.red() 65 | else: 66 | description = f'Utilizador `{user}` recebeu a permissão de utilizar o bot\nAção executada por {author}' 67 | colour = discord.Colour.green() 68 | params = {'channel': main_info.get_moderation_channel(self.client), 69 | 'title': 'Banimentos do BOT', 70 | 'description': description, 71 | 'colour': colour, 72 | 'icon': user.avatar_url} 73 | await self._log(**params) 74 | 75 | async def _blacklist_guild_log(self, guild, author, ban=True): 76 | if ban: 77 | description = f'Servidor `{guild}` foi proibido de utilizar o bot\nAção executada por {author}' 78 | colour = discord.Colour.red() 79 | else: 80 | description = f'Servidor `{guild}` recebeu a permissão de utilizar o bot\nAção executada por {author}' 81 | colour = discord.Colour.green() 82 | params = {'channel': main_info.get_moderation_channel(self.client), 83 | 'title': 'Banimentos do BOT', 84 | 'description': description, 85 | 'colour': colour, 86 | 'icon': guild.icon_url} 87 | await self._log(**params) 88 | 89 | @commands.Cog.listener() 90 | async def on_ready(self): 91 | params = {'channel': main_info.get_status_channel(self.client), 92 | 'title': 'Estado', 93 | 'description': f'Estou online!', 94 | 'colour': discord.Colour.gold(), 95 | 'icon': self.client.user.avatar_url} 96 | await self._log(**params) 97 | 98 | @commands.Cog.listener() 99 | async def on_member_update(self, before, after): 100 | 101 | if before.roles == after.roles: 102 | return 103 | 104 | try: 105 | premium_before = main_info.MemberInfo(self.client, before).premium 106 | premium_after = main_info.MemberInfo(self.client, after).premium 107 | except WrongGuild: 108 | return 109 | 110 | if premium_before == premium_after: 111 | return 112 | 113 | params = {'channel': main_info.get_moderation_channel(self.client), 114 | 'title': 'Premium', 115 | 'description': f'O utilizador `{after}` ganhou acesso premium' if premium_after else f'O utilizador `{after}` perdeu acesso premium', 116 | 'colour': discord.Colour.blue() if premium_after else discord.Colour.orange(), 117 | 'icon': after.avatar_url} 118 | 119 | await self._log(**params) 120 | 121 | 122 | def setup(client): 123 | client.add_cog(MainLogs(client)) 124 | -------------------------------------------------------------------------------- /src/cogs/moderation.py: -------------------------------------------------------------------------------- 1 | import discord 2 | from discord.ext import commands 3 | from cogs.utils.mod import ModData 4 | from cogs.utils.time import TimeConverter, get_string_time 5 | import cogs.utils.exceptions as exc 6 | 7 | 8 | class Moderation(commands.Cog): 9 | 10 | def __init__(self, client): 11 | self.client = client 12 | self.msg_error = '''Can\'t {0} {1} because one of the following reasons: 13 | {1} has a higher or equal role has me or you 14 | You don\'t have any role allowed to use the command''' 15 | 16 | async def cog_check(self, ctx): 17 | return ctx.guild is not None 18 | 19 | async def cog_before_invoke(self, ctx): 20 | ctx.mod_data = await ModData.get_Data(self.client, ctx.guild.id) 21 | send_msg_perm = ctx.channel.permissions_for(ctx.me).send_messages 22 | ctx.dest = ctx.channel if send_msg_perm else ctx.author 23 | ctx.delete_time = 15 if send_msg_perm else None 24 | 25 | @commands.Cog.listener() 26 | async def on_guild_channel_create(self, channel): 27 | mod_data = await ModData.get_Data(self.client, channel.guild.id) 28 | mod_data.set_one_channel_perms(channel) 29 | 30 | @commands.Cog.listener() 31 | async def on_member_join(self, member): 32 | if not member.guild.me.guild_permissions.manage_roles: 33 | return 34 | 35 | query = 'SELECT time from mute WHERE guild=$1 AND member=$2' 36 | 37 | async with self.client.db.acquire() as con: 38 | mute_time = await con.fetchrow(query, member.guild.id, member.id) 39 | 40 | if mute_time is None: 41 | return 42 | 43 | mod_data = await ModData.get_Data(self.client, member.guild.id) 44 | 45 | if mod_data.mute_role is None or not mod_data._bot_can_do_action(member): 46 | return 47 | 48 | await mod_data.mute(member) 49 | 50 | @commands.command() 51 | @commands.bot_has_permissions(ban_members=True) 52 | async def ban(self, ctx, target: discord.Member, time: TimeConverter = 0): 53 | mod_data = ctx.mod_data 54 | 55 | if not mod_data.can_ban(ctx.author, target): 56 | return await ctx.dest.send(self.msg_error.format('ban', target)) 57 | 58 | if time is None: 59 | return await ctx.dest.send('Tempo não reconhecido ou não positivo') 60 | 61 | if time: 62 | 63 | string_time = get_string_time(time) 64 | fmt = f'durante {string_time}' 65 | else: 66 | fmt = string_time = 'permanentemente' 67 | 68 | await ctx.dest.send(f'`{target}` foi banido por {ctx.author} com sucesso {fmt}', delete_after=ctx.delete_time) 69 | 70 | await mod_data.ban(target, time) 71 | 72 | @commands.command() 73 | @commands.bot_has_permissions(kick_members=True) 74 | async def kick(self, ctx, target: discord.Member, reason=None): 75 | if not ctx.mod_data.can_kick(ctx.author, target): 76 | return await ctx.dest.send(self.msg_error.format('kick', target)) 77 | 78 | logs = self.client.get_cog('logs') 79 | 80 | # check if a member was kicked by bot so it will log as kicked instead of left 81 | logs.kicked_members.setdefault(ctx.guild.id, {})[target.id] = ctx.author 82 | 83 | await target.kick() 84 | await ctx.dest.send(f'`{target}` foi expulso por {ctx.author} com sucesso', delete_after=ctx.delete_time) 85 | 86 | @commands.command() 87 | @commands.bot_has_permissions(manage_roles=True) 88 | async def mute(self, ctx, target: discord.Member, *, time: TimeConverter = 0): 89 | mod_data = ctx.mod_data 90 | 91 | if not mod_data.can_mute(ctx.author, target): 92 | return await ctx.dest.send(self.msg_error.format('mute', target)) 93 | 94 | if time is None: 95 | return await ctx.dest.send('Tempo não reconhecido ou não positivo') 96 | 97 | if mod_data.mute_role is None: 98 | try: 99 | await mod_data.setup_mute_role() 100 | except exc.MaximumRoles: 101 | return await ctx.send('Alguma coisa deu errado....\n`Número de cargos tem de ser inferior ao limite máximo para poder criar o cargo Silenciado`') 102 | 103 | is_muted = await mod_data.is_muted(target) 104 | 105 | if is_muted: 106 | return await ctx.send('O membro já se encontrava silenciado...\nRemova o silêncio e volte a silenciar para escolher um novo intervalo de tempo.') 107 | 108 | if time: 109 | string_time = get_string_time(time) 110 | 111 | fmt = f'durante {string_time}' 112 | else: 113 | fmt = string_time = 'permanentemente' 114 | 115 | await ctx.dest.send(f'`{target}` foi silenciado por `{ctx.author}` {fmt} ', delete_after=ctx.delete_time) 116 | 117 | logs = self.client.get_cog('Logs') 118 | 119 | await logs.mute_log(target, ctx.author, string_time) 120 | 121 | await mod_data.mute(target, time) 122 | 123 | @commands.command() 124 | @commands.bot_has_permissions(manage_roles=True) 125 | async def unmute(self, ctx, target: discord.Member): 126 | mod_data = ctx.mod_data 127 | 128 | if mod_data.mute_role is None: # se não tem mute role também não tem como o membro estar silenciado por este cargo 129 | return await ctx.dest.send('O membro não se encontra silenciado.') 130 | 131 | if not mod_data.can_mute(ctx.author, target): 132 | return await ctx.dest.send(self.msg_error.format('unmute', target)) 133 | 134 | is_muted = await mod_data.is_muted(target) 135 | 136 | if not is_muted: 137 | return await ctx.send('O membro não se encontra silenciado.') 138 | 139 | await mod_data.unmute(target) 140 | await ctx.dest.send(f'Removi o silêncio a {target}', delete_after=ctx.delete_time) 141 | 142 | 143 | def setup(client): 144 | client.add_cog(Moderation(client)) 145 | -------------------------------------------------------------------------------- /src/cogs/utils/mod.py: -------------------------------------------------------------------------------- 1 | import discord 2 | import asyncio 3 | import cogs.utils.exceptions as exc 4 | from cogs.utils.database import DB 5 | 6 | 7 | class ModData(DB): 8 | 9 | db_table = 'config_mod' 10 | 11 | def __init__(self, client, record): 12 | super().__init__(client) 13 | 14 | ban_roles = record['ban_roles'] 15 | kick_roles = record['kick_roles'] 16 | mute_roles = record['mute_roles'] 17 | 18 | self.ban_roles = set(ban_roles) if ban_roles else set() 19 | self.kick_roles = set(kick_roles) if kick_roles else set() 20 | self.mute_roles = set(mute_roles) if mute_roles else set() 21 | 22 | guild_id = record['guild'] 23 | self.guild = guild = guild_id and client.get_guild(guild_id) 24 | if guild is None: 25 | raise exc.GuildNotFound('Given ID wasn\'t a valid one') 26 | 27 | mute_role_id = record['mute_role'] 28 | self.mute_role = mute_role_id and self.guild.get_role(mute_role_id) 29 | 30 | log_channel_id = record['log_channel'] 31 | self.log_channel = log_channel_id and self.guild.get_channel(log_channel_id) 32 | 33 | def bot_can_log(self): 34 | channel = self.log_channel 35 | if not channel: 36 | return False 37 | 38 | bot_perms = channel.permissions_for(self.guild.me) 39 | if not bot_perms.send_messages or not bot_perms.embed_links: 40 | return False 41 | return True 42 | 43 | def _user_can_do_action(self, user, target): 44 | guild_owner = self.guild.owner 45 | return (user.top_role > target.top_role and target != guild_owner) or user == guild_owner 46 | 47 | def _bot_can_do_action(self, target): 48 | bot = self.guild.me 49 | guild_owner = self.guild.owner 50 | return (bot.top_role > target.top_role and target != guild_owner) or bot == guild_owner 51 | 52 | def can_mute(self, user, target): # can a member mute another member? 53 | if not self._user_can_do_action(user, target) or not self._bot_can_do_action(target): 54 | return False 55 | return user.guild_permissions.administrator or any(role.id in self.mute_roles for role in user.roles) 56 | 57 | def can_kick(self, user, target): # can a member kick another member? 58 | if not self._user_can_do_action(user, target) or not self._bot_can_do_action(target): 59 | return False 60 | return user.guild_permissions.administrator or any(role.id in self.kick_roles for role in user.roles) 61 | 62 | def can_ban(self, user, target): # can a member ban another member? 63 | if not self._user_can_do_action(user, target) or not self._bot_can_do_action(target): 64 | return False 65 | return user.guild_permissions.administrator or any(role.id in self.ban_roles for role in user.roles) 66 | 67 | async def is_muted(self, target): 68 | return any(role == self.mute_role for role in target.roles) 69 | 70 | async def mute(self, target, time): 71 | 72 | await target.add_roles(self.mute_role) 73 | if time: 74 | await self._add_time_to_db(target, time, 'mute') 75 | 76 | async def ban(self, target, time): 77 | await target.ban() 78 | await self._add_time_to_db(target, time, 'ban') 79 | 80 | async def _add_time_to_db(self, target, time, event): 81 | 82 | if time is not None: # if not time then its forever 83 | query_insert = 'INSERT INTO timers (guild, member, time, event) VALUES ($1, $2, $3, $4)' 84 | 85 | async with self.client.db.acquire() as con: 86 | await con.execute(query_insert, self.guild.id, target.id, time, event) 87 | 88 | mute_task_cog = self.client.get_cog('Mute_Task') 89 | 90 | if mute_task_cog._task.done() or mute_task_cog._current_timer.time > time: 91 | await mute_task_cog.run_task() 92 | 93 | async def unmute(self, target): 94 | 95 | await target.remove_roles(self.mute_role) 96 | await self.remove_time_from_db(target, event='mute') 97 | 98 | 99 | async def remove_time_from_db(self, target=None, id=None, event=None): 100 | id = id or target.id 101 | ''' 102 | 103 | Removing row from database only (Mute_Task if no mute_role) 104 | 105 | ''' 106 | query_delete = 'DELETE FROM timers WHERE guild=$1 AND member=$2 AND event=$3' 107 | 108 | async with self.client.db.acquire() as con: 109 | await con.execute(query_delete, self.guild.id, id, event) 110 | 111 | async def setup_mute_role(self): 112 | 113 | if len(self.guild.roles) == 250: 114 | raise exc.MaximumRoles('250 roles limit.') 115 | 116 | mute_role = await self.guild.create_role(name='Silenciado', colour=discord.Colour.dark_grey()) 117 | self.mute_role = mute_role 118 | 119 | await self._send_to_db('mute_role', mute_role.id) 120 | 121 | await self.set_channels_perms() 122 | 123 | return mute_role 124 | 125 | async def set_channels_perms(self): 126 | tasks = [] 127 | for channel in self.guild.text_channels: 128 | task = asyncio.ensure_future(self.set_one_channel_perms(channel)) 129 | tasks.append(task) 130 | 131 | await asyncio.wait(tasks) 132 | 133 | async def set_one_channel_perms(self, channel): 134 | bot = self.guild.me 135 | perms = channel.permissions_for(bot) 136 | if perms.manage_roles: 137 | try: 138 | await channel.set_permissions(self.mute_role, send_messages=False, add_reactions=False) 139 | except discord.HTTPException: 140 | pass 141 | 142 | async def set_mute_roles(self, roles): 143 | roles = [role.id for role in roles] 144 | await self._send_to_db('mute_roles', roles) 145 | 146 | async def set_kick_roles(self, roles): 147 | roles = [role.id for role in roles] 148 | await self._send_to_db('kick_roles', roles) 149 | 150 | async def set_ban_roles(self, roles): 151 | roles = [role.id for role in roles] 152 | await self._send_to_db('ban_roles', roles) 153 | 154 | async def unban_by_id(self, id): 155 | user = discord.Object(id=id) 156 | try: 157 | await self.guild.unban(user) 158 | except discord.NotFound: 159 | pass 160 | finally: 161 | await self.remove_time_from_db(id=id, event='ban') 162 | -------------------------------------------------------------------------------- /src/cogs/logs.py: -------------------------------------------------------------------------------- 1 | import discord 2 | import re 3 | 4 | from discord.ext import commands 5 | from cogs.utils.customdatas import * 6 | from functools import wraps 7 | from datetime import datetime 8 | 9 | 10 | class Logs(commands.Cog): 11 | 12 | def __init__(self, client): 13 | self.client = client 14 | self.kicked_members = {} 15 | 16 | async def cog_check(self, ctx): 17 | return ctx.guild is not None 18 | 19 | def _before_member_events(func): 20 | 21 | @wraps(func) 22 | async def wrapper(self, member): 23 | 24 | if func.__name__ == 'on_member_join': 25 | data = await WelcomeData.get_Data(self.client, member.guild.id) 26 | elif func.__name__ == 'on_member_remove': 27 | 28 | guild_id = member.guild.id 29 | author = None 30 | 31 | try: 32 | author = self.kicked_members.get(guild_id, {}).pop(member.id) 33 | except KeyError: 34 | was_kicked = False 35 | else: 36 | was_kicked = True 37 | 38 | if was_kicked: 39 | data = await KickLogData.get_Data(self.client, guild_id) 40 | else: 41 | data = await GoodbyeData.get_Data(self.client, guild_id) 42 | else: 43 | return 44 | 45 | await func(self, member, data, author) 46 | return wrapper 47 | 48 | @commands.Cog.listener() 49 | @_before_member_events 50 | async def on_member_join(self, member, data, author): 51 | 52 | await self._send_msg(data, member=member, can_dms=True, author=author) 53 | 54 | @commands.Cog.listener() 55 | @_before_member_events 56 | async def on_member_remove(self, member, data, author): 57 | 58 | await self._send_msg(data, member=member, can_dms=False, author=author) 59 | 60 | async def _send_msg(self, data, member=None, user=None, guild=None, can_dms=False, mute_time=None, author=None, reps_count=None, report_text=None): 61 | channel = data.channel 62 | colour = data.colour 63 | embed = bool(colour) 64 | embed_msg = None 65 | msg = None 66 | guild = guild or member.guild 67 | member = user or member 68 | 69 | if not data.description or not data.enabled: 70 | return 71 | 72 | if channel is not None: 73 | 74 | perms = channel.permissions_for(guild.me) 75 | 76 | if not perms.send_messages: 77 | return 78 | 79 | if not perms.embed_links: 80 | embed = False 81 | 82 | dest = channel 83 | 84 | else: 85 | 86 | if not can_dms: 87 | return 88 | 89 | dest = member 90 | 91 | def replace_all(string): 92 | if string is not None: 93 | atm_time = datetime.now().strftime('%d/%m/%Y, %H %M') 94 | 95 | replacements = {'\\n': '\n', 96 | '{membro}': member, 97 | '{membro|menção}': member.mention, 98 | '{membro|id}': member.id, 99 | '{servidor}': guild.name, 100 | '{membro|nome}': member.name, 101 | '{tempo|atual}': atm_time, 102 | '{tempo|estimado}': mute_time, 103 | '{autor}': author, 104 | '{autor|nome}': author and author.name, 105 | '{autor|menção}': author and author.mention, 106 | '{autor|id}': author and author.id, 107 | '{reputações}': reps_count, 108 | '{denúncia}': report_text} 109 | 110 | rep = dict((re.escape(k), str(v)) for k, v in replacements.items()) 111 | pattern = re.compile("|".join(rep.keys())) 112 | string = pattern.sub(lambda m: rep[re.escape(m.group(0))], string) 113 | 114 | return string 115 | 116 | title = replace_all(data.title) 117 | description = replace_all(data.description) 118 | 119 | if embed: 120 | embed_msg = discord.Embed(title=title, description=description, 121 | colour=getattr(discord.Colour, colour)()) 122 | embed_msg.set_thumbnail(url=member.avatar_url) 123 | else: 124 | title = f'**{title}**\n\n' if title else '' 125 | msg = f'{title}{description}' 126 | 127 | await dest.send(msg, embed=embed_msg) 128 | 129 | @commands.Cog.listener() 130 | async def on_user_update(self, before_user, after_user): 131 | client = self.client 132 | if before_user.avatar == after_user.avatar: 133 | return 134 | 135 | mutual_guilds_ids = [ 136 | guild.id for guild in client.guilds if guild.get_member(after_user.id) is not None] 137 | avatar_datas_list = await AvatarLogData.get_Data_From_Mutual_Guilds(client, mutual_guilds_ids) 138 | 139 | for avatar_data in avatar_datas_list: 140 | 141 | if not avatar_data.enabled: 142 | continue 143 | 144 | channel = avatar_data.channel 145 | 146 | perms = channel and channel.permissions_for(channel.guild.me) 147 | 148 | if perms is None or not perms.send_messages or not perms.embed_links: 149 | continue 150 | 151 | colour = avatar_data.colour 152 | 153 | if colour is not None: 154 | colour = getattr(discord.Colour, colour)() 155 | 156 | embed = discord.Embed(title=str(after_user), 157 | description='➡️➡️ **Antiga** ➡️➡️', colour=colour) 158 | embed.add_field(name='-'*20, value='⬇️⬇️ **Nova** ⬇️⬇️') 159 | embed.set_thumbnail(url=before_user.avatar_url) 160 | embed.set_image(url=after_user.avatar_url) 161 | 162 | await avatar_data.channel.send(embed=embed) 163 | 164 | @commands.Cog.listener() 165 | async def on_member_ban(self, guild, user): 166 | data = await BanLogData.get_Data(self.client, guild.id) 167 | 168 | await self._send_msg(data, guild=guild, user=user, can_dms=False) 169 | 170 | async def mute_log(self, member, author, time): 171 | data = await MuteLogData.get_Data(self.client, member.guild.id) 172 | await self._send_msg(data, member=member, author=author, can_dms=False, mute_time=time) 173 | 174 | async def rep_log(self, member, author, reps_count): 175 | data = await RepLogData.get_Data(self.client, member.guild.id) 176 | await self._send_msg(data, member=member, author=author, can_dms=False, reps_count=reps_count) 177 | 178 | async def report_log(self, member, author, text, data=None): 179 | data = data or await ReportLogData.get_Data(self.client, member.guild.id) 180 | await self._send_msg(data, member=member, author=author, can_dms=False, report_text=text) 181 | 182 | 183 | def setup(client): 184 | client.add_cog(Logs(client)) 185 | -------------------------------------------------------------------------------- /src/cogs/general.py: -------------------------------------------------------------------------------- 1 | import discord 2 | from discord.ext import commands 3 | from cogs.utils import main_info 4 | 5 | 6 | class General(commands.Cog): 7 | 8 | def __init__(self, client): 9 | self.client = client 10 | 11 | async def cog_before_invoke(self, ctx): 12 | perms = ctx.channel.permissions_for(ctx.me) 13 | send_msg_perm = perms.send_messages 14 | ctx.to_embed = perms.embed_links or not send_msg_perm 15 | ctx.dest = ctx.channel if send_msg_perm else ctx.author 16 | 17 | @main_info.is_admin() 18 | @commands.command() 19 | async def show_guilds(self, ctx, page=0): 20 | guilds = self.client.guilds 21 | embed = None 22 | msg = [] 23 | 24 | if len(guilds) < page*10: 25 | return await ctx.dest.send('Página inválida.') 26 | 27 | embed = discord.Embed(title='**Lista de Servidores**', description=str(ctx.me), 28 | colour=discord.Colour.blurple()) 29 | embed.set_thumbnail(url=ctx.me.avatar_url) 30 | 31 | for guild in guilds[page*10: page*10 + 10]: 32 | if ctx.to_embed: 33 | embed.add_field(name=guild.name, value=guild.id, inline=False) 34 | else: 35 | msg.append(f'{guild.name} -> {guild.id}') 36 | 37 | await ctx.dest.send('\n'.join(msg), embed=embed) 38 | 39 | @main_info.is_admin() 40 | @commands.command() 41 | async def remove_guild(self, ctx, id: int): 42 | guild = self.client.get_guild(id) 43 | if not guild: 44 | return await ctx.dest.send('Servidor não encontrado') 45 | await guild.leave() 46 | await ctx.dest.send(f'Saí do servidor {guild.name} como pedido') 47 | 48 | @commands.command() 49 | @commands.has_permissions(manage_roles=True) 50 | async def colour(self, ctx, role: discord.Role, colour): 51 | not_author_perms = role >= ctx.author.top_role and ctx.author != ctx.guild.owner 52 | 53 | not_bot_perms = not ctx.me.guild_permissions.manage_roles or ( 54 | role >= ctx.me.top_role and ctx.guild.me != ctx.guild.owner) 55 | 56 | if not_author_perms or not_bot_perms or role.is_default(): 57 | return await ctx.dest.send(f'Um de nós não tem permissão para mudar a cor do seguinte cargo: `{role.name}`') 58 | 59 | colour = discord.Colour(int(colour, 16)) 60 | await role.edit(colour=colour) 61 | await ctx.dest.send('Cor alterada com sucesso.') 62 | 63 | @main_info.is_premium() 64 | @commands.command() 65 | @commands.has_permissions(administrator=True) 66 | async def set_prefix(self, ctx, new_prefix): 67 | prefixes = self.client.prefixes 68 | prefix = self.client.prefix 69 | old_prefix = prefixes.get(ctx.guild.id, prefix) 70 | 71 | if new_prefix == old_prefix: 72 | return await ctx.dest.send('O prefixo continua igual...') 73 | 74 | prefixes[ctx.guild.id] = new_prefix 75 | 76 | if new_prefix == prefix: 77 | return await self.remove_prefix(ctx) 78 | 79 | if old_prefix == prefix: 80 | query = 'INSERT INTO prefixes (guild, prefix) VALUES ($1, $2)' 81 | else: 82 | query = 'UPDATE prefixes SET prefix=$2 WHERE guild=$1' 83 | 84 | async with self.client.db.acquire() as con: 85 | await con.execute(query, ctx.guild.id, new_prefix) 86 | 87 | await ctx.dest.send(f'Prefixo alterado para `{new_prefix}`') 88 | 89 | @commands.command() 90 | @commands.has_permissions(administrator=True) 91 | async def reset_prefix(self, ctx): 92 | prefixes = self.client.prefixes 93 | old_prefix = prefixes.get(ctx.guild.id) 94 | prefix = self.client.prefix 95 | 96 | if not old_prefix: 97 | return await ctx.dest.send(f'O prefixo de momento é o por defeito: `{prefix}`') 98 | 99 | await self.remove_prefix(ctx) 100 | 101 | await ctx.dest.send(f'Prefixo resetado com sucesso: `{prefix}`') 102 | 103 | async def remove_prefix(self, ctx): 104 | query = 'DELETE FROM prefixes WHERE guild=$1' 105 | async with self.client.db.acquire() as con: 106 | await con.execute(query, ctx.guild.id) 107 | 108 | self.client.prefixes.pop(ctx.guild.id) 109 | 110 | @main_info.is_mod() 111 | @commands.command() 112 | async def userban(self, ctx, *, raw_user): 113 | 114 | try: 115 | user = await commands.UserConverter().convert(ctx, raw_user) 116 | except commands.BadArgument: 117 | user = raw_user.isdigit() and await self.client.fetch_user(raw_user) 118 | 119 | if not user: 120 | return await ctx.dest.send('Não foi encontrado nenhum utilizador com os dados fornecidos') 121 | 122 | blacklist = self.client.blacklist 123 | 124 | if user.id in blacklist: 125 | return await ctx.dest.send(f'O utilizador `{user}` já se encontrava banido') 126 | 127 | blacklist.add(user.id) 128 | await ctx.dest.send(f'Utilizador `{user}` banido com sucesso. Ele não poderá usar mais os meus comandos') 129 | 130 | query = 'INSERT INTO user_blacklist (_user) VALUES ($1)' 131 | async with self.client.db.acquire() as con: 132 | await con.execute(query, user.id) 133 | 134 | cog = self.client.get_cog('MainLogs') 135 | await cog._blacklist_user_log(user, ctx.author) 136 | 137 | @main_info.is_admin() 138 | @commands.command() 139 | async def userunban(self, ctx, *, raw_user): 140 | 141 | try: 142 | user = await commands.UserConverter().convert(ctx, raw_user) 143 | except commands.BadArgument: 144 | user = raw_user.isdigit() and await self.client.fetch_user(raw_user) 145 | 146 | if not user: 147 | return await ctx.dest.send('Não foi encontrado nenhum utilizador com os dados fornecidos') 148 | 149 | try: 150 | self.client.blacklist.remove(user.id) 151 | except KeyError: 152 | await ctx.dest.send(f'O utilizador `{user}` não se encontrava banido.') 153 | else: 154 | await ctx.dest.send(f'Removi o banimento do utilizador `{user}`. Ele pode utilizar os meus comandos denovo') 155 | 156 | query = 'DELETE FROM user_blacklist WHERE _user=$1' 157 | async with self.client.db.acquire() as con: 158 | await con.execute(query, user.id) 159 | 160 | cog = self.client.get_cog('MainLogs') 161 | await cog._blacklist_user_log(user, ctx.author, ban=False) 162 | 163 | @main_info.is_mod() 164 | @commands.command() 165 | async def serverban(self, ctx, raw_guild: int): 166 | 167 | guild = self.client.get_guild(int(raw_guild)) 168 | 169 | if guild: 170 | await guild.leave() 171 | else: 172 | try: 173 | guild = raw_guild and await self.client.fetch_guild(raw_guild) 174 | 175 | except discord.Forbidden: 176 | return await ctx.dest.send('Não foi encontrado nenhum utilizador com os dados fornecidos') 177 | 178 | query = 'SELECT guild FROM guild_blacklist WHERE guild=$1' 179 | async with self.client.db.acquire() as con: 180 | blacklisted = await con.fetchval(query, guild.id) 181 | 182 | if blacklisted: 183 | return await ctx.dest.send(f'O servidor `{guild.name}` já se encontrava proibído de usar o bot.') 184 | 185 | query = 'INSERT INTO guild_blacklist (guild) VALUES ($1)' 186 | async with self.client.db.acquire() as con: 187 | await con.execute(query, guild.id) 188 | 189 | await ctx.dest.send(f'Proibi o servidor ``{guild.name}` de usar o bot') 190 | 191 | cog = self.client.get_cog('MainLogs') 192 | await cog._blacklist_guild_log(guild, ctx.author) 193 | 194 | @main_info.is_admin() 195 | @commands.command() 196 | async def serverunban(self, ctx, raw_guild: int): 197 | 198 | guild = self.client.get_guild(int(raw_guild)) 199 | if guild: 200 | return await ctx.dest.send(f'O servidor `{guild.name}` não se encontra proibído de usar o bot.') 201 | 202 | try: 203 | guild = raw_guild and await self.client.fetch_guild(raw_guild) 204 | except discord.Forbidden: 205 | return await ctx.dest.send('Não foi encontrado nenhum utilizador com os dados fornecidos') 206 | 207 | query = 'SELECT guild FROM guild_blacklist WHERE guild=$1' 208 | async with self.client.db.acquire() as con: 209 | blacklisted = await con.fetchval(query, guild.id) 210 | 211 | if not blacklisted: 212 | return await ctx.dest.send(f'O servidor `{guild.name}` não se encontra proibído de usar o bot.') 213 | 214 | query = 'DELETE FROM guild_blacklist WHERE guild=$1' 215 | async with self.client.db.acquire() as con: 216 | await con.execute(query, guild.id) 217 | 218 | await ctx.dest.send(f'O servidor ``{guild.name}` pode utilizar os meus comandos denovo!') 219 | 220 | cog = self.client.get_cog('MainLogs') 221 | await cog._blacklist_guild_log(guild, ctx.author, ban=False) 222 | 223 | @main_info.is_owner() 224 | @commands.command() 225 | async def restart(self, ctx): 226 | self.client.restart = True 227 | await ctx.dest.send('Irei reiniciar agora mesmo. Volto em segundos!') 228 | await self.client.logout() 229 | 230 | @commands.Cog.listener() 231 | async def on_guild_join(self, guild): 232 | query = 'SELECT guild FROM guild_blacklist WHERE guild=$1' 233 | async with self.client.db.acquire() as con: 234 | blacklisted = await con.fetchval(query, guild.id) 235 | 236 | if blacklisted: 237 | await guild.leave() 238 | 239 | 240 | def setup(client): 241 | client.add_cog(General(client)) 242 | -------------------------------------------------------------------------------- /src/cogs/configuration.py: -------------------------------------------------------------------------------- 1 | import discord 2 | from discord.ext import commands 3 | from cogs.utils.mod import ModData 4 | from cogs.utils.customdatas import * 5 | from cogs.utils.rep import GuildRepData 6 | from cogs.utils.time import SecondsConverter 7 | from itertools import chain 8 | from cogs.utils.main_info import UserInfo 9 | 10 | 11 | def premium_guild(): 12 | def predicate(ctx): 13 | admin_roles = [role for role in ctx.guild.roles if role.permissions.administrator] 14 | admin_members = {member for member in chain.from_iterable( 15 | [role.members for role in admin_roles])} 16 | 17 | return any(UserInfo(ctx.bot, user).premium for user in admin_members) 18 | return commands.check(predicate) 19 | 20 | 21 | ''' 22 | 23 | Messages' title 24 | 25 | ''' 26 | 27 | 28 | async def title(ctx, *, title): 29 | if len(title) >= 200: # 256 limit 30 | return await ctx.dest.send('Número de caracteres excedido') 31 | 32 | title = title.replace('\n', '\\n') 33 | 34 | await ctx.dest.send(f'Título da mensagem de {ctx.fmt}s atualizada com sucesso!') 35 | 36 | await ctx.data.set_title(title) 37 | 38 | ''' 39 | 40 | Messages' description 41 | 42 | ''' 43 | 44 | 45 | async def description(ctx, *, description): 46 | if len(description) >= 2000: # 2048 limit 47 | return await ctx.dest.send('Número de caracteres excedido') 48 | 49 | description = description.replace('\n', '\\n') 50 | 51 | await ctx.dest.send(f'Descrição da mensagem de {ctx.fmt} atualizada com sucesso!') 52 | 53 | await ctx.data.set_description(description) 54 | 55 | ''' 56 | 57 | Messages' colour 58 | 59 | ''' 60 | 61 | 62 | async def colour(ctx, colour=None): 63 | if colour is not None: 64 | colour_dict = {'vermelho': 'red', 'verde': 'green', 'azul': 'blue', 65 | 'laranja': 'orange', 'magenta': 'magenta', 'dourado': 'gold', 'roxo': 'purple'} 66 | 67 | colour = colour_dict.get(colour.lower()) 68 | 69 | if colour is None: 70 | return await ctx.dest.send('Nenhuma cor disponível foi encontrada com esse nome.') 71 | 72 | await ctx.dest.send(f'A cor do embed da mensagem de {ctx.fmt} foi alterado com sucesso.') 73 | else: 74 | await ctx.dest.send(f'O embed da mensagem de {ctx.fmt} foi removido uma vez que removida a sua cor.') 75 | 76 | await ctx.data.set_colour(colour) 77 | 78 | ''' 79 | 80 | Messages' destination 81 | 82 | ''' 83 | 84 | 85 | async def channel(ctx, channel: discord.TextChannel = None): 86 | 87 | if channel is None and ctx.command.name == 'leave': 88 | return await ctx.dest.send('Não posso enviar mensagens ao utilizador quando sai do servidor.') 89 | 90 | if channel is None: 91 | await ctx.dest.send(f'Mensagens de {ctx.fmt} passarão a ser enviadas ao membro.') 92 | else: 93 | await ctx.dest.send(f'Canal de {ctx.fmt} alterado -> {channel.mention}') 94 | 95 | await ctx.data.set_channel(channel) 96 | 97 | ''' 98 | 99 | Enable/Disable Welcome/Goodbye Message 100 | 101 | ''' 102 | 103 | 104 | async def enable(ctx): 105 | if ctx.data.enabled: 106 | enabled = False 107 | else: 108 | enabled = True 109 | 110 | await ctx.data.set_enabled(enabled) 111 | fmt = 'ativada' if enabled else 'desativada' 112 | await ctx.dest.send(f'A mensagem de {ctx.fmt} foi {fmt}') 113 | 114 | 115 | class LogsGroup(commands.Group): 116 | 117 | _all_cmds = (title, description, colour, channel, enable) 118 | 119 | _cmds_group_methods = {'mute': _all_cmds, 120 | 'kick': _all_cmds, 121 | 'ban': _all_cmds, 122 | 'avatar': (colour, channel, enable), 123 | 'rep': _all_cmds, 124 | 'join': _all_cmds, 125 | 'leave': _all_cmds, 126 | 'report': _all_cmds 127 | } 128 | 129 | def add_command(self, command): 130 | 131 | super().add_command(command) 132 | 133 | cmds_methods = self._cmds_group_methods.get(command.name) 134 | 135 | if cmds_methods is None: 136 | return 137 | 138 | for cmd_method in cmds_methods: 139 | command.command()(cmd_method) 140 | 141 | self._cmds_group_methods.pop(command.name) 142 | 143 | 144 | class Configuration(commands.Cog): 145 | 146 | def __init__(self, client): 147 | self.client = client 148 | 149 | async def cog_check(self, ctx): 150 | return ctx.guild is not None and ctx.author.guild_permissions.administrator 151 | 152 | async def cog_before_invoke(self, ctx): 153 | 154 | if ctx.command.parent: # it will only execute once (subcommands won't pass here) 155 | return 156 | 157 | send_msg_perm = ctx.channel.permissions_for(ctx.me).send_messages 158 | ctx.dest = ctx.channel if send_msg_perm else ctx.author 159 | 160 | @commands.group() 161 | async def config(self, ctx): 162 | if ctx.invoked_subcommand is None: 163 | return await ctx.dest.send('Nenhum parâmetro encontrado...') 164 | 165 | @config.group(name='mod') 166 | async def mod_group(self, ctx): 167 | if ctx.invoked_subcommand is None: 168 | return await ctx.dest.send('Nenhum parâmetro dentro de `mod` encontrado...') 169 | ctx.mod_data = await ModData.get_Data(self.client, ctx.guild.id) 170 | 171 | @config.group(name='log', cls=LogsGroup) 172 | async def log_group(self, ctx): 173 | if ctx.invoked_subcommand is None: 174 | return await ctx.dest.send('Nenhum parâmetro dentro de `log` encontrado...') 175 | 176 | @config.group(name='rep') 177 | @premium_guild() 178 | async def rep_group(self, ctx): 179 | if ctx.invoked_subcommand is None: 180 | return await ctx.dest.send('Nenhum parâmetro dentro de `rep` encontrado...') 181 | ctx.rep_data = await GuildRepData.get_Data(self.client, ctx.guild.id) 182 | 183 | ''' 184 | 185 | Mod 186 | 187 | ''' 188 | 189 | @mod_group.command() 190 | async def mute_roles(self, ctx, roles: commands.Greedy[discord.Role]): 191 | 192 | await self._mod_roles(ctx, roles, 'mute') 193 | 194 | @mod_group.command() 195 | async def kick_roles(self, ctx, roles: commands.Greedy[discord.Role]): 196 | 197 | await self._mod_roles(ctx, roles, 'kick') 198 | 199 | @mod_group.command() 200 | async def ban_roles(self, ctx, roles: commands.Greedy[discord.Role]): 201 | 202 | await self._mod_roles(ctx, roles, 'ban') 203 | 204 | async def _mod_roles(self, ctx, roles, attr): 205 | 206 | translation = {'mute': 'silenciar', 'kick': 'expulsar', 'ban': 'banir'} 207 | 208 | fmt = translation.get(attr) 209 | 210 | if {role.id for role in roles} == ctx.mod_data.mute_roles: 211 | return await ctx.dest.send(f'Os cargos com acesso a {fmt} continuam iguais.') 212 | 213 | await getattr(ctx.mod_data, f'set_{attr}_roles')(roles) 214 | await ctx.dest.send('Os seguintes cargos foram adicionados com permissão de {}.\n`{}`'.format(fmt, '`, `'.join(map(str, roles)))) 215 | 216 | ''' 217 | 218 | 219 | Rep 220 | 221 | 222 | ''' 223 | 224 | @rep_group.command() 225 | async def cooldown(self, ctx, time: SecondsConverter): 226 | if time <= 0 or time > 31536000: 227 | return await ctx.dest.send('Tempo tem de ser positivo e menor que um ano.') 228 | 229 | await ctx.rep_data.set_cooldown(time) 230 | await ctx.dest.send(f'Cooldown em segundos: `{time}s`') 231 | 232 | @rep_group.command() 233 | async def roles(self, ctx, roles: commands.Greedy[discord.Role]): 234 | 235 | if {role.id for role in roles} == ctx.rep_data.roles: 236 | return await ctx.dest.send(f'Os cargos com direito a reputação continuam iguais.') 237 | 238 | await ctx.rep_data.set_roles(roles) 239 | await ctx.dest.send('Os seguintes cargos foram adicionados com o direito a reputação.\n`{}`'.format('`, `'.join(map(str, roles)))) 240 | 241 | ''' 242 | 243 | 244 | Log 245 | 246 | 247 | 248 | ''' 249 | 250 | @log_group.group() 251 | async def mute(self, ctx): 252 | 253 | if ctx.invoked_subcommand is None: 254 | return await ctx.dest.send('Nenhum parâmetro encontrado...') 255 | 256 | ctx.fmt = 'registro de silenciamentos' 257 | ctx.data = await MuteLogData.get_Data(self.client, ctx.guild.id) 258 | 259 | @log_group.group() 260 | async def kick(self, ctx): 261 | 262 | if ctx.invoked_subcommand is None: 263 | return await ctx.dest.send('Nenhum parâmetro encontrado...') 264 | 265 | ctx.fmt = 'registro de expulsões' 266 | ctx.data = await KickLogData.get_Data(self.client, ctx.guild.id) 267 | 268 | @log_group.group() 269 | async def ban(self, ctx): 270 | 271 | if ctx.invoked_subcommand is None: 272 | return await ctx.dest.send('Nenhum parâmetro encontrado...') 273 | 274 | ctx.fmt = 'registro de banimentos' 275 | ctx.data = await BanLogData.get_Data(self.client, ctx.guild.id) 276 | 277 | @log_group.group() 278 | async def avatar(self, ctx): 279 | 280 | if ctx.invoked_subcommand is None: 281 | return await ctx.dest.send('Nenhum parâmetro encontrado...') 282 | 283 | ctx.fmt = 'registro de avatar' 284 | ctx.data = await AvatarLogData.get_Data(self.client, ctx.guild.id) 285 | 286 | @log_group.group() 287 | async def rep(self, ctx): 288 | 289 | if ctx.invoked_subcommand is None: 290 | return await ctx.dest.send('Nenhum parâmetro encontrado...') 291 | 292 | ctx.fmt = 'registro de reputação' 293 | ctx.data = await RepLogData.get_Data(self.client, ctx.guild.id) 294 | 295 | @log_group.group() 296 | async def join(self, ctx): 297 | 298 | if ctx.invoked_subcommand is None: 299 | return await ctx.dest.send('Nenhum parâmetro encontrado...') 300 | 301 | ctx.fmt = 'boas-vindas' 302 | ctx.data = await WelcomeData.get_Data(self.client, ctx.guild.id) 303 | 304 | @log_group.group() 305 | async def leave(self, ctx): 306 | 307 | if ctx.invoked_subcommand is None: 308 | return await ctx.dest.send('Nenhum parâmetro encontrado...') 309 | 310 | ctx.fmt = 'despedida' 311 | ctx.data = await GoodbyeData.get_Data(self.client, ctx.guild.id) 312 | 313 | @log_group.group() 314 | @premium_guild() 315 | async def report(self, ctx): 316 | if ctx.invoked_subcommand is None: 317 | return await ctx.dest.send('Nenhum parâmetro encontrado...') 318 | 319 | ctx.fmt = 'denúncias' 320 | ctx.data = await ReportLogData.get_Data(self.client, ctx.guild.id) 321 | 322 | 323 | def setup(client): 324 | client.add_cog(Configuration(client)) 325 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------