Refactor to conform to PEP 8 styling

add-license-1
DustyP 8 years ago
parent 55209e711e
commit 2da878f3d6

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

@ -1,14 +1,9 @@
import discord import discord
from discord.ext import commands from discord.ext import commands
import json import json
from srcds import rcon as rcon_con import logging
import time, logging, math import inspect
from datetime import datetime, timedelta import os
import asyncio, inspect
import aiohttp, async_timeout
from bs4 import BeautifulSoup as bs
import traceback
import os, sys
from .imports import checks from .imports import checks
config_dir = 'config/' config_dir = 'config/'
@ -21,11 +16,13 @@ invite_match = '(https?://)?(www.)?discord(app.com/(invite|oauth2)|.gg|.io)/[\w\
admin_log = logging.getLogger('admin') admin_log = logging.getLogger('admin')
class admin():
class Admin:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
def _get_config_string(self, guild_config): @staticmethod
def _get_config_string(guild_config):
config_str = '' config_str = ''
for config in guild_config: for config in guild_config:
if isinstance(guild_config[config], dict): if isinstance(guild_config[config], dict):
@ -76,9 +73,12 @@ class admin():
else: else:
emoji_code = f'<:{emoji.name}:{emoji.id}>' emoji_code = f'<:{emoji.name}:{emoji.id}>'
if self.bot.con.all('select id from geeksbot_emojis where id = %(id)s', {'id': emoji.id}): if self.bot.con.all('select id from geeksbot_emojis where id = %(id)s', {'id': emoji.id}):
self.bot.con.run("update geeksbot_emojis set id = %(id)s, name = %(name)s, code = %(emoji_code)s where name = %(name)s", {'name':emoji.name,'id':emoji.id,'emoji_code':emoji_code}) self.bot.con.run("update geeksbot_emojis set id = %(id)s, name = %(name)s, code = %(emoji_code)s "
"where name = %(name)s",
{'name': emoji.name, 'id': emoji.id, 'emoji_code': emoji_code})
else: else:
self.bot.con.run("insert into geeksbot_emojis(id,name,code) values (%(id)s,%(name)s,%(emoji_code)s)", {'name':emoji.name,'id':emoji.id,'emoji_code':emoji_code}) self.bot.con.run("insert into geeksbot_emojis(id,name,code) values (%(id)s,%(name)s,%(emoji_code)s)",
{'name': emoji.name, 'id': emoji.id, 'emoji_code': emoji_code})
await ctx.message.add_reaction('') await ctx.message.add_reaction('')
await ctx.send(f'Emojis have been updated in the database.') await ctx.send(f'Emojis have been updated in the database.')
@ -95,25 +95,26 @@ class admin():
@commands.group(case_insensitive=True) @commands.group(case_insensitive=True)
async def set(self, ctx): async def set(self, ctx):
'''Run help set for more info''' """Run help set for more info"""
pass pass
@commands.group(case_insensitive=True) @commands.group(case_insensitive=True)
async def add(self, ctx): async def add(self, ctx):
'''Run help set for more info''' """Run help set for more info"""
pass pass
@commands.group(case_insensitive=True) @commands.group(case_insensitive=True)
async def remove(self, ctx): async def remove(self, ctx):
'''Run help set for more info''' """Run help set for more info"""
pass pass
@set.command(name='admin_chan', aliases=['ac', 'admin_chat', 'admin chat']) @set.command(name='admin_chan', aliases=['ac', 'admin_chat', 'admin chat'])
async def _admin_channel(self, ctx, channel: discord.TextChannel=None): async def _admin_channel(self, ctx, channel: discord.TextChannel=None):
if ctx.guild: if ctx.guild:
if checks.is_admin(self.bot, ctx): if checks.is_admin(self.bot, ctx):
if channel != None: if channel is not None:
self.bot.con.run('update guild_config set admin_chat = %(chan)s where guild_id = %(id)s', {'id':ctx.guild.id, 'chan': channel.id}) self.bot.con.run('update guild_config set admin_chat = %(chan)s where guild_id = %(id)s',
{'id': ctx.guild.id, 'chan': channel.id})
await ctx.send(f'{channel.name} is now set as the Admin Chat channel for this guild.') await ctx.send(f'{channel.name} is now set as the Admin Chat channel for this guild.')
@set.command(name='channel_lockdown', aliases=['lockdown', 'restrict_access', 'cl']) @set.command(name='channel_lockdown', aliases=['lockdown', 'restrict_access', 'cl'])
@ -121,14 +122,18 @@ class admin():
if ctx.guild: if ctx.guild:
if checks.is_admin(self.bot, ctx): if checks.is_admin(self.bot, ctx):
if str(config).lower() == 'true': if str(config).lower() == 'true':
if self.bot.con.one('select allowed_channels from guild_config where guild_id = %(id)s', {'id':ctx.guild.id}) == []: if self.bot.con.one('select allowed_channels from guild_config where guild_id = %(id)s',
{'id': ctx.guild.id}) is []:
await ctx.send('Please set at least one allowed channel before running this command.') await ctx.send('Please set at least one allowed channel before running this command.')
else: else:
self.bot.con.run('update guild_config set channel_lockdown = True where guild_id = %(id)s', {'id':ctx.guild.id}) self.bot.con.run('update guild_config set channel_lockdown = True where guild_id = %(id)s',
{'id': ctx.guild.id})
await ctx.send('Channel Lockdown is now active.') await ctx.send('Channel Lockdown is now active.')
elif str(config).lower() == 'false': elif str(config).lower() == 'false':
if self.bot.con.one('select channel_lockdown from guild_config where guild_id = %(id)s', {'id':ctx.guild.id}): if self.bot.con.one('select channel_lockdown from guild_config where guild_id = %(id)s',
self.bot.con.run('update guild_config set channel_lockdown = False where guild_id = %(id)s', {'id':ctx.guild.id}) {'id': ctx.guild.id}):
self.bot.con.run('update guild_config set channel_lockdown = False where guild_id = %(id)s',
{'id': ctx.guild.id})
await ctx.send('Channel Lockdown has been deactivated.') await ctx.send('Channel Lockdown has been deactivated.')
else: else:
await ctx.send('Channel Lockdown is already deactivated.') await ctx.send('Channel Lockdown is already deactivated.')
@ -137,7 +142,6 @@ class admin():
else: else:
await ctx.send('This command must be run from inside a guild.') await ctx.send('This command must be run from inside a guild.')
@add.command(name='allowed_channels', aliases=['channel', 'ac']) @add.command(name='allowed_channels', aliases=['channel', 'ac'])
async def _allowed_channels(self, ctx, *, channels): async def _allowed_channels(self, ctx, *, channels):
if ctx.guild: if ctx.guild:
@ -146,23 +150,32 @@ class admin():
added = '' added = ''
for channel in channels: for channel in channels:
chnl = discord.utils.get(ctx.guild.channels, name=channel) chnl = discord.utils.get(ctx.guild.channels, name=channel)
if chnl == None: if chnl is None:
await ctx.send(f'{channel} is not a valid text channel in this guild.') await ctx.send(f'{channel} is not a valid text channel in this guild.')
else: else:
admin_log.info('Chan found') admin_log.info('Chan found')
if self.bot.con.one('select allowed_channels from guild_config where guild_id = %(id)s', {'id':ctx.guild.id}): if self.bot.con.one('select allowed_channels from guild_config where guild_id = %(id)s',
if chnl.id in json.loads(self.bot.con.one('select allowed_channels from guild_config where guild_id = %(id)s', {'id':ctx.guild.id})): {'id': ctx.guild.id}):
if chnl.id in json.loads(self.bot.con.one('select allowed_channels from guild_config '
'where guild_id = %(id)s',
{'id': ctx.guild.id})):
admin_log.info('Chan found in config') admin_log.info('Chan found in config')
await ctx.send(f'{channel} is already in the list of allowed channels. Skipping...') await ctx.send(f'{channel} is already in the list of allowed channels. Skipping...')
else: else:
admin_log.info('Chan not found in config') admin_log.info('Chan not found in config')
allowed_channels = json.loads(self.bot.con.one('select allowed_channels from guild_config where guild_id = %(id)s', {'id':ctx.guild.id})).append(chnl.id) allowed_channels = json.loads(self.bot.con.one('select allowed_channels from '
self.bot.con.run('update guild_config set allowed_channels = %(channels)s where guild_id = %(id)s', {'id':ctx.guild.id, 'channels':allowed_channels}) 'guild_config where guild_id = %(id)s',
{'id': ctx.guild.id})).append(chnl.id)
self.bot.con.run('update guild_config set allowed_channels = %(channels)s '
'where guild_id = %(id)s',
{'id': ctx.guild.id, 'channels': allowed_channels})
added = f'{added}\n{channel}' added = f'{added}\n{channel}'
else: else:
admin_log.info('Chan not found in config') admin_log.info('Chan not found in config')
allowed_channels = [chnl.id] allowed_channels = [chnl.id]
self.bot.con.run('update guild_config set allowed_channels = %(channels)s where guild_id = %(id)s', {'id':ctx.guild.id, 'channels':allowed_channels}) self.bot.con.run('update guild_config set allowed_channels = %(channels)s '
'where guild_id = %(id)s',
{'id': ctx.guild.id, 'channels': allowed_channels})
added = f'{added}\n{channel}' added = f'{added}\n{channel}'
if added != '': if added != '':
await ctx.send(f'The following channels have been added to the allowed channel list: {added}') await ctx.send(f'The following channels have been added to the allowed channel list: {added}')
@ -182,11 +195,12 @@ class admin():
async def add_prefix(self, ctx, *, prefix=None): async def add_prefix(self, ctx, *, prefix=None):
if ctx.guild: if ctx.guild:
if checks.is_admin(self.bot, ctx): if checks.is_admin(self.bot, ctx):
prefixes = self.bot.con.one('select prefix from guild_config where guild_id = %(id)s', {'id':ctx.guild.id}) prefixes = self.bot.con.one('select prefix from guild_config where guild_id = %(id)s',
if prefix == None: {'id': ctx.guild.id})
if prefix is None:
await ctx.send(prefixes) await ctx.send(prefixes)
return return
elif prefixes == None: elif prefixes is None:
prefixes = prefix.replace(' ', ',').split(',') prefixes = prefix.replace(' ', ',').split(',')
else: else:
for p in prefix.replace(' ', ',').split(','): for p in prefix.replace(' ', ',').split(','):
@ -194,9 +208,12 @@ class admin():
if len(prefixes) > 10: if len(prefixes) > 10:
await ctx.send(f'Only 10 prefixes are allowed per guild.\nPlease remove some before adding more.') await ctx.send(f'Only 10 prefixes are allowed per guild.\nPlease remove some before adding more.')
prefixes = prefixes[:10] prefixes = prefixes[:10]
self.bot.con.run('update guild_config set prefix = %(prefixes)s where guild_id = %(id)s', {'id':ctx.guild.id, 'prefixes':prefixes}) self.bot.con.run('update guild_config set prefix = %(prefixes)s where guild_id = %(id)s',
{'id': ctx.guild.id, 'prefixes': prefixes})
await ctx.guild.me.edit(nick=f'[{prefixes[0]}] Geeksbot') await ctx.guild.me.edit(nick=f'[{prefixes[0]}] Geeksbot')
await ctx.send(f"Updated. You currently have {len(prefixes)} {'prefix' if len(prefixes) == 1 else 'prefixes'} in your config.\n{', '.join(prefixes)}") await ctx.send(f"Updated. You currently have {len(prefixes)} "
f"{'prefix' if len(prefixes) == 1 else 'prefixes'} "
f"in your config.\n{', '.join(prefixes)}")
else: else:
await ctx.send(f'You are not authorized to run this command.') await ctx.send(f'You are not authorized to run this command.')
else: else:
@ -207,13 +224,13 @@ class admin():
async def remove_prefix(self, ctx, *, prefix=None): async def remove_prefix(self, ctx, *, prefix=None):
if ctx.guild: if ctx.guild:
if checks.is_admin(self.bot, ctx): if checks.is_admin(self.bot, ctx):
prefixes = [] prefixes = self.bot.con.one('select prefix from guild_config where guild_id = %(id)s',
prefixes = self.bot.con.one('select prefix from guild_config where guild_id = %(id)s', {'id':ctx.guild.id}) {'id': ctx.guild.id})
found = 0 found = 0
if prefix == None: if prefix is None:
await ctx.send(prefixes) await ctx.send(prefixes)
return return
elif prefixes == None or prefixes == []: elif prefixes is None or prefixes == []:
await ctx.send('There are no custom prefixes setup for this guild.') await ctx.send('There are no custom prefixes setup for this guild.')
return return
else: else:
@ -225,9 +242,13 @@ class admin():
else: else:
await ctx.send(f'The prefix {p} is not in the config for this guild.') await ctx.send(f'The prefix {p} is not in the config for this guild.')
if found: if found:
self.bot.con.run('update guild_config set prefix = %(prefixes)s where guild_id = %(id)s', {'id':ctx.guild.id, 'prefixes':prefixes}) self.bot.con.run('update guild_config set prefix = %(prefixes)s where guild_id = %(id)s',
await ctx.guild.me.edit(nick=f'[{prefixes[0] if len(prefixes) != 0 else self.bot.default_prefix}] Geeksbot') {'id': ctx.guild.id, 'prefixes': prefixes})
await ctx.send(f"Updated. You currently have {len(prefixes)} {'prefix' if len(prefixes) == 1 else 'prefixes'} in your config.\n{', '.join(prefixes)}") await ctx.guild.me.edit(nick=f'[{prefixes[0] if len(prefixes) != 0 else self.bot.default_prefix}] '
f'Geeksbot')
await ctx.send(f"Updated. You currently have {len(prefixes)} "
f"{'prefix' if len(prefixes) == 1 else 'prefixes'} "
f"in your config.\n{', '.join(prefixes)}")
else: else:
await ctx.send(f'You are not authorized to run this command.') await ctx.send(f'You are not authorized to run this command.')
else: else:
@ -238,13 +259,15 @@ class admin():
@commands.check(checks.is_guild_owner) @commands.check(checks.is_guild_owner)
async def _add_admin_role(self, ctx, role=None): async def _add_admin_role(self, ctx, role=None):
role = discord.utils.get(ctx.guild.roles, name=role) role = discord.utils.get(ctx.guild.roles, name=role)
if role != None: if role is not None:
roles = json.loads(self.bot.con.one('select admin_roles from guild_config where guild_id = %(id)s', {'id':ctx.guild.id})) roles = json.loads(self.bot.con.one('select admin_roles from guild_config where guild_id = %(id)s',
{'id': ctx.guild.id}))
if role.name in roles: if role.name in roles:
await ctx.send(f'{role.name} is already registered as an admin role in this guild.') await ctx.send(f'{role.name} is already registered as an admin role in this guild.')
else: else:
roles[role.name] = role.id roles[role.name] = role.id
self.bot.con.run('update guild_config set admin_roles = %(roles)s where guild_id = %(id)s', {'id':ctx.guild.id, 'roles':json.dumps(roles)}) self.bot.con.run('update guild_config set admin_roles = %(roles)s where guild_id = %(id)s',
{'id': ctx.guild.id, 'roles': json.dumps(roles)})
await ctx.send(f'{role.name} has been added to the list of admin roles for this guild.') await ctx.send(f'{role.name} has been added to the list of admin roles for this guild.')
else: else:
await ctx.send('You must include a role with this command.') await ctx.send('You must include a role with this command.')
@ -254,16 +277,19 @@ class admin():
@commands.check(checks.is_guild_owner) @commands.check(checks.is_guild_owner)
async def _remove_admin_role(self, ctx, role=None): async def _remove_admin_role(self, ctx, role=None):
role = discord.utils.get(ctx.guild.roles, name=role) role = discord.utils.get(ctx.guild.roles, name=role)
if role != None: if role is not None:
roles = json.loads(self.bot.con.one('select admin_roles from guild_config where guild_id = %(id)s', {'id':ctx.guild.id})) roles = json.loads(self.bot.con.one('select admin_roles from guild_config where guild_id = %(id)s',
{'id': ctx.guild.id}))
if role.name in roles: if role.name in roles:
del roles[role.name] del roles[role.name]
self.bot.con.run('update guild_config set admin_roles = %(roles)s where guild_id = %(id)s', {'id':ctx.guild.id, 'roles':roles}) self.bot.con.run('update guild_config set admin_roles = %(roles)s where guild_id = %(id)s',
{'id': ctx.guild.id, 'roles': roles})
await ctx.send(f'{role.name} has been removed from the list of admin roles for this guild.') await ctx.send(f'{role.name} has been removed from the list of admin roles for this guild.')
else: else:
await ctx.send(f'{role.name} is not registered as an admin role in this guild.') await ctx.send(f'{role.name} is not registered as an admin role in this guild.')
else: else:
await ctx.send('You must include a role with this command.') await ctx.send('You must include a role with this command.')
def setup(bot): def setup(bot):
bot.add_cog(admin(bot)) bot.add_cog(Admin(bot))

@ -1,10 +1,9 @@
import discord import discord
from discord.ext import commands
import logging import logging
from datetime import datetime, timedelta from datetime import datetime
import json, asyncio, traceback import json
import os, re import re
from .imports import checks, utils from .imports import utils
config_dir = 'config/' config_dir = 'config/'
admin_id_file = 'admin_ids' admin_id_file = 'admin_ids'
@ -30,11 +29,13 @@ emojis = {
'trident': '🔱' 'trident': '🔱'
} }
class bot_events():
class BotEvents:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
def _get_config_string(self, guild_config): @staticmethod
def _get_config_string(guild_config):
config_str = '' config_str = ''
for config in guild_config: for config in guild_config:
if isinstance(guild_config[config], dict): if isinstance(guild_config[config], dict):
@ -50,7 +51,8 @@ class bot_events():
return config_str return config_str
async def on_raw_message_delete(self, msg_id, chan_id): async def on_raw_message_delete(self, msg_id, chan_id):
self.bot.con.run('update messages set deleted_at = %(time)s where id = %(id)s', {'time': datetime.utcnow(), 'id': msg_id}) self.bot.con.run('update messages set deleted_at = %(time)s where id = %(id)s',
{'time': datetime.utcnow(), 'id': msg_id})
async def on_raw_bulk_message_delete(self, msg_ids, chan_id): async def on_raw_bulk_message_delete(self, msg_ids, chan_id):
sql = '' sql = ''
@ -66,11 +68,15 @@ class bot_events():
# await ctx.channel.send(f'{ctx.author.mention} You have been healed.') # await ctx.channel.send(f'{ctx.author.mention} You have been healed.')
else: else:
await ctx.add_reaction(self.bot.infected[ctx.author][0]) await ctx.add_reaction(self.bot.infected[ctx.author][0])
except: except Exception:
pass pass
sql = 'insert into messages (id, tts, type, content, embeds, channel, mention_everyone, mentions, channel_mentions, role_mentions, webhook, attachments, pinned, reactions, guild, created_at, system_content, author) \ sql = 'insert into messages (id, tts, type, content, embeds, channel, mention_everyone, mentions,\
values (%(id)s, %(tts)s, %(type)s, %(content)s, %(embeds)s, %(channel)s, %(mention_everyone)s, %(mentions)s, %(channel_mentions)s, %(role_mentions)s, %(webhook)s, %(attachments)s, %(pinned)s, %(reactions)s, %(guild)s, %(created_at)s, %(system_content)s, %(author)s)' channel_mentions, role_mentions, webhook, attachments, pinned, reactions, guild, created_at,\
msg_data = {} system_content, author) \
values (%(id)s, %(tts)s, %(type)s, %(content)s, %(embeds)s, %(channel)s, %(mention_everyone)s, %(mentions)s,\
%(channel_mentions)s, %(role_mentions)s, %(webhook)s, %(attachments)s, %(pinned)s, %(reactions)s, %(guild)s,\
%(created_at)s, %(system_content)s, %(author)s)'
msg_data = dict()
msg_data['id'] = ctx.id msg_data['id'] = ctx.id
msg_data['tts'] = ctx.tts msg_data['tts'] = ctx.tts
msg_data['type'] = str(ctx.type) msg_data['type'] = str(ctx.type)
@ -82,7 +88,8 @@ class bot_events():
msg_data['channel_mentions'] = [channel.id for channel in ctx.channel_mentions] msg_data['channel_mentions'] = [channel.id for channel in ctx.channel_mentions]
msg_data['role_mentions'] = [role.id for role in ctx.role_mentions] msg_data['role_mentions'] = [role.id for role in ctx.role_mentions]
msg_data['webhook'] = ctx.webhook_id msg_data['webhook'] = ctx.webhook_id
msg_data['attachments'] = [json.dumps({'id': a.id, 'size': a.size, 'height': a.height, 'width': a.width, 'filename': a.filename, 'url': a.url}) for a in ctx.attachments] msg_data['attachments'] = [json.dumps({'id': a.id, 'size': a.size, 'height': a.height, 'width': a.width,
'filename': a.filename, 'url': a.url}) for a in ctx.attachments]
msg_data['pinned'] = ctx.pinned msg_data['pinned'] = ctx.pinned
msg_data['guild'] = ctx.guild.id msg_data['guild'] = ctx.guild.id
msg_data['created_at'] = ctx.created_at msg_data['created_at'] = ctx.created_at
@ -94,7 +101,8 @@ class bot_events():
if ctx.author != ctx.guild.me: if ctx.author != ctx.guild.me:
if self.bot.con.one(f"select pg_filter from guild_config where guild_id = {ctx.guild.id}"): if self.bot.con.one(f"select pg_filter from guild_config where guild_id = {ctx.guild.id}"):
profane = 0 profane = 0
for word in self.bot.con.one('select profane_words from guild_config where guild_id = %(id)s', {'id':ctx.guild.id}): for word in self.bot.con.one('select profane_words from guild_config where guild_id = %(id)s',
{'id': ctx.guild.id}):
word = word.strip() word = word.strip()
if word in ctx.content.lower(): if word in ctx.content.lower():
events_log.info(f'Found non PG word {word}') events_log.info(f'Found non PG word {word}')
@ -121,23 +129,28 @@ class bot_events():
await react.message.channel.send(f"You can't Poop on me {user.mention} :P") await react.message.channel.send(f"You can't Poop on me {user.mention} :P")
reactions = react.message.reactions reactions = react.message.reactions
reacts = [json.dumps({'emoji': r.emoji, 'count': r.count}) for r in reactions] reacts = [json.dumps({'emoji': r.emoji, 'count': r.count}) for r in reactions]
self.bot.con.run('update messages set reactions = %(reacts)s where id = {react.message.id}', {'reacts': reacts}) self.bot.con.run('update messages set reactions = %(reacts)s where id = %(id)s',
{'id': react.message.id, 'reacts': reacts})
async def on_message_edit(self, before, ctx): async def on_message_edit(self, before, ctx):
previous_content = self.bot.con.one('select previous_content from messages where id = {ctx.id}') previous_content = self.bot.con.one('select previous_content from messages where id = %(id)s', {'id': ctx.id})
if previous_content: if previous_content:
previous_content.append(before.content) previous_content.append(before.content)
else: else:
previous_content = [before.content] previous_content = [before.content]
previous_embeds = self.bot.con.one('select previous_embeds from messages where id = {ctx.id}') previous_embeds = self.bot.con.one('select previous_embeds from messages where id = %(id)s', {'id': ctx.id})
if previous_embeds: if previous_embeds:
previous_embeds.append([json.dumps(e.to_dict()) for e in before.embeds]) previous_embeds.append([json.dumps(e.to_dict()) for e in before.embeds])
else: else:
previous_embeds = [[json.dumps(e.to_dict()) for e in before.embeds]] previous_embeds = [[json.dumps(e.to_dict()) for e in before.embeds]]
sql = 'update messages set (edited_at, previous_content, previous_embeds, tts, type, content, embeds, channel, mention_everyone, mentions, channel_mentions, role_mentions, webhook, attachments, pinned, reactions, guild, created_at, system_content, author) \ sql = 'update messages set (edited_at, previous_content, previous_embeds, tts, type, content,\
= (%(edited_at)s, %(previous_content)s, %(previous_embeds)s, %(tts)s, %(type)s, %(content)s, %(embeds)s, %(channel)s, %(mention_everyone)s, %(mentions)s, %(channel_mentions)s, %(role_mentions)s, %(webhook)s, %(attachments)s, %(pinned)s, %(reactions)s, %(guild)s, %(created_at)s, %(system_content)s, %(author)s) \ embeds, channel, mention_everyone, mentions, channel_mentions, role_mentions, webhook,\
where id = %(id)s' attachments, pinned, reactions, guild, created_at, system_content, author) \
msg_data = {} = (%(edited_at)s, %(previous_content)s, %(previous_embeds)s, %(tts)s, %(type)s, %(content)s,\
%(embeds)s, %(channel)s, %(mention_everyone)s, %(mentions)s, %(channel_mentions)s, %(role_mentions)s,\
%(webhook)s, %(attachments)s, %(pinned)s, %(reactions)s, %(guild)s, %(created_at)s, %(system_content)s,\
%(author)s) where id = %(id)s'
msg_data = dict()
msg_data['id'] = ctx.id msg_data['id'] = ctx.id
msg_data['tts'] = ctx.tts msg_data['tts'] = ctx.tts
msg_data['type'] = str(ctx.type) msg_data['type'] = str(ctx.type)
@ -161,7 +174,8 @@ class bot_events():
msg_data['edited_at'] = datetime.utcnow() msg_data['edited_at'] = datetime.utcnow()
self.bot.con.run(sql, msg_data) self.bot.con.run(sql, msg_data)
async def on_command_error(self,ctx,error): @staticmethod
async def on_command_error(ctx, error):
if ctx.channel.id == 418452585683484680 and type(error) == discord.ext.commands.errors.CommandNotFound: if ctx.channel.id == 418452585683484680 and type(error) == discord.ext.commands.errors.CommandNotFound:
return return
for page in utils.paginate(error): for page in utils.paginate(error):
@ -175,8 +189,10 @@ class bot_events():
default_config['name'] = guild.name.replace("'", "\\'") default_config['name'] = guild.name.replace("'", "\\'")
default_config['guild_id'] = guild.id default_config['guild_id'] = guild.id
events_log.info(default_config) events_log.info(default_config)
self.bot.con.run("insert into guild_config(guild_id,guild_name,admin_roles,rcon_enabled,channel_lockdown,raid_status,pg_filter,patreon_enabled,referral_enabled)\ self.bot.con.run("insert into guild_config(guild_id, guild_name, admin_roles, rcon_enabled, channel_lockdown,\
values (%(guild_id)s,%(name)s,%(admin_roles)s,%(rcon_enabled)s,%(channel_lockdown)s,%(raid_status)s,%(pg_filter)s,%(patreon_enabled)s,%(referral_enabled)s)", raid_status, pg_filter, patreon_enabled, referral_enabled)\
values (%(guild_id)s, %(name)s, %(admin_roles)s, %(rcon_enabled)s, %(channel_lockdown)s,\
%(raid_status)s, %(pg_filter)s, %(patreon_enabled)s, %(referral_enabled)s)",
{'guild_id': default_config['guild_id'], {'guild_id': default_config['guild_id'],
'name': default_config['name'], 'name': default_config['name'],
'admin_roles': json.dumps(default_config['admin_roles']), 'admin_roles': json.dumps(default_config['admin_roles']),
@ -188,49 +204,53 @@ class bot_events():
'referral_enabled': default_config['referral_enabled'] 'referral_enabled': default_config['referral_enabled']
}) })
events_log.info(f'Entry Created for {guild.name}') events_log.info(f'Entry Created for {guild.name}')
config_str = self._get_config_string(default_config)
self.bot.recent_msgs[guild.id] = deque(maxlen=50)
await guild.me.edit(nick='[g$] Geeksbot') await guild.me.edit(nick='[g$] Geeksbot')
# await guild.owner.send(f'Geeksbot has joined your guild {guild.name}!\nYour current configuration is:\n```{config_str}```\nEnjoy!')
async def on_guild_remove(self, guild): async def on_guild_remove(self, guild):
self.bot.con.run(f'delete from guild_config where guild_id = %(id)s', {'id':ctx.guild.id}) self.bot.con.run(f'delete from guild_config where guild_id = %(id)s', {'id': guild.id})
events_log.info(f'Left the {guild.name} guild.') events_log.info(f'Left the {guild.name} guild.')
async def on_member_join(self, member): async def on_member_join(self, member):
events_log.info(f'Member joined: {member.name} {member.id} Guild: {member.guild.name} {member.guild.id}') events_log.info(f'Member joined: {member.name} {member.id} Guild: {member.guild.name} {member.guild.id}')
join_chan = self.bot.con.one('select join_leave_chat from guild_config where guild_id = %(id)s', {'id':member.guild.id}) join_chan = self.bot.con.one('select join_leave_chat from guild_config where guild_id = %(id)s',
{'id': member.guild.id})
if join_chan: if join_chan:
em = discord.Embed(style='rich', em = discord.Embed(style='rich',
color=embed_color color=embed_color
) )
em.set_thumbnail(url=member.avatar_url) em.set_thumbnail(url=member.avatar_url)
em.add_field(name=f'Welcome {member.name}#{member.discriminator}', value=member.id, inline=False) em.add_field(name=f'Welcome {member.name}#{member.discriminator}', value=member.id, inline=False)
em.add_field(name='User created on:', value=member.created_at.strftime('%Y-%m-%d at %H:%M:%S GMT'), inline=True) em.add_field(name='User created on:', value=member.created_at.strftime('%Y-%m-%d at %H:%M:%S GMT'),
inline=True)
em.add_field(name='Bot:', value=str(member.bot)) em.add_field(name='Bot:', value=str(member.bot))
em.set_footer(text=f"{member.guild.name} | {member.joined_at.strftime('%Y-%m-%d at %H:%M:%S GMT')}", icon_url=member.guild.icon_url) em.set_footer(text=f"{member.guild.name} | {member.joined_at.strftime('%Y-%m-%d at %H:%M:%S GMT')}",
icon_url=member.guild.icon_url)
await discord.utils.get(member.guild.channels, id=join_chan).send(embed=em) await discord.utils.get(member.guild.channels, id=join_chan).send(embed=em)
mem_data = {'id': member.id, mem_data = {'id': member.id,
'name': member.name, 'name': member.name,
'discriminator': member.discriminator, 'discriminator': member.discriminator,
'bot': member.bot 'bot': member.bot
} }
mem = self.bot.con.one('select guilds,nicks from user_data where id = {member.id}') mem = self.bot.con.one('select guilds,nicks from user_data where id = %(id)s', {'id': member.id})
if mem: if mem:
mem[1].append(json.dumps({member.guild.id: member.display_name})) mem[1].append(json.dumps({member.guild.id: member.display_name}))
mem[0].append(member.guild.id) mem[0].append(member.guild.id)
mem_data['nicks'] = mem[1] mem_data['nicks'] = mem[1]
mem_data['guilds'] = mem[0] mem_data['guilds'] = mem[0]
self.bot.con.run('update user_data set (name, discriminator, bot, nicks, guilds) = (%(name)s, %(discriminator)s, %(bot)s, %(nicks)s, %(guilds)s) where id = %(id)s',mem_data) self.bot.con.run('update user_data set (name, discriminator, bot, nicks, guilds) =\
(%(name)s, %(discriminator)s, %(bot)s, %(nicks)s, %(guilds)s) where\
id = %(id)s', mem_data)
else: else:
mem_data['nicks'] = [json.dumps({member.guild.id: member.display_name})] mem_data['nicks'] = [json.dumps({member.guild.id: member.display_name})]
mem_data['guilds'] = [member.guild.id] mem_data['guilds'] = [member.guild.id]
self.bot.con.run('insert into user_data (id, name, discriminator, bot, nicks, guilds) values (%(id)s, %(name)s, %(discriminator)s, %(bot)s, %(nicks)s, %(guilds)s)',mem_data) self.bot.con.run('insert into user_data (id, name, discriminator, bot, nicks, guilds) values\
(%(id)s, %(name)s, %(discriminator)s, %(bot)s, %(nicks)s, %(guilds)s)', mem_data)
async def on_member_remove(self, member): async def on_member_remove(self, member):
leave_time = datetime.utcnow() leave_time = datetime.utcnow()
events_log.info(f'Member left: {member.name} {member.id} Guild: {member.guild.name} {member.guild.id}') events_log.info(f'Member left: {member.name} {member.id} Guild: {member.guild.name} {member.guild.id}')
join_chan = self.bot.con.one('select join_leave_chat from guild_config where guild_id = %(id)s', {'id':member.guild.id}) join_chan = self.bot.con.one('select join_leave_chat from guild_config where guild_id = %(id)s',
{'id': member.guild.id})
if join_chan: if join_chan:
em = discord.Embed(style='rich', em = discord.Embed(style='rich',
color=red_color color=red_color
@ -245,11 +265,15 @@ class bot_events():
days, remainder = divmod(total_time.total_seconds(), 86400) days, remainder = divmod(total_time.total_seconds(), 86400)
hours, remainder = divmod(remainder, 3600) hours, remainder = divmod(remainder, 3600)
minutes, seconds = divmod(remainder, 60) minutes, seconds = divmod(remainder, 60)
time_str = f"{str(int(days)) + ' days, ' if days != 0 else ''}{str(int(hours)) + ' hours, ' if hours != 0 else ''}{str(int(minutes)) + ' minutes and ' if minutes != 0 else ''}{int(seconds)} seconds" days_str = str(int(days)) + ' days, ' if days != 0 else ''
hours_str = str(int(hours)) + ' hours, ' if hours != 0 else ''
minutes_str = str(int(minutes)) + ' minutes and ' if minutes != 0 else ''
time_str = f"{days_str}{hours_str}{minutes_str}{int(seconds)} seconds"
em.add_field(name='Total time in Guild:', value=time_str, inline=False) em.add_field(name='Total time in Guild:', value=time_str, inline=False)
em.set_footer(text=f"{member.guild.name} | {datetime.utcnow().strftime('%Y-%m-%d at %H:%M:%S GMT')}", icon_url=member.guild.icon_url) em.set_footer(text=f"{member.guild.name} | {datetime.utcnow().strftime('%Y-%m-%d at %H:%M:%S GMT')}",
icon_url=member.guild.icon_url)
await discord.utils.get(member.guild.channels, id=join_chan).send(embed=em) await discord.utils.get(member.guild.channels, id=join_chan).send(embed=em)
def setup(bot): def setup(bot):
bot.add_cog(bot_events(bot)) bot.add_cog(BotEvents(bot))

@ -2,8 +2,8 @@ import discord
from discord.ext import commands from discord.ext import commands
import logging import logging
from datetime import datetime from datetime import datetime
import json, asyncio import asyncio
import os, re, aiohttp, async_timeout import youtube_dl
config_dir = 'config/' config_dir = 'config/'
admin_id_file = 'admin_ids' admin_id_file = 'admin_ids'
@ -25,7 +25,8 @@ emojis = {
'poop': '💩' 'poop': '💩'
} }
class fun():
class Fun:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
@ -36,9 +37,11 @@ class fun():
await ctx.send(f'You rolled a Critical Fail...\nInfection bounces off and rebounds on the attacker.') await ctx.send(f'You rolled a Critical Fail...\nInfection bounces off and rebounds on the attacker.')
member = ctx.author member = ctx.author
if member in self.bot.infected: if member in self.bot.infected:
await ctx.send(f'{member.display_name} is already infected. Please wait until they are healed before infecting them again...') await ctx.send(f'{member.display_name} is already infected. '
f'Please wait until they are healed before infecting them again...')
else: else:
emoji = self.bot.get_emoji(int(emoji.split(':')[2].strip('>'))) if '<:' in emoji or '<a:' in emoji else emoji emoji = self.bot.get_emoji(int(emoji.split(':')[2].strip('>'))) if '<:' in emoji \
or '<a:' in emoji else emoji
self.bot.infected[member] = [emoji, datetime.now().timestamp()] self.bot.infected[member] = [emoji, datetime.now().timestamp()]
await ctx.send(f"{member.display_name} has been infected with {emoji}") await ctx.send(f"{member.display_name} has been infected with {emoji}")
@ -64,12 +67,14 @@ class fun():
async def slap(self, ctx, member: discord.Member): async def slap(self, ctx, member: discord.Member):
if member.id == self.bot.user.id and ctx.author.id != owner_id: if member.id == self.bot.user.id and ctx.author.id != owner_id:
await ctx.send(f'You rolled a Critical Fail...\nThe trout bounces off and rebounds on the attacker.') await ctx.send(f'You rolled a Critical Fail...\nThe trout bounces off and rebounds on the attacker.')
member = ctx.author await ctx.send(f'{ctx.author.mention} '
await ctx.send(f'{ctx.author.mention} You slap yourself in the face with a large trout <:trout:408543365085397013>') f'You slap yourself in the face with a large trout <:trout:408543365085397013>')
else: else:
await ctx.send(f'{ctx.author.display_name} slaps {member.mention} around a bit with a large trout <:trout:408543365085397013>') await ctx.send(f'{ctx.author.display_name} slaps '
f'{member.mention} around a bit with a large trout <:trout:408543365085397013>')
def get_factorial(self,number): @staticmethod
def get_factorial(number):
a = 1 a = 1
for i in range(1, int(number)): for i in range(1, int(number)):
a = a * (i + 1) a = a * (i + 1)
@ -103,8 +108,11 @@ class fun():
self.bot.voice_chans[ctx.author.voice.channel.name] = await ctx.author.voice.channel.connect() self.bot.voice_chans[ctx.author.voice.channel.name] = await ctx.author.voice.channel.connect()
asyncio.sleep(5) asyncio.sleep(5)
if url: if url:
import youtube_dl opts = {"format": 'webm[abr>0]/bestaudio/best',
opts = {"format": 'webm[abr>0]/bestaudio/best',"ignoreerrors": True,"default_search": "auto","source_address": "0.0.0.0",'quiet': True} "ignoreerrors": True,
"default_search": "auto",
"source_address": "0.0.0.0",
'quiet': True}
ydl = youtube_dl.YoutubeDL(opts) ydl = youtube_dl.YoutubeDL(opts)
info = ydl.extract_info(url, download=False) info = ydl.extract_info(url, download=False)
self.bot.player = discord.FFmpegPCMAudio(info['url']) self.bot.player = discord.FFmpegPCMAudio(info['url'])
@ -140,4 +148,4 @@ class fun():
def setup(bot): def setup(bot):
bot.add_cog(fun(bot)) bot.add_cog(Fun(bot))

@ -1,6 +1,6 @@
import discord import discord
from discord.ext import commands from discord.ext import commands
import os, logging import logging
from .imports.utils import paginate, run_command from .imports.utils import paginate, run_command
import asyncio import asyncio
@ -9,13 +9,14 @@ embed_color = discord.Colour.from_rgb(49,107,111)
git_log = logging.getLogger('git') git_log = logging.getLogger('git')
class Git():
class Git:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
@commands.group(case_insensitive=True) @commands.group(case_insensitive=True)
async def git(self, ctx): async def git(self, ctx):
'''Run help set for more info''' """Run help git for more info"""
pass pass
@git.command() @git.command()
@ -26,8 +27,10 @@ class Git():
color=embed_color) color=embed_color)
em.set_thumbnail(url=f'{ctx.guild.me.avatar_url}') em.set_thumbnail(url=f'{ctx.guild.me.avatar_url}')
result = await asyncio.wait_for(self.bot.loop.create_task(run_command('git fetch --all')), 120) + '\n' result = await asyncio.wait_for(self.bot.loop.create_task(run_command('git fetch --all')), 120) + '\n'
result += await asyncio.wait_for(self.bot.loop.create_task(run_command('git reset --hard origin/master')),120) + '\n\n' result += await asyncio.wait_for(self.bot.loop.create_task(run_command('git reset --hard '
result += await asyncio.wait_for(self.bot.loop.create_task(run_command('git show --stat | sed "s/.*@.*[.].*/ /g"')),10) 'origin/master')), 120) + '\n\n'
result += await asyncio.wait_for(self.bot.loop.create_task(run_command('git show --stat | '
'sed "s/.*@.*[.].*/ /g"')), 10)
results = paginate(result, maxlen=1014) results = paginate(result, maxlen=1014)
for page in results[:5]: for page in results[:5]:
em.add_field(name='', value=f'{page}') em.add_field(name='', value=f'{page}')

@ -1,50 +1,60 @@
import discord, json, asyncio import discord
import json
from . import utils from . import utils
owner_id = 351794468870946827 owner_id = 351794468870946827
def check_admin_role(bot, ctx, member): def check_admin_role(bot, ctx, member):
admin_roles = json.loads(bot.con.one(f"select admin_roles from guild_config where guild_id = {ctx.guild.id}")) admin_roles = json.loads(bot.con.one(f"select admin_roles from guild_config where guild_id = %(id)s",
{'id': ctx.guild.id}))
for role in admin_roles: for role in admin_roles:
if discord.utils.get(ctx.guild.roles, id=admin_roles[role]) in member.roles: if discord.utils.get(ctx.guild.roles, id=admin_roles[role]) in member.roles:
return True return True
return member.id == ctx.guild.owner.id or member.id == owner_id return member.id == ctx.guild.owner.id or member.id == owner_id
def check_rcon_role(bot, ctx, member): def check_rcon_role(bot, ctx, member):
rcon_admin_roles = json.loads(bot.con.one(f"select rcon_admin_roles from guild_config where guild_id = {ctx.guild.id}")) rcon_admin_roles = json.loads(bot.con.one("select rcon_admin_roles from guild_config where guild_id = %(id)s",
{'id': ctx.guild.id}))
for role in rcon_admin_roles: for role in rcon_admin_roles:
if discord.utils.get(ctx.guild.roles, id=rcon_admin_roles[role]) in member.roles: if discord.utils.get(ctx.guild.roles, id=rcon_admin_roles[role]) in member.roles:
return True return True
return member.id == ctx.guild.owner.id or member.id == owner_id return member.id == ctx.guild.owner.id or member.id == owner_id
def is_admin(bot, ctx): def is_admin(bot, ctx):
admin_roles = json.loads(bot.con.one(f"select admin_roles from guild_config where guild_id = {ctx.guild.id}")) admin_roles = json.loads(bot.con.one("select admin_roles from guild_config where guild_id = %(id)s",
{'id': ctx.guild.id}))
for role in admin_roles: for role in admin_roles:
if discord.utils.get(ctx.guild.roles, id=admin_roles[role]) in ctx.message.author.roles: if discord.utils.get(ctx.guild.roles, id=admin_roles[role]) in ctx.message.author.roles:
return True return True
return ctx.message.author.id == ctx.guild.owner.id or ctx.message.author.id == owner_id return ctx.message.author.id == ctx.guild.owner.id or ctx.message.author.id == owner_id
def is_guild_owner(ctx): def is_guild_owner(ctx):
if ctx.guild: if ctx.guild:
return ctx.message.author.id == ctx.guild.owner.id or ctx.message.author.id == owner_id return ctx.message.author.id == ctx.guild.owner.id or ctx.message.author.id == owner_id
return False return False
def is_rcon_admin(bot, ctx): def is_rcon_admin(bot, ctx):
rcon_admin_roles = json.loads(bot.con.one(f"select rcon_admin_roles from guild_config where guild_id = {ctx.guild.id}")) rcon_admin_roles = json.loads(bot.con.one("select rcon_admin_roles from guild_config where guild_id = %(id)s",
{'id': ctx.guild.id}))
for role in rcon_admin_roles: for role in rcon_admin_roles:
if discord.utils.get(ctx.guild.roles, id=rcon_admin_roles[role]) in ctx.message.author.roles: if discord.utils.get(ctx.guild.roles, id=rcon_admin_roles[role]) in ctx.message.author.roles:
return True return True
return ctx.message.author.id == ctx.guild.owner.id or ctx.message.author.id == owner_id return ctx.message.author.id == ctx.guild.owner.id or ctx.message.author.id == owner_id
def is_restricted_chan(ctx): def is_restricted_chan(ctx):
if ctx.guild: if ctx.guild:
if ctx.channel.overwrites_for(ctx.guild.default_role).read_messages == False: if ctx.channel.overwrites_for(ctx.guild.default_role).read_messages is False:
return True return True
return False return False
return False return False
async def is_spam(bot, ctx): async def is_spam(bot, ctx):
max_rep = 5 max_rep = 5
rep_time = 20 rep_time = 20
@ -56,7 +66,8 @@ async def is_spam(bot, ctx):
if msg['author'] == ctx.author: if msg['author'] == ctx.author:
if msg['time'] > ctx.message.created_at.timestamp() - spam_time: if msg['time'] > ctx.message.created_at.timestamp() - spam_time:
spam_check += 1 spam_check += 1
if msg['content'].lower() == ctx.content.lower() and msg['time'] > ctx.message.created_at.timestamp() - rep_time: if msg['content'].lower() == ctx.content.lower() \
and msg['time'] > ctx.message.created_at.timestamp() - rep_time:
msg_check += 1 msg_check += 1
if spam_check == spam_rep - 1 or msg_check == max_rep - 1: if spam_check == spam_rep - 1 or msg_check == max_rep - 1:
await utils.mute(bot, ctx, admin=1, member=ctx.author.id) await utils.mute(bot, ctx, admin=1, member=ctx.author.id)

@ -1,5 +1,7 @@
from io import StringIO from io import StringIO
import sys, asyncio import sys
import asyncio
import discord
from discord.ext.commands.formatter import Paginator from discord.ext.commands.formatter import Paginator
from . import checks from . import checks
@ -9,20 +11,23 @@ class Capturing(list):
self._stdout = sys.stdout self._stdout = sys.stdout
sys.stdout = self._stringio = StringIO() sys.stdout = self._stringio = StringIO()
return self return self
def __exit__(self, *args): def __exit__(self, *args):
self.extend(self._stringio.getvalue().splitlines()) self.extend(self._stringio.getvalue().splitlines())
del self._stringio # free up some memory del self._stringio # free up some memory
sys.stdout = self._stdout sys.stdout = self._stdout
async def mute(bot, ctx, admin=0, member_id=None): async def mute(bot, ctx, admin=0, member_id=None):
mute_role = self.bot.con.one(f'select muted_role from guild_config where guild_id = {ctx.guild.id}') mute_role = bot.con.one(f'select muted_role from guild_config where guild_id = {ctx.guild.id}')
if muted_role: if mute_role:
if admin or checks.is_admin(bot, ctx): if admin or checks.is_admin(bot, ctx):
if ctx.guild.me.guild_permissions.manage_roles: if ctx.guild.me.guild_permissions.manage_roles:
if member: if member_id:
ctx.guild.get_member(member_id).edit(roles=[discord.utils.get(ctx.guild.roles, id=mute_role)]) ctx.guild.get_member(member_id).edit(roles=[discord.utils.get(ctx.guild.roles, id=mute_role)])
def to_list_of_str(items, out:list=[], level=1, recurse=0):
def to_list_of_str(items, out: list=list(), level=1, recurse=0):
def rec_loop(item, key, out, level): def rec_loop(item, key, out, level):
quote = '"' quote = '"'
if type(item) == list: if type(item) == list:
@ -40,7 +45,7 @@ def to_list_of_str(items, out:list=[], level=1, recurse=0):
if type(items) == list: if type(items) == list:
if not recurse: if not recurse:
out = [] out = list()
out.append('[') out.append('[')
for item in items: for item in items:
rec_loop(item, None, out, level) rec_loop(item, None, out, level)
@ -48,7 +53,7 @@ def to_list_of_str(items, out:list=[], level=1, recurse=0):
out.append(']') out.append(']')
elif type(items) == dict: elif type(items) == dict:
if not recurse: if not recurse:
out = [] out = list()
out.append('{') out.append('{')
for key in items: for key in items:
rec_loop(items[key], key, out, level) rec_loop(items[key], key, out, level)
@ -57,8 +62,8 @@ def to_list_of_str(items, out:list=[], level=1, recurse=0):
return out return out
def paginate(text, maxlen=1990): def paginate(text, maxlen=1990):
data = []
paginator = Paginator(prefix='```py', max_size=maxlen+10) paginator = Paginator(prefix='```py', max_size=maxlen+10)
if type(text) == list: if type(text) == list:
data = to_list_of_str(text) data = to_list_of_str(text)
@ -75,6 +80,7 @@ def paginate(text, maxlen=1990):
paginator.add_line(line) paginator.add_line(line)
return paginator.pages return paginator.pages
async def run_command(args): async def run_command(args):
# Create subprocess # Create subprocess
process = await asyncio.create_subprocess_shell( process = await asyncio.create_subprocess_shell(

@ -7,7 +7,8 @@ config_dir = 'config'
extension_dir = 'extensions' extension_dir = 'extensions'
owner_id = 351794468870946827 owner_id = 351794468870946827
class patreon():
class Patreon:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
@ -15,14 +16,16 @@ class patreon():
@commands.command(aliases=['get_patreon', 'patreon']) @commands.command(aliases=['get_patreon', 'patreon'])
@commands.cooldown(1, 5, type=commands.BucketType.user) @commands.cooldown(1, 5, type=commands.BucketType.user)
async def get_patreon_links(self, ctx, target: discord.Member=None): async def get_patreon_links(self, ctx, target: discord.Member=None):
'Prints Patreon information for creators on the server.' """Prints Patreon information for creators on the server."""
if self.bot.con.one('select patreon_enabled from guild_config where guild_id = %(id)s', {'id': ctx.guild.id}): if self.bot.con.one('select patreon_enabled from guild_config where guild_id = %(id)s', {'id': ctx.guild.id}):
patreon_info = self.bot.con.one('select patreon_message,patreon_links from guild_config where guild_id = %(id)s', {'id':ctx.guild.id}) patreon_info = self.bot.con.one('select patreon_message,patreon_links\
from guild_config where guild_id = %(id)s',
{'id': ctx.guild.id})
message = patreon_info[0].replace('\\n', '\n') message = patreon_info[0].replace('\\n', '\n')
patreon_links = json.loads(patreon_info[1]) patreon_links = json.loads(patreon_info[1])
for key in patreon_links: for key in patreon_links:
message = message + '\n{0}: {1}'.format(key, patreon_links[key]) message = message + '\n{0}: {1}'.format(key, patreon_links[key])
if target == None: if target is None:
await ctx.send(message) await ctx.send(message)
else: else:
await ctx.send('{0}\n{1}'.format(target.mention, message)) await ctx.send('{0}\n{1}'.format(target.mention, message))
@ -32,11 +35,13 @@ class patreon():
@commands.command(aliases=['patreon_message']) @commands.command(aliases=['patreon_message'])
async def set_patreon_message(self, ctx, message): async def set_patreon_message(self, ctx, message):
if checks.is_admin(self.bot, ctx): if checks.is_admin(self.bot, ctx):
patreon_message = self.bot.con.one('select patreon_message from guild_config where guild_id = %(id)s', {'id':ctx.guild.id}) patreon_message = self.bot.con.one('select patreon_message from guild_config where guild_id = %(id)s',
{'id': ctx.guild.id})
if message == patreon_message: if message == patreon_message:
await ctx.send('That is already the current message for this guild.') await ctx.send('That is already the current message for this guild.')
else: else:
self.bot.con.run('update guild_config set patreon_message = %(message)s where guild_id = %(id)s', {'id':ctx.guild.id, 'message': message}) self.bot.con.run('update guild_config set patreon_message = %(message)s where guild_id = %(id)s',
{'id': ctx.guild.id, 'message': message})
await ctx.send(f'The patreon message for this guild has been set to:\n{message}') await ctx.send(f'The patreon message for this guild has been set to:\n{message}')
else: else:
await ctx.send(f'You are not authorized to run this command.') await ctx.send(f'You are not authorized to run this command.')
@ -44,7 +49,8 @@ class patreon():
@commands.command(aliases=['add_patreon', 'set_patreon']) @commands.command(aliases=['add_patreon', 'set_patreon'])
async def add_patreon_info(self, ctx, name, url): async def add_patreon_info(self, ctx, name, url):
if checks.is_admin(self.bot, ctx): if checks.is_admin(self.bot, ctx):
patreon_info = self.bot.con.one('select patreon_links from guild_config where guild_id = %(id)s', {'id':ctx.guild.id}) patreon_info = self.bot.con.one('select patreon_links from guild_config where guild_id = %(id)s',
{'id': ctx.guild.id})
patreon_links = {} patreon_links = {}
update = 0 update = 0
if patreon_info: if patreon_info:
@ -52,21 +58,24 @@ class patreon():
if name in patreon_links: if name in patreon_links:
update = 1 update = 1
patreon_links[name] = url patreon_links[name] = url
self.bot.con.run('update guild_config set patreon_links = %(links)s where guild_id = %(id)s', {'id':ctx.guild.id, 'links': json.dumps(patreon_links)}) self.bot.con.run('update guild_config set patreon_links = %(links)s where guild_id = %(id)s',
await ctx.send(f"The Patreon link for {name} has been {'updated to the new url.' if update else'added to the config for this guild.'}") {'id': ctx.guild.id, 'links': json.dumps(patreon_links)})
await ctx.send(f"The Patreon link for {name} has been "
f"{'updated to the new url.' if update else'added to the config for this guild.'}")
else: else:
await ctx.send(f'You are not authorized to run this command.') await ctx.send(f'You are not authorized to run this command.')
@commands.command(aliases=['remove_patreon']) @commands.command(aliases=['remove_patreon'])
async def remove_patreon_info(self, ctx, name): async def remove_patreon_info(self, ctx, name):
if checks.is_admin(self.bot, ctx): if checks.is_admin(self.bot, ctx):
patreon_info = self.bot.con.one('select patreon_links from guild_config where guild_id = %(id)s', {'id':ctx.guild.id}) patreon_info = self.bot.con.one('select patreon_links from guild_config where guild_id = %(id)s',
patreon_links = {} {'id': ctx.guild.id})
if patreon_info: if patreon_info:
patreon_links = json.loads(patreon_info) patreon_links = json.loads(patreon_info)
if name in patreon_links: if name in patreon_links:
del patreon_links[name] del patreon_links[name]
self.bot.con.run('update guild_config set patreon_links = %(links)s where guild_id = %(id)s', {'id':ctx.guild.id, 'links': json.dumps(patreon_links)}) self.bot.con.run('update guild_config set patreon_links = %(links)s where guild_id = %(id)s',
{'id': ctx.guild.id, 'links': json.dumps(patreon_links)})
await ctx.send(f'The Patreon link for {name} has been removed from the config for this guild.') await ctx.send(f'The Patreon link for {name} has been removed from the config for this guild.')
return return
else: else:
@ -79,14 +88,17 @@ class patreon():
@commands.command() @commands.command()
async def enable_patreon(self, ctx, state: bool=True): async def enable_patreon(self, ctx, state: bool=True):
if checks.is_admin(self.bot, ctx): if checks.is_admin(self.bot, ctx):
patreon_status = self.bot.con.one('select patreon_enabled from guild_config where guild_id = %(id)s', {'id':ctx.guild.id}) patreon_status = self.bot.con.one('select patreon_enabled from guild_config where guild_id = %(id)s',
{'id': ctx.guild.id})
if patreon_status and state: if patreon_status and state:
await ctx.send('Patreon is already enabled for this guild.') await ctx.send('Patreon is already enabled for this guild.')
elif patreon_status and not state: elif patreon_status and not state:
self.bot.con.run('update guild_config set patreon_enabled = %(state)s where guild_id = %(id)s', {'id':ctx.guild.id, 'state': state}) self.bot.con.run('update guild_config set patreon_enabled = %(state)s where guild_id = %(id)s',
{'id': ctx.guild.id, 'state': state})
await ctx.send('Patreon has been disabled for this guild.') await ctx.send('Patreon has been disabled for this guild.')
elif not patreon_status and state: elif not patreon_status and state:
self.bot.con.run('update guild_config set patreon_enabled = %(state)s where guild_id = %(id)s', {'id':ctx.guild.id, 'state': state}) self.bot.con.run('update guild_config set patreon_enabled = %(state)s where guild_id = %(id)s',
{'id': ctx.guild.id, 'state': state})
await ctx.send('Patreon has been enabled for this guild.') await ctx.send('Patreon has been enabled for this guild.')
elif not patreon_status and not state: elif not patreon_status and not state:
await ctx.send('Patreon is already disabled for this guild.') await ctx.send('Patreon is already disabled for this guild.')
@ -94,19 +106,21 @@ class patreon():
@commands.command(aliases=['referral', 'ref']) @commands.command(aliases=['referral', 'ref'])
@commands.cooldown(1, 5, type=commands.BucketType.user) @commands.cooldown(1, 5, type=commands.BucketType.user)
async def referral_links(self, ctx, target: discord.Member=None): async def referral_links(self, ctx, target: discord.Member=None):
'Prints G-Portal Referral Links.' """Prints G-Portal Referral Links."""
if self.bot.con.one('select referral_enabled from guild_config where guild_id = %(id)s', {'id': ctx.guild.id}): if self.bot.con.one('select referral_enabled from guild_config where guild_id = %(id)s', {'id': ctx.guild.id}):
referral_info = self.bot.con.one('select referral_message,referral_links from guild_config where guild_id = %(id)s', {'id':ctx.guild.id}) referral_info = self.bot.con.one('select referral_message,referral_links from guild_config\
where guild_id = %(id)s', {'id': ctx.guild.id})
message = referral_info[0] message = referral_info[0]
referral_links = json.loads(referral_info[1]) referral_links = json.loads(referral_info[1])
for key in referral_links: for key in referral_links:
message = message + '\n{0}: {1}'.format(key, referral_links[key]) message = message + '\n{0}: {1}'.format(key, referral_links[key])
if target == None: if target is None:
await ctx.send(message) await ctx.send(message)
else: else:
await ctx.send('{0}\n{1}'.format(target.mention, message)) await ctx.send('{0}\n{1}'.format(target.mention, message))
else: else:
await ctx.send('Referrals are not enabled on this guild.') await ctx.send('Referrals are not enabled on this guild.')
def setup(bot): def setup(bot):
bot.add_cog(patreon(bot)) bot.add_cog(Patreon(bot))

@ -2,7 +2,8 @@ import discord
from discord.ext import commands from discord.ext import commands
import json import json
from srcds import rcon as rcon_con from srcds import rcon as rcon_con
import time, logging import time
import logging
from datetime import datetime from datetime import datetime
import asyncio import asyncio
import traceback import traceback
@ -22,12 +23,14 @@ rcon_log = logging.getLogger('rcon')
game_commands = ['admin', ] game_commands = ['admin', ]
game_prefix = '$' game_prefix = '$'
class rcon():
class Rcon:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
def _listplayers(self, con_info): @staticmethod
def _listplayers(con_info):
con = rcon_con.RconConnection(con_info['ip'], con_info['port'], con_info['password']) con = rcon_con.RconConnection(con_info['ip'], con_info['port'], con_info['password'])
asyncio.sleep(5) asyncio.sleep(5)
response = con.exec_command('listplayers') response = con.exec_command('listplayers')
@ -38,7 +41,8 @@ class rcon():
rcon_log.info(response) rcon_log.info(response)
return response.strip(b'\n \x00\x00').decode('ascii').strip() return response.strip(b'\n \x00\x00').decode('ascii').strip()
def _saveworld(self, con_info): @staticmethod
def _saveworld(con_info):
con = rcon_con.RconConnection(con_info['ip'], con_info['port'], con_info['password']) con = rcon_con.RconConnection(con_info['ip'], con_info['port'], con_info['password'])
asyncio.sleep(5) asyncio.sleep(5)
response = con.exec_command('saveworld') response = con.exec_command('saveworld')
@ -49,7 +53,8 @@ class rcon():
rcon_log.info(response) rcon_log.info(response)
return response.strip(b'\n \x00\x00').decode('ascii').strip() return response.strip(b'\n \x00\x00').decode('ascii').strip()
def _whitelist(self, con_info, steam_ids): @staticmethod
def _whitelist(con_info, steam_ids):
messages = [] messages = []
con = rcon_con.RconConnection(con_info['ip'], con_info['port'], con_info['password']) con = rcon_con.RconConnection(con_info['ip'], con_info['port'], con_info['password'])
asyncio.sleep(5) asyncio.sleep(5)
@ -63,7 +68,8 @@ class rcon():
messages.append(response.strip(b'\n \x00\x00').decode('ascii').strip()) messages.append(response.strip(b'\n \x00\x00').decode('ascii').strip())
return messages return messages
def _broadcast(self, con_info, message): @staticmethod
def _broadcast(con_info, message):
messages = [] messages = []
con = rcon_con.RconConnection(con_info['ip'], con_info['port'], con_info['password']) con = rcon_con.RconConnection(con_info['ip'], con_info['port'], con_info['password'])
asyncio.sleep(5) asyncio.sleep(5)
@ -76,7 +82,8 @@ class rcon():
messages.append(response.strip(b'\n \x00\x00').decode('ascii').strip()) messages.append(response.strip(b'\n \x00\x00').decode('ascii').strip())
return messages return messages
def _get_current_chat(self, con): @staticmethod
def _get_current_chat(con):
response = con.exec_command('getchat') response = con.exec_command('getchat')
rcon_log.debug(response) rcon_log.debug(response)
return response.strip(b'\n \x00\x00').decode('ascii').strip() return response.strip(b'\n \x00\x00').decode('ascii').strip()
@ -94,7 +101,7 @@ class rcon():
for msg in message.split('\n'): for msg in message.split('\n'):
msg = '{0} ||| {1}'.format(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), msg.strip()) msg = '{0} ||| {1}'.format(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), msg.strip())
return_messages.append(msg) return_messages.append(msg)
except rcon_con.RconError as e: except rcon_con.RconError:
rcon_log.error('RCON Error {0}\n{1}'.format(guild_id, traceback.format_exc())) rcon_log.error('RCON Error {0}\n{1}'.format(guild_id, traceback.format_exc()))
return_messages.append('RCON Error') return_messages.append('RCON Error')
except Exception as e: except Exception as e:
@ -104,15 +111,15 @@ class rcon():
rcon_log.debug(return_messages) rcon_log.debug(return_messages)
return return_messages return return_messages
@staticmethod
def admin(ctx, msg, rcon_server, admin_roles):
def admin(self, ctx, msg, rcon_server, admin_roles):
player = msg.split(' ||| ')[1].split(' (')[0] player = msg.split(' ||| ')[1].split(' (')[0]
con = rcon_con.RconConnection(rcon_server['ip'], con = rcon_con.RconConnection(rcon_server['ip'],
rcon_server['port'], rcon_server['port'],
rcon_server['password'], rcon_server['password'],
True) True)
con.exec_command('ServerChatToPlayer "{0}" GeeksBot: Admin Geeks have been notified you need assistance. Please be patient.'.format(player)) con.exec_command('ServerChatToPlayer "{0}" GeeksBot: Admin Geeks have been notified you need assistance. '
'Please be patient.'.format(player))
con._sock.close() con._sock.close()
for role in admin_roles: for role in admin_roles:
msg = '{0} {1}'.format(msg, discord.utils.get(ctx.guild.roles, id=admin_roles[role]).mention) msg = '{0} {1}'.format(msg, discord.utils.get(ctx.guild.roles, id=admin_roles[role]).mention)
@ -124,18 +131,21 @@ class rcon():
'''Begins monitoring the specified ARK server for chat messages and other events. '''Begins monitoring the specified ARK server for chat messages and other events.
The specified server must already be in the current guild\'s configuration. The specified server must already be in the current guild\'s configuration.
To add and remove ARK servers from the guild see add_rcon_server and remove_rcon_server. To add and remove ARK servers from the guild see add_rcon_server and remove_rcon_server.
The server argument is not case sensitive and if the server name has 2 words it can be in one of the following forms: The server argument is not case sensitive and if the server name has two
words it can be in one of the following forms:
first last first last
first_last first_last
"first last" "first last"
To view all the valid ARK servers for this guild see list_ark_servers.''' To view all the valid ARK servers for this guild see list_ark_servers.'''
if checks.is_rcon_admin(self.bot, ctx): if checks.is_rcon_admin(self.bot, ctx):
if server != None: if server is not None:
rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config where guild_id = %(id)s', {'id':ctx.guild.id})) rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config\
where guild_id = %(id)s', {'id': ctx.guild.id}))
server = server.replace('_', ' ').title() server = server.replace('_', ' ').title()
if server in rcon_connections: if server in rcon_connections:
rcon_connections[server]["monitoring_chat"] = 1 rcon_connections[server]["monitoring_chat"] = 1
self.bot.con.run('update guild_config set rcon_connections = %(json)s where guild_id = %(id)s', {'id':ctx.guild.id, 'json': json.dumps(rcon_connections)}) self.bot.con.run('update guild_config set rcon_connections = %(json)s where guild_id = %(id)s',
{'id': ctx.guild.id, 'json': json.dumps(rcon_connections)})
channel = self.bot.get_channel(rcon_connections[server]['game_chat_chan_id']) channel = self.bot.get_channel(rcon_connections[server]['game_chat_chan_id'])
await channel.send('Started monitoring on the {0} server.'.format(server)) await channel.send('Started monitoring on the {0} server.'.format(server))
await ctx.message.add_reaction('') await ctx.message.add_reaction('')
@ -146,7 +156,8 @@ class rcon():
rcon_connections[server]['port'], rcon_connections[server]['port'],
rcon_connections[server]['password'], rcon_connections[server]['password'],
True) True)
messages = await self.bot.loop.run_in_executor(None, self.server_chat_background_process, ctx.guild.id, con) messages = await self.bot.loop.run_in_executor(None, self.server_chat_background_process,
ctx.guild.id, con)
con._sock.close() con._sock.close()
except TimeoutError: except TimeoutError:
rcon_log.error(traceback.format_exc()) rcon_log.error(traceback.format_exc())
@ -169,7 +180,8 @@ class rcon():
message = func(ctx, message, rcon_connections['server']) message = func(ctx, message, rcon_connections['server'])
await channel.send('{0}'.format(message)) await channel.send('{0}'.format(message))
await asyncio.sleep(1) await asyncio.sleep(1)
rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config where guild_id = %(id)s', {'id':ctx.guild.id})) rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config\
where guild_id = %(id)s', {'id': ctx.guild.id}))
await channel.send('Monitoring Stopped') await channel.send('Monitoring Stopped')
else: else:
await ctx.send(f'Server not found: {server}') await ctx.send(f'Server not found: {server}')
@ -181,15 +193,17 @@ class rcon():
@commands.command() @commands.command()
@commands.guild_only() @commands.guild_only()
async def end_monitor_chat(self, ctx, *, server=None): async def end_monitor_chat(self, ctx, *, server=None):
'''Ends chat monitoring on the specified server. """Ends chat monitoring on the specified server.
Context is the same as monitor_chat''' Context is the same as monitor_chat"""
if checks.is_rcon_admin(self.bot, ctx): if checks.is_rcon_admin(self.bot, ctx):
if server != None: if server is not None:
rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config where guild_id = %(id)s', {'id':ctx.guild.id})) rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config\
where guild_id = %(id)s', {'id': ctx.guild.id}))
server = server.replace('_', ' ').title() server = server.replace('_', ' ').title()
if server in rcon_connections: if server in rcon_connections:
rcon_connections[server]["monitoring_chat"] = 0 rcon_connections[server]["monitoring_chat"] = 0
self.bot.con.run('update guild_config set rcon_connections = %(json)s where guild_id = %(id)s', {'id':ctx.guild.id, 'json': json.dumps(rcon_connections)}) self.bot.con.run('update guild_config set rcon_connections = %(json)s where guild_id = %(id)s',
{'id': ctx.guild.id, 'json': json.dumps(rcon_connections)})
else: else:
await ctx.send(f'Server not found: {server}') await ctx.send(f'Server not found: {server}')
else: else:
@ -200,17 +214,19 @@ class rcon():
@commands.command() @commands.command()
@commands.guild_only() @commands.guild_only()
async def listplayers(self, ctx, *, server=None): async def listplayers(self, ctx, *, server=None):
'''Lists the players currently connected to the specified ARK server. """Lists the players currently connected to the specified ARK server.
The specified server must already be in the current guild\'s configuration. The specified server must already be in the current guild\'s configuration.
To add and remove ARK servers from the guild see add_rcon_server and remove_rcon_server. To add and remove ARK servers from the guild see add_rcon_server and remove_rcon_server.
The server argument is not case sensitive and if the server name has 2 words it can be in one of the following forms: The server argument is not case sensitive and if the server name has two
words it can be in one of the following forms:
first last first last
first_last first_last
"first last" "first last"
To view all the valid ARK servers for this guild see list_ark_servers.''' To view all the valid ARK servers for this guild see list_ark_servers."""
if checks.is_rcon_admin(self.bot, ctx): if checks.is_rcon_admin(self.bot, ctx):
rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config where guild_id = %(id)s', {'id':ctx.guild.id})) rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config\
if server != None: where guild_id = %(id)s', {'id': ctx.guild.id}))
if server is not None:
server = server.replace('_', ' ').title() server = server.replace('_', ' ').title()
if server in rcon_connections: if server in rcon_connections:
connection_info = rcon_connections[server] connection_info = rcon_connections[server]
@ -221,7 +237,8 @@ class rcon():
await msg.delete() await msg.delete()
await ctx.send('Players currently on the {0} server:\n{1}'.format(server.title(), message)) await ctx.send('Players currently on the {0} server:\n{1}'.format(server.title(), message))
else: else:
await ctx.send('That server is not in my configuration.\nPlease add it via !add_rcon_server "{0}" "ip" port "password" if you would like to get info from it.'.format(server)) await ctx.send('That server is not in my configuration.\nPlease add it via !add_rcon_server "{0}" '
'"ip" port "password" if you would like to get info from it.'.format(server))
else: else:
for server in rcon_connections: for server in rcon_connections:
try: try:
@ -241,11 +258,12 @@ class rcon():
@commands.command() @commands.command()
@commands.guild_only() @commands.guild_only()
async def add_rcon_server(self, ctx, server, ip, port, password): async def add_rcon_server(self, ctx, server, ip, port, password):
'''Adds the specified server to the current guild\'s rcon config. """Adds the specified server to the current guild\'s rcon config.
All strings (<server>, <ip>, <password>) must be contained inside double quotes.''' All strings (<server>, <ip>, <password>) must be contained inside double quotes."""
if checks.is_rcon_admin(self.bot, ctx): if checks.is_rcon_admin(self.bot, ctx):
server = server.title() server = server.title()
rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config where guild_id = %(id)s', {'id':ctx.guild.id})) rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config\
where guild_id = %(id)s', {'id': ctx.guild.id}))
if server not in rcon_connections: if server not in rcon_connections:
rcon_connections[server] = { rcon_connections[server] = {
'ip': ip, 'ip': ip,
@ -256,7 +274,8 @@ class rcon():
'msg_chan_id': 0, 'msg_chan_id': 0,
'monitoring_chat': 0 'monitoring_chat': 0
} }
self.bot.con.run('update guild_config set rcon_connections = %(connections)s where guild_id = %(id)s', {'id':ctx.guild.id, 'connections':json.dumps(rcon_connections)}) self.bot.con.run('update guild_config set rcon_connections = %(connections)s where guild_id = %(id)s',
{'id': ctx.guild.id, 'connections': json.dumps(rcon_connections)})
await ctx.send('{0} server has been added to my configuration.'.format(server)) await ctx.send('{0} server has been added to my configuration.'.format(server))
else: else:
await ctx.send('This server name is already in my configuration. Please choose another.') await ctx.send('This server name is already in my configuration. Please choose another.')
@ -268,14 +287,16 @@ class rcon():
@commands.command() @commands.command()
@commands.guild_only() @commands.guild_only()
async def remove_rcon_server(self, ctx, server): async def remove_rcon_server(self, ctx, server):
'''removes the specified server from the current guild\'s rcon config. """removes the specified server from the current guild\'s rcon config.
All strings <server> must be contained inside double quotes.''' All strings <server> must be contained inside double quotes."""
if checks.is_rcon_admin(self.bot, ctx): if checks.is_rcon_admin(self.bot, ctx):
server = server.title() server = server.title()
rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config where guild_id = %(id)s', {'id':ctx.guild.id})) rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config\
where guild_id = %(id)s', {'id': ctx.guild.id}))
if server in rcon_connections: if server in rcon_connections:
del rcon_connections[server] del rcon_connections[server]
self.bot.con.run('update guild_config set rcon_connections = %(connections)s where guild_id = %(id)s', {'id':ctx.guild.id, 'connections':json.dumps(rcon_connections)}) self.bot.con.run('update guild_config set rcon_connections = %(connections)s where guild_id = %(id)s',
{'id': ctx.guild.id, 'connections': json.dumps(rcon_connections)})
await ctx.send('{0} has been removed from my configuration.'.format(server)) await ctx.send('{0} has been removed from my configuration.'.format(server))
else: else:
await ctx.send('{0} is not in my configuration.'.format(server)) await ctx.send('{0} is not in my configuration.'.format(server))
@ -285,12 +306,13 @@ class rcon():
@commands.command() @commands.command()
@commands.guild_only() @commands.guild_only()
async def add_whitelist(self, ctx, *, steam_ids=None): async def add_whitelist(self, ctx, *, steam_ids=None):
'''Adds the included Steam 64 IDs to the running whitelist on all the ARK servers in the current guild\'s rcon config. """Adds the included Steam 64 IDs to the running whitelist on all the ARK servers in the current guild\'s rcon config.
Steam 64 IDs should be a comma seperated list of IDs. Steam 64 IDs should be a comma seperated list of IDs.
Example: 76561198024193239,76561198024193239,76561198024193239''' Example: 76561198024193239,76561198024193239,76561198024193239"""
if checks.is_rcon_admin(self.bot, ctx): if checks.is_rcon_admin(self.bot, ctx):
if steam_ids != None: if steam_ids is not None:
rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config where guild_id = %(id)s', {'id':ctx.guild.id})) rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config\
where guild_id = %(id)s', {'id': ctx.guild.id}))
error = 0 error = 0
error_msg = '' error_msg = ''
success_msg = 'Adding to the running whitelist on all servers.' success_msg = 'Adding to the running whitelist on all servers.'
@ -309,7 +331,10 @@ class rcon():
try: try:
success_msg = '{0}\n\n{1}:'.format(success_msg, server.title()) success_msg = '{0}\n\n{1}:'.format(success_msg, server.title())
await msg.edit(content=success_msg.strip()) await msg.edit(content=success_msg.strip())
messages = await self.bot.loop.run_in_executor(None, self._whitelist, rcon_connections[server], steam_ids) messages = await self.bot.loop.run_in_executor(None,
self._whitelist,
rcon_connections[server],
steam_ids)
except Exception as e: except Exception as e:
success_msg = '{0}\n{1}'.format(success_msg, e.strip()) success_msg = '{0}\n{1}'.format(success_msg, e.strip())
await msg.edit(content=success_msg.strip()) await msg.edit(content=success_msg.strip())
@ -328,17 +353,15 @@ class rcon():
@commands.command() @commands.command()
@commands.guild_only() @commands.guild_only()
async def saveworld(self, ctx, *, server=None): async def saveworld(self, ctx, *, server=None):
'''Runs SaveWorld on the specified ARK server. """Runs SaveWorld on the specified ARK server.
If a server is not specified it will default to running saveworld on all servers in the guild\'s config. If a server is not specified it will default to running saveworld on all servers in the guild\'s config.
Will print out "World Saved" for each server when the command completes sucessfully.''' Will print out "World Saved" for each server when the command completes successfully."""
if checks.is_rcon_admin(self.bot, ctx): if checks.is_rcon_admin(self.bot, ctx):
rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config where guild_id = %(id)s', {'id':ctx.guild.id})) rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config\
where guild_id = %(id)s', {'id': ctx.guild.id}))
success_msg = 'Running saveworld' success_msg = 'Running saveworld'
if server == None: if server is None:
success_msg += ' on all the servers:' success_msg += ' on all the servers:'
# server = server.replace('_',' ').title()
if server in rcon_connections:
connection_info = rcon_connections[server]
msg = await ctx.send(success_msg) msg = await ctx.send(success_msg)
for server in rcon_connections: for server in rcon_connections:
try: try:
@ -352,8 +375,8 @@ class rcon():
success_msg = '{0}\n{1}'.format(success_msg, message.strip()) success_msg = '{0}\n{1}'.format(success_msg, message.strip())
await msg.edit(content=success_msg.strip()) await msg.edit(content=success_msg.strip())
await msg.add_reaction('') await msg.add_reaction('')
elif server.title() in rcon_connections: elif server.replace('_', ' ').title() in rcon_connections:
success_msg = '{0} {1}:'.format(success_msg, server.title()) success_msg = '{0} {1}:'.format(success_msg, server.replace('_', ' ').title())
msg = await ctx.send(success_msg) msg = await ctx.send(success_msg)
message = await self.bot.loop.run_in_executor(None, self._saveworld, rcon_connections[server.title()]) message = await self.bot.loop.run_in_executor(None, self._saveworld, rcon_connections[server.title()])
success_msg = '{0}\n{1}'.format(success_msg, message.strip()) success_msg = '{0}\n{1}'.format(success_msg, message.strip())
@ -366,18 +389,19 @@ class rcon():
@commands.group(case_insensitive=True) @commands.group(case_insensitive=True)
async def broadcast(self, ctx): async def broadcast(self, ctx):
'''Run help broadcast for more info''' """Run help broadcast for more info"""
pass pass
@broadcast.command(name='all') @broadcast.command(name='all')
@commands.guild_only() @commands.guild_only()
async def broadcast_all(self, ctx, *, message=None): async def broadcast_all(self, ctx, *, message=None):
'''Sends a broadcast message to all servers in the guild config. """Sends a broadcast message to all servers in the guild config.
The message will be prefixed with the Discord name of the person running the command. The message will be prefixed with the Discord name of the person running the command.
Will print "Success" for each server once the broadcast is sent.''' Will print "Success" for each server once the broadcast is sent."""
if checks.is_rcon_admin(self.bot, ctx): if checks.is_rcon_admin(self.bot, ctx):
rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config where guild_id = %(id)s', {'id':ctx.guild.id})) rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config\
if message != None: where guild_id = %(id)s', {'id': ctx.guild.id}))
if message is not None:
message = f'{ctx.author.display_name}: {message}' message = f'{ctx.author.display_name}: {message}'
success_msg = f'Broadcasting "{message}" to all servers.' success_msg = f'Broadcasting "{message}" to all servers.'
msg = await ctx.send(success_msg) msg = await ctx.send(success_msg)
@ -385,7 +409,10 @@ class rcon():
try: try:
success_msg = '{0}\n\n{1}:'.format(success_msg, server.title()) success_msg = '{0}\n\n{1}:'.format(success_msg, server.title())
await msg.edit(content=success_msg.strip()) await msg.edit(content=success_msg.strip())
messages = await self.bot.loop.run_in_executor(None, self._broadcast, rcon_connections[server], message) messages = await self.bot.loop.run_in_executor(None,
self._broadcast,
rcon_connections[server],
message)
except Exception as e: except Exception as e:
success_msg = '{0}\n{1}'.format(success_msg, e.strip()) success_msg = '{0}\n{1}'.format(success_msg, e.strip())
await msg.edit(content=success_msg.strip()) await msg.edit(content=success_msg.strip())
@ -404,19 +431,24 @@ class rcon():
@broadcast.command(name='server') @broadcast.command(name='server')
@commands.guild_only() @commands.guild_only()
async def broadcast_server(self, ctx, server, *, message=None): async def broadcast_server(self, ctx, server, *, message=None):
'''Sends a broadcast message to the specified server that is in the guild's config. """Sends a broadcast message to the specified server that is in the guild's config.
The message will be prefixed with the Discord name of the person running the command. The message will be prefixed with the Discord name of the person running the command.
If <server> has more than one word in it's name it will either need to be sorrounded by double quotes or the words seperated by _''' If <server> has more than one word in it's name it will either need to be surrounded
by double quotes or the words separated by _"""
if checks.is_rcon_admin(self.bot, ctx): if checks.is_rcon_admin(self.bot, ctx):
rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config where guild_id = %(id)s', {'id':ctx.guild.id})) rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config\
if server != None: where guild_id = %(id)s', {'id': ctx.guild.id}))
if server is not None:
server = server.replace('_', ' ').title() server = server.replace('_', ' ').title()
if message != None: if message is not None:
message = f'{ctx.author.display_name}: {message}' message = f'{ctx.author.display_name}: {message}'
success_msg = f'Broadcasting "{message}" to {server}.' success_msg = f'Broadcasting "{message}" to {server}.'
msg = await ctx.send(success_msg) msg = await ctx.send(success_msg)
if server in rcon_connections: if server in rcon_connections:
messages = await self.bot.loop.run_in_executor(None, self._broadcast, rcon_connections[server], message) messages = await self.bot.loop.run_in_executor(None,
self._broadcast,
rcon_connections[server],
message)
for mesg in messages: for mesg in messages:
if mesg != 'Server received, But no response!!': if mesg != 'Server received, But no response!!':
success_msg = '{0}\n{1}'.format(success_msg, mesg.strip()) success_msg = '{0}\n{1}'.format(success_msg, mesg.strip())
@ -434,16 +466,19 @@ class rcon():
@commands.command() @commands.command()
@commands.guild_only() @commands.guild_only()
async def create_server_chat_chans(self, ctx): async def create_server_chat_chans(self, ctx):
'''Creates a category and server chat channels in the current guild. """Creates a category and server chat channels in the current guild.
The category will be named "Server Chats" and read_messages is disabled for the guild default role (everyone) The category will be named "Server Chats" and read_messages is disabled for the guild default role (everyone)
This can be overridden by modifying the category's permissions. This can be overridden by modifying the category's permissions.
Inside this category a channel will be created for each server in the current guild's rcon config and these channel's permissions will be synced to the category. Inside this category a channel will be created for each server in the current guild's rcon config
These channels will be added to the guild's rcon config and are where the server chat messages will be sent when monitor_chat is run.''' and these channel's permissions will be synced to the category.
These channels will be added to the guild's rcon config and are where the
server chat messages will be sent when monitor_chat is run."""
if checks.is_rcon_admin(self.bot, ctx): if checks.is_rcon_admin(self.bot, ctx):
rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config where guild_id = %(id)s', {'id':ctx.guild.id})) rcon_connections = json.loads(self.bot.con.one('select rcon_connections from guild_config\
where guild_id = %(id)s', {'id': ctx.guild.id}))
edited = 0 edited = 0
category = discord.utils.get(ctx.guild.categories, name='Server Chats') category = discord.utils.get(ctx.guild.categories, name='Server Chats')
if category == None: if category is None:
overrides = {ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False)} overrides = {ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False)}
category = await ctx.guild.create_category('Server Chats', overwrites=overrides) category = await ctx.guild.create_category('Server Chats', overwrites=overrides)
channels = ctx.guild.channels channels = ctx.guild.channels
@ -453,7 +488,7 @@ class rcon():
cat_chans.append(channel) cat_chans.append(channel)
for server in rcon_connections: for server in rcon_connections:
exists = 0 exists = 0
if cat_chans != []: if cat_chans:
for channel in cat_chans: for channel in cat_chans:
if rcon_connections[server]['game_chat_chan_id'] == channel.id: if rcon_connections[server]['game_chat_chan_id'] == channel.id:
exists = 1 exists = 1
@ -463,7 +498,8 @@ class rcon():
rcon_connections[server]['game_chat_chan_id'] = chan.id rcon_connections[server]['game_chat_chan_id'] = chan.id
edited = 1 edited = 1
if edited == 1: if edited == 1:
self.bot.con.run('update guild_config set rcon_connections = %(json)s where guild_id = %(id)s', {'id':ctx.guild.id, 'json': json.dumps(rcon_connections)}) self.bot.con.run('update guild_config set rcon_connections = %(json)s where guild_id = %(id)s',
{'id': ctx.guild.id, 'json': json.dumps(rcon_connections)})
await ctx.message.add_reaction('') await ctx.message.add_reaction('')
else: else:
await ctx.send(f'You are not authorized to run this command.') await ctx.send(f'You are not authorized to run this command.')
@ -472,8 +508,9 @@ class rcon():
@commands.guild_only() @commands.guild_only()
@commands.check(checks.is_restricted_chan) @commands.check(checks.is_restricted_chan)
async def list_ark_servers(self, ctx): async def list_ark_servers(self, ctx):
'''Returns a list of all the ARK servers in the current guild\'s config.''' """Returns a list of all the ARK servers in the current guild\'s config."""
servers = json.loads(self.bot.con.one('select rcon_connections from guild_config where guild_id = %(id)s', {'id':ctx.guild.id})) servers = json.loads(self.bot.con.one('select rcon_connections from guild_config\
where guild_id = %(id)s', {'id': ctx.guild.id}))
em = discord.Embed(style='rich', em = discord.Embed(style='rich',
title=f'__**There are currently {len(servers)} ARK servers in my config:**__', title=f'__**There are currently {len(servers)} ARK servers in my config:**__',
color=discord.Colour.green() color=discord.Colour.green()
@ -481,9 +518,13 @@ class rcon():
if ctx.guild.icon: if ctx.guild.icon:
em.set_thumbnail(url=f'{ctx.guild.icon_url}') em.set_thumbnail(url=f'{ctx.guild.icon_url}')
for server in servers: for server in servers:
description = f" **IP:** {servers[server]['ip']}:{servers[server]['port']}\n **Steam Connect:** [steam://connect/{servers[server]['ip']}:{servers[server]['port']}](steam://connect/{servers[server]['ip']}:{servers[server]['port']})" description = f"""
**IP:** {servers[server]['ip']}:{servers[server]['port']}
**Steam Connect:** [steam://connect/{servers[server]['ip']}:{servers[server]['port']}]\
(steam://connect/{servers[server]['ip']}:{servers[server]['port']})"""
em.add_field(name=f'__***{server}***__', value=description, inline=False) em.add_field(name=f'__***{server}***__', value=description, inline=False)
await ctx.send(embed=em) await ctx.send(embed=em)
def setup(bot): def setup(bot):
bot.add_cog(rcon(bot)) bot.add_cog(Rcon(bot))

@ -1,8 +1,5 @@
from discord.ext import commands from discord.ext import commands
import time
import datetime
import math
import asyncio import asyncio
import traceback import traceback
import discord import discord
@ -10,28 +7,28 @@ import inspect
import textwrap import textwrap
from contextlib import redirect_stdout from contextlib import redirect_stdout
import io import io
import os, sys
import subprocess
import async_timeout
from .imports.utils import paginate, run_command from .imports.utils import paginate, run_command
ownerids = [351794468870946827, 275280442884751360] ownerids = [351794468870946827, 275280442884751360]
ownerid = 351794468870946827 ownerid = 351794468870946827
class REPL():
class Repl:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self._last_result = None self._last_result = None
self.sessions = set() self.sessions = set()
def cleanup_code(self, content): @staticmethod
'Automatically removes code blocks from the code.' def cleanup_code(content):
"""Automatically removes code blocks from the code."""
if content.startswith('```') and content.endswith('```'): if content.startswith('```') and content.endswith('```'):
return '\n'.join(content.split('\n')[1:(- 1)]) return '\n'.join(content.split('\n')[1:(- 1)])
return content.strip('` \n') return content.strip('` \n')
def get_syntax_error(self, e): @staticmethod
def get_syntax_error(e):
if e.text is None: if e.text is None:
return '```py\n{0.__class__.__name__}: {0}\n```'.format(e) return '```py\n{0.__class__.__name__}: {0}\n```'.format(e)
return '```py\n{0.text}{1:>{0.offset}}\n{2}: {0}```'.format(e, '^', type(e).__name__) return '```py\n{0.text}{1:>{0.offset}}\n{2}: {0}```'.format(e, '^', type(e).__name__)
@ -61,14 +58,14 @@ class REPL():
try: try:
with redirect_stdout(stdout): with redirect_stdout(stdout):
ret = await func() ret = await func()
except Exception as e: except Exception:
value = stdout.getvalue() value = stdout.getvalue()
await ctx.send('```py\n{}{}\n```'.format(value, traceback.format_exc())) await ctx.send('```py\n{}{}\n```'.format(value, traceback.format_exc()))
else: else:
value = stdout.getvalue() value = stdout.getvalue()
try: try:
await ctx.message.add_reaction('') await ctx.message.add_reaction('')
except: except Exception:
pass pass
if ret is None: if ret is None:
if value: if value:
@ -131,7 +128,7 @@ class REPL():
result = executor(code, variables) result = executor(code, variables)
if inspect.isawaitable(result): if inspect.isawaitable(result):
result = await result result = await result
except Exception as e: except Exception:
value = stdout.getvalue() value = stdout.getvalue()
fmt = '{}{}'.format(value, traceback.format_exc()) fmt = '{}{}'.format(value, traceback.format_exc())
else: else:
@ -171,5 +168,6 @@ class REPL():
await ctx.send(page) await ctx.send(page)
await ctx.message.add_reaction('') await ctx.message.add_reaction('')
def setup(bot): def setup(bot):
bot.add_cog(REPL(bot)) bot.add_cog(Repl(bot))

@ -1,15 +1,13 @@
import discord import discord
from discord.ext import commands from discord.ext import commands
import json import json
from srcds import rcon as rcon_con import logging
import time, logging, math, psutil import math
import psutil
from datetime import datetime, timedelta from datetime import datetime, timedelta
import asyncio, inspect import asyncio
import aiohttp, async_timeout import async_timeout
from bs4 import BeautifulSoup as bs
import traceback
from .imports import checks from .imports import checks
from .imports.utils import paginate
import pytz import pytz
import gspread import gspread
from oauth2client.service_account import ServiceAccountCredentials from oauth2client.service_account import ServiceAccountCredentials
@ -25,7 +23,8 @@ invite_match = '(https?://)?(www.)?discord(app.com/(invite|oauth2)|.gg|.io)/[\w\
utils_log = logging.getLogger('utils') utils_log = logging.getLogger('utils')
clock_emojis = ['🕛', '🕐', '🕑', '🕒', '🕓', '🕔', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚'] clock_emojis = ['🕛', '🕐', '🕑', '🕒', '🕓', '🕔', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚']
class utils():
class Utils:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
@ -53,17 +52,22 @@ class utils():
@commands.command() @commands.command()
@commands.is_owner() @commands.is_owner()
async def sysinfo(self, ctx): async def sysinfo(self, ctx):
await ctx.send(f'```ml\nCPU Percentages: {psutil.cpu_percent(percpu=True)}\nMemory Usage: {psutil.virtual_memory().percent}%\nDisc Usage: {psutil.disk_usage("/").percent}%```') await ctx.send(f'''
```ml
CPU Percentages: {psutil.cpu_percent(percpu=True)}
Memory Usage: {psutil.virtual_memory().percent}%
Disc Usage: {psutil.disk_usage("/").percent}%
```''')
@commands.command(hidden=True) @commands.command(hidden=True)
async def role(self, ctx, role): async def role(self, ctx, role):
if ctx.guild.id == 396156980974059531 and role != 'Admin' and role != 'Admin Geeks': if ctx.guild.id == 396156980974059531 and role != 'Admin' and role != 'Admin Geeks':
try: try:
role = discord.utils.get(ctx.guild.roles, name=role) role = discord.utils.get(ctx.guild.roles, name=role)
except: except Exception:
await ctx.send('Unknown Role') await ctx.send('Unknown Role')
else: else:
if role != None: if role is not None:
await ctx.message.author.add_roles(role) await ctx.message.author.add_roles(role)
await ctx.send("Roles Updated") await ctx.send("Roles Updated")
else: else:
@ -74,67 +78,101 @@ class utils():
@commands.command(aliases=['oauth', 'link']) @commands.command(aliases=['oauth', 'link'])
@commands.cooldown(1, 5, type=commands.BucketType.user) @commands.cooldown(1, 5, type=commands.BucketType.user)
async def invite(self, ctx, guy: discord.User=None): async def invite(self, ctx, guy: discord.User=None):
'''Shows you the bot's invite link. """Shows you the bot's invite link.
If you pass in an ID of another bot, it gives you the invite link to that bot. If you pass in an ID of another bot, it gives you the invite link to that bot.
''' """
guy = guy or self.bot.user guy = guy or self.bot.user
url = discord.utils.oauth_url(guy.id) url = discord.utils.oauth_url(guy.id)
await ctx.send(f'**{url}**') await ctx.send(f'**{url}**')
def create_date_string(self, time, time_now): @staticmethod
def create_date_string(time, time_now):
diff = (time_now - time) diff = (time_now - time)
date_str = time.strftime('%Y-%m-%d %H:%M:%S') date_str = time.strftime('%Y-%m-%d %H:%M:%S')
return f"{diff.days} {'day' if diff.days == 1 else 'days'} {diff.seconds // 3600} {'hour' if diff.seconds // 3600 == 1 else 'hours'} {diff.seconds % 3600 // 60} {'minute' if diff.seconds % 3600 // 60 == 1 else 'minutes'} {diff.seconds % 3600 % 60} {'second' if diff.seconds % 3600 % 60 == 1 else 'seconds'} ago.\n{date_str}" return f"{diff.days} {'day' if diff.days == 1 else 'days'} " \
f"{diff.seconds // 3600} {'hour' if diff.seconds // 3600 == 1 else 'hours'} " \
f"{diff.seconds % 3600 // 60} {'minute' if diff.seconds % 3600 // 60 == 1 else 'minutes'} " \
f"{diff.seconds % 3600 % 60} {'second' if diff.seconds % 3600 % 60 == 1 else 'seconds'} ago.\n{date_str}"
@commands.command() @commands.command()
@commands.cooldown(1, 5, type=commands.BucketType.user) @commands.cooldown(1, 5, type=commands.BucketType.user)
async def me(self, ctx): async def me(self, ctx):
'Prints out your user information.' """Prints out your user information."""
em = discord.Embed(style='rich', em = discord.Embed(style='rich',
title=f'{ctx.author.name}#{ctx.author.discriminator} ({ctx.author.display_name})', title=f'{ctx.author.name}#{ctx.author.discriminator} ({ctx.author.display_name})',
description=f'({ctx.author.id})', description=f'({ctx.author.id})',
color=embed_color) color=embed_color)
em.set_thumbnail(url=f'{ctx.author.avatar_url}') em.set_thumbnail(url=f'{ctx.author.avatar_url}')
em.add_field(name=f'Highest Role:', value=f'{ctx.author.top_role}', inline=True) em.add_field(name=f'Highest Role:',
em.add_field(name=f'Bot:', value=f'{ctx.author.bot}', inline=True) value=f'{ctx.author.top_role}',
em.add_field(name=f'Joined Guild:', value=f'{self.create_date_string(ctx.author.joined_at,ctx.message.created_at)}', inline=False) inline=True)
em.add_field(name=f'Joined Discord:', value=f'{self.create_date_string(ctx.author.created_at,ctx.message.created_at)}', inline=False) em.add_field(name=f'Bot:',
em.add_field(name=f'Current Status:', value=f'{ctx.author.status}', inline=True) value=f'{ctx.author.bot}',
em.add_field(name=f"Currently{' '+ctx.author.activity.type.name.title() if ctx.author.activity else ''}:", value=f"{ctx.author.activity.name if ctx.author.activity else 'Not doing anything important.'}", inline=True) inline=True)
em.add_field(name=f'Joined Guild:',
value=f'{self.create_date_string(ctx.author.joined_at, ctx.message.created_at)}',
inline=False)
em.add_field(name=f'Joined Discord:',
value=f'{self.create_date_string(ctx.author.created_at, ctx.message.created_at)}',
inline=False)
em.add_field(name=f'Current Status:',
value=f'{ctx.author.status}',
inline=True)
em.add_field(name=f"Currently{' '+ctx.author.activity.type.name.title() if ctx.author.activity else ''}:",
value=f"{ctx.author.activity.name if ctx.author.activity else 'Not doing anything important.'}",
inline=True)
count = 0 count = 0
async for message in ctx.channel.history(after=(ctx.message.created_at - timedelta(hours=1))): async for message in ctx.channel.history(after=(ctx.message.created_at - timedelta(hours=1))):
if message.author == ctx.author: if message.author == ctx.author:
count += 1 count += 1
em.add_field(name=f'Activity:', value=f'You have sent {count} {"message" if count == 1 else "messages"} in the last hour to this channel.', inline=False) em.add_field(name=f'Activity:',
value=f'You have sent {count} '
f'{"message" if count == 1 else "messages"} in the last hour to this channel.',
inline=False)
await ctx.send(embed=em) await ctx.send(embed=em)
@commands.command() @commands.command()
@commands.cooldown(1, 5, type=commands.BucketType.user) @commands.cooldown(1, 5, type=commands.BucketType.user)
async def user(self, ctx, member: discord.Member): async def user(self, ctx, member: discord.Member):
'''Prints User information. """Prints User information.
<member> should be in the form @Dusty.P#0001''' <member> should be in the form @Dusty.P#0001"""
em = discord.Embed(style='rich', em = discord.Embed(style='rich',
title=f'{member.name}#{member.discriminator} ({member.display_name})', title=f'{member.name}#{member.discriminator} ({member.display_name})',
description=f'({member.id})', description=f'({member.id})',
color=embed_color) color=embed_color)
em.set_thumbnail(url=f'{member.avatar_url}') em.set_thumbnail(url=f'{member.avatar_url}')
em.add_field(name=f'Highest Role:', value=f'{member.top_role}', inline=True) em.add_field(name=f'Highest Role:',
em.add_field(name=f'Bot:', value=f'{member.bot}', inline=True) value=f'{member.top_role}',
em.add_field(name=f'Joined Guild:', value=f'{self.create_date_string(member.joined_at,ctx.message.created_at)}', inline=False) inline=True)
em.add_field(name=f'Joined Discord:', value=f'{self.create_date_string(member.created_at,ctx.message.created_at)}', inline=False) em.add_field(name=f'Bot:',
em.add_field(name=f'Current Status:', value=f'{member.status}', inline=True) value=f'{member.bot}',
em.add_field(name=f"Currently{' '+member.activity.type.name.title() if member.activity else ''}:", value=f"{member.activity.name if member.activity else 'Not doing anything important.'}", inline=True) inline=True)
em.add_field(name=f'Joined Guild:',
value=f'{self.create_date_string(member.joined_at,ctx.message.created_at)}',
inline=False)
em.add_field(name=f'Joined Discord:',
value=f'{self.create_date_string(member.created_at,ctx.message.created_at)}',
inline=False)
em.add_field(name=f'Current Status:',
value=f'{member.status}',
inline=True)
em.add_field(name=f"Currently{' '+member.activity.type.name.title() if member.activity else ''}:",
value=f"{member.activity.name if member.activity else 'Not doing anything important.'}",
inline=True)
count = 0 count = 0
async for message in ctx.channel.history(after=(ctx.message.created_at - timedelta(hours=1))): async for message in ctx.channel.history(after=(ctx.message.created_at - timedelta(hours=1))):
if message.author == member: if message.author == member:
count += 1 count += 1
em.add_field(name=f'Activity:', value=f'{member.display_name} has sent {count} {"message" if count == 1 else "messages"} in the last hour to this channel.', inline=False) em.add_field(name=f'Activity:',
value=f'{member.display_name} has sent {count} '
f'{"message" if count == 1 else "messages"} in the last hour to this channel.',
inline=False)
await ctx.send(embed=em) await ctx.send(embed=em)
@commands.command() @commands.command()
@commands.cooldown(1, 5, type=commands.BucketType.user) @commands.cooldown(1, 5, type=commands.BucketType.user)
async def ping(self, ctx, mode='normal', count: int=2): async def ping(self, ctx, mode='normal', count: int=2):
'Check the Bot\'s connection to Discord' """Check the Bot\'s connection to Discord"""
em = discord.Embed(style='rich', em = discord.Embed(style='rich',
title=f'Pong 🏓', title=f'Pong 🏓',
color=discord.Colour.green() color=discord.Colour.green()
@ -142,13 +180,14 @@ class utils():
msg = await ctx.send(embed=em) msg = await ctx.send(embed=em)
time1 = ctx.message.created_at time1 = ctx.message.created_at
time = (msg.created_at - time1).total_seconds() * 1000 time = (msg.created_at - time1).total_seconds() * 1000
em.description = f'Response Time: **{math.ceil(time)}ms**\nDiscord Latency: **{math.ceil(self.bot.latency*1000)}ms**' em.description = f'''Response Time: **{math.ceil(time)}ms**
Discord Latency: **{math.ceil(self.bot.latency*1000)}ms**'''
await msg.edit(embed=em) await msg.edit(embed=em)
if mode == 'comp': if mode == 'comp':
try: try:
count = int(count) count = int(count)
except: except Exception:
await ctx.send('Not a valid count. Must be a whole number.') await ctx.send('Not a valid count. Must be a whole number.')
else: else:
if count > 24: if count > 24:
@ -170,7 +209,10 @@ class utils():
time = now - self.bot.ping_times[i]['snd'].created_at time = now - self.bot.ping_times[i]['snd'].created_at
time = time.total_seconds() time = time.total_seconds()
times.append(time) times.append(time)
value = f"Message Sent: {datetime.strftime(self.bot.ping_times[i]['snd'].created_at, '%H:%M:%S.%f')}\nResponse Received: {datetime.strftime(now, '%H:%M:%S.%f')}\nTotal Time: {math.ceil(time * 1000)}ms" value = f"Message Sent:" \
f"{datetime.strftime(self.bot.ping_times[i]['snd'].created_at, '%H:%M:%S.%f')}" \
f"Response Received: {datetime.strftime(now, '%H:%M:%S.%f')}" \
f"Total Time: {math.ceil(time * 1000)}ms"
await self.bot.ping_times[i]['rec'].delete() await self.bot.ping_times[i]['rec'].delete()
em.add_field(name=f'Ping Test {i}', value=value, inline=True) em.add_field(name=f'Ping Test {i}', value=value, inline=True)
else: else:
@ -179,32 +221,39 @@ class utils():
print(times) print(times)
for time in times: for time in times:
total_time += time * 1000 total_time += time * 1000
em.add_field(value=f'Total Time for Comprehensive test: {math.ceil(total_time)}ms', name=f'Average: **{round(total_time/count,1)}ms**', inline=False) em.add_field(value=f'Total Time for Comprehensive test: {math.ceil(total_time)}ms',
name=f'Average: **{round(total_time/count,1)}ms**',
inline=False)
await msg.edit(embed=em) await msg.edit(embed=em)
@commands.group(case_insensitive=True) @commands.group(case_insensitive=True)
async def admin(self, ctx): async def admin(self, ctx):
'''Run help admin for more info''' """Run help admin for more info"""
pass pass
@admin.command(name='new', aliases=['nr']) @admin.command(name='new', aliases=['nr'])
@commands.cooldown(1, 30, type=commands.BucketType.user) @commands.cooldown(1, 30, type=commands.BucketType.user)
async def new_admin_request(self, ctx, *, request_msg=None): async def new_admin_request(self, ctx, *, request_msg=None):
'''Submit a new request for admin assistance. """Submit a new request for admin assistance.
The admin will be notified when your request is made and it will be added to the request list for this guild. The admin will be notified when your request is made and it will be added to the request list for this guild.
''' """
if ctx.guild: if ctx.guild:
if request_msg != None: if request_msg is not None:
if len(request_msg) < 1000: if len(request_msg) < 1000:
self.bot.con.run('insert into admin_requests (issuing_member_id, guild_orig, request_text, request_time) values (%(member_id)s, %(guild_id)s, %(text)s, %(time)s)', self.bot.con.run('insert into admin_requests (issuing_member_id, guild_orig, request_text,'
{'member_id': ctx.author.id, 'guild_id': ctx.guild.id, 'text': request_msg, 'time': ctx.message.created_at}) 'request_time) values (%(member_id)s, %(guild_id)s, %(text)s, %(time)s)',
{'member_id': ctx.author.id, 'guild_id': ctx.guild.id, 'text': request_msg,
'time': ctx.message.created_at})
channel = self.bot.con.one(f'select admin_chat from guild_config where guild_id = {ctx.guild.id}') channel = self.bot.con.one(f'select admin_chat from guild_config where guild_id = {ctx.guild.id}')
if channel: if channel:
chan = discord.utils.get(ctx.guild.channels, id=channel) chan = discord.utils.get(ctx.guild.channels, id=channel)
msg = '' msg = ''
admin_roles = [] admin_roles = []
roles = self.bot.con.one(f'select admin_roles,rcon_admin_roles from guild_config where guild_id = {ctx.guild.id}') roles = self.bot.con.one(f'select admin_roles,rcon_admin_roles from guild_config where '
request_id = self.bot.con.one(f'select id from admin_requests where issuing_member_id = %(member_id)s and request_time = %(time)s', {'member_id': ctx.author.id, 'time': ctx.message.created_at}) f'guild_id = %(id)s', {'id': ctx.guild.id})
request_id = self.bot.con.one(f'select id from admin_requests where '
f'issuing_member_id = %(member_id)s and request_time = %(time)s',
{'member_id': ctx.author.id, 'time': ctx.message.created_at})
for item in roles: for item in roles:
i = json.loads(item) i = json.loads(item)
for j in i: for j in i:
@ -212,7 +261,10 @@ class utils():
admin_roles.append(i[j]) admin_roles.append(i[j])
for role in admin_roles: for role in admin_roles:
msg = '{0} {1}'.format(msg, discord.utils.get(ctx.guild.roles, id=role).mention) msg = '{0} {1}'.format(msg, discord.utils.get(ctx.guild.roles, id=role).mention)
msg += f" New Request ID: {request_id}\n{ctx.author.mention} has requested assistance:\n```{request_msg}```\nRequested on: {datetime.strftime(ctx.message.created_at, '%Y-%m-%d at %H:%M:%S')} GMT" msg += f"""New Request ID: {request_id}
{ctx.author.mention} has requested assistance:
```{request_msg}```
Requested on: {datetime.strftime(ctx.message.created_at, '%Y-%m-%d at %H:%M:%S')} GMT"""
await chan.send(msg) await chan.send(msg)
await ctx.send('The Admin have received your request.') await ctx.send('The Admin have received your request.')
else: else:
@ -225,75 +277,107 @@ class utils():
@admin.command(name='list', aliases=['lr']) @admin.command(name='list', aliases=['lr'])
@commands.cooldown(1, 5, type=commands.BucketType.user) @commands.cooldown(1, 5, type=commands.BucketType.user)
async def list_admin_requests(self, ctx, assigned_to: discord.Member=None): async def list_admin_requests(self, ctx, assigned_to: discord.Member=None):
'''Returns a list of all active Admin help requests for this guild """Returns a list of all active Admin help requests for this guild
If a user runs this command it will return all the requests that they have submitted and are still open. If a user runs this command it will return all the requests that they have submitted and are still open.
- The [assigned_to] argument is ignored but will still give an error if an incorrect value is entered. - The [assigned_to] argument is ignored but will still give an error if an incorrect value is entered.
If an admin runs this command it will return all the open requests for this guild. If an admin runs this command it will return all the open requests for this guild.
- If the [assigned_to] argument is included it will instead return all open requests that are assigned to the specified admin. - If the [assigned_to] argument is included it will instead return all open requests that
''' are assigned to the specified admin.
"""
em = discord.Embed(style='rich', em = discord.Embed(style='rich',
title=f'Admin Help Requests', title=f'Admin Help Requests',
color=discord.Colour.green() color=discord.Colour.green()
) )
if checks.is_admin(self.bot, ctx) or checks.is_rcon_admin(self.bot, ctx): if checks.is_admin(self.bot, ctx) or checks.is_rcon_admin(self.bot, ctx):
if assigned_to == None: if assigned_to is None:
requests = self.bot.con.all(f'select * from admin_requests where guild_orig = %(guild_id)s and completed_time is null', {'guild_id': ctx.guild.id}) requests = self.bot.con.all(f'select * from admin_requests where guild_orig = %(guild_id)s '
f'and completed_time is null', {'guild_id': ctx.guild.id})
em.title = f'Admin help requests for {ctx.guild.name}' em.title = f'Admin help requests for {ctx.guild.name}'
if requests: if requests:
for request in requests: for request in requests:
member = discord.utils.get(ctx.guild.members, id=request[1]) member = discord.utils.get(ctx.guild.members, id=request[1])
admin = discord.utils.get(ctx.guild.members, id=request[2]) admin = discord.utils.get(ctx.guild.members, id=request[2])
title = f"{'Request ID':^12}{'Requested By':^20}{'Assigned to':^20}\n{request[0]:^12}{member.display_name if member else 'None':^20}{admin.display_name if admin else 'None':^20}" title = f"""{'Request ID':^12}{'Requested By':^20}{'Assigned to':^20}
em.add_field(name='', value=f"```{title}\n\n{request[4]}\n\nRequested on: {datetime.strftime(request[5], '%Y-%m-%d at %H:%M:%S')} GMT```", inline=False) {request[0]:^12}{member.display_name if member else 'None':^20}
{admin.display_name if admin else 'None':^20}"""
em.add_field(name='',
value=f"""```{title}
{request[4]}
Requested on: {datetime.strftime(request[5], '%Y-%m-%d at %H:%M:%S')} GMT```""",
inline=False)
else: else:
em.add_field(name='There are no pending requests for this guild.', value='', inline=False) em.add_field(name='There are no pending requests for this guild.', value='', inline=False)
else: else:
if checks.check_admin_role(self.bot, ctx, assigned_to) or checks.check_rcon_role(self.bot, ctx, assigned_to): if checks.check_admin_role(self.bot, ctx, assigned_to)\
requests = self.bot.con.all('select * from admin_requests where assigned_to = %(admin_id)s and guild_orig = %(guild_id)s and completed_time is null', or checks.check_rcon_role(self.bot, ctx, assigned_to):
requests = self.bot.con.all('select * from admin_requests where assigned_to = %(admin_id)s '
'and guild_orig = %(guild_id)s and completed_time is null',
{'admin_id': assigned_to.id, 'guild_id': ctx.guild.id}) {'admin_id': assigned_to.id, 'guild_id': ctx.guild.id})
em.title = f'Admin help requests asigned to {assigned_to.display_name} in {ctx.guild.name}' em.title = f'Admin help requests assigned to {assigned_to.display_name} in {ctx.guild.name}'
if requests: if requests:
for request in requests: for request in requests:
member = discord.utils.get(ctx.guild.members, id=request[1]) member = discord.utils.get(ctx.guild.members, id=request[1])
em.add_field(name=f"Request ID: {request[0]} Requested By: {member.display_name if member else 'None'}", value=f"{request[4]}\nRequested on: {datetime.strftime(request[5], '%Y-%m-%d at %H:%M:%S')} GMT\n", inline=False) em.add_field(name=f"Request ID: {request[0]} Requested By:"
f"{member.display_name if member else 'None'}",
value=f"""{request[4]}
Requested on: {datetime.strftime(request[5], '%Y-%m-%d at %H:%M:%S')} GMT
""",
inline=False)
else: else:
em.add_field(name=f'There are no pending requests for {assigned_to.display_name} this guild.', value='', inline=False) em.add_field(name=f'There are no pending requests for {assigned_to.display_name} this guild.',
value='',
inline=False)
else: else:
em.title = f'{assigned_to.display_name} is not an admin in this guild.' em.title = f'{assigned_to.display_name} is not an admin in this guild.'
else: else:
requests = self.bot.con.all('select * from admin_requests where issuing_member_id = %(member_id)s and guild_orig = %(guild_id)s and completed_time is null', requests = self.bot.con.all('select * from admin_requests where issuing_member_id = %(member_id)s '
'and guild_orig = %(guild_id)s and completed_time is null',
{'member_id': ctx.author.id, 'guild_id': ctx.guild.id}) {'member_id': ctx.author.id, 'guild_id': ctx.guild.id})
em.title = f'Admin help requests for {ctx.author.display_name}' em.title = f'Admin help requests for {ctx.author.display_name}'
if requests: if requests:
for request in requests: for request in requests:
admin = discord.utils.get(ctx.guild.members, id=request[2]) admin = discord.utils.get(ctx.guild.members, id=request[2])
em.add_field(name=f"Request ID: {request[0]}{' Assigned to: ' + admin.display_name if admin else ''}", value=f"{request[4]}\nRequested on: {datetime.strftime(request[5], '%Y-%m-%d at %H:%M:%S')} GMT\n", inline=False) em.add_field(name=f"Request ID: {request[0]}"
f"{' Assigned to: ' + admin.display_name if admin else ''}",
value=f"""{request[4]}
Requested on: {datetime.strftime(request[5], '%Y-%m-%d at %H:%M:%S')} GMT
""",
inline=False)
else: else:
em.add_field(name='You have no pending Admin Help requests.', value='To submit a request please use `admin new <message>`', inline=False) em.add_field(name='You have no pending Admin Help requests.',
value='To submit a request please use `admin new <message>`',
inline=False)
await ctx.send(embed=em) await ctx.send(embed=em)
@admin.command(name='close') @admin.command(name='close')
async def close_request(self, ctx, *, request_ids=None): async def close_request(self, ctx, *, request_ids=None):
'''Allows Admin to close admin help tickets. """Allows Admin to close admin help tickets.
[request_id] must be a valid integer pointing to an open Request ID [request_id] must be a valid integer pointing to an open Request ID
''' """
if checks.is_admin(self.bot, ctx) or checks.is_rcon_admin(self.bot, ctx): if checks.is_admin(self.bot, ctx) or checks.is_rcon_admin(self.bot, ctx):
if request_ids: if request_ids:
request_ids = request_ids.replace(' ', '').split(',') request_ids = request_ids.replace(' ', '').split(',')
for request_id in request_ids: for request_id in request_ids:
try: try:
request_id = int(request_id) request_id = int(request_id)
except: except Exception:
await ctx.send(f'{request_id} is not a valid request id.') await ctx.send(f'{request_id} is not a valid request id.')
else: else:
request = self.bot.con.one(f'select * from admin_requests where id = %(request_id)s', {'request_id': request_id}) request = self.bot.con.one(f'select * from admin_requests where id = %(request_id)s',
{'request_id': request_id})
if request: if request:
if request[3] == ctx.guild.id: if request[3] == ctx.guild.id:
if request[6] == None: if request[6] is None:
self.bot.con.run('update admin_requests set completed_time = %(time_now)s where id = %(request_id)s', {'time_now': ctx.message.created_at, 'request_id': request_id}) self.bot.con.run('update admin_requests set completed_time = %(time_now)s where '
await ctx.send(f'Request {request_id} by {ctx.guild.get_member(request[1]).display_name} has been marked complete.') 'id = %(request_id)s',
{'time_now': ctx.message.created_at, 'request_id': request_id})
await ctx.send(f'Request {request_id} by '
f'{ctx.guild.get_member(request[1]).display_name}'
f' has been marked complete.')
else: else:
await ctx.send(f'Request {request_id} is already marked complete.') await ctx.send(f'Request {request_id} is already marked complete.')
else: else:
@ -308,9 +392,9 @@ class utils():
@commands.command(name='weather', aliases=['wu']) @commands.command(name='weather', aliases=['wu'])
@commands.cooldown(5, 15, type=commands.BucketType.default) @commands.cooldown(5, 15, type=commands.BucketType.default)
async def get_weather(self, ctx, *, location='palmer ak'): async def get_weather(self, ctx, *, location='palmer ak'):
'''Gets the weather data for the location provided, """Gets the weather data for the location provided,
If no location is included then it will get the weather for the Bot's home location. If no location is included then it will get the weather for the Bot's home location.
''' """
try: try:
url = f'http://autocomplete.wunderground.com/aq?query={location}&format=JSON' url = f'http://autocomplete.wunderground.com/aq?query={location}&format=JSON'
with async_timeout.timeout(10): with async_timeout.timeout(10):
@ -327,14 +411,17 @@ class utils():
em.url = data['current_observation']['forecast_url'] em.url = data['current_observation']['forecast_url']
em.description = data['current_observation']['observation_time'] em.description = data['current_observation']['observation_time']
em.set_thumbnail(url=data['current_observation']['icon_url']) em.set_thumbnail(url=data['current_observation']['icon_url'])
em.set_footer(text='Data provided by wunderground.com', icon_url=data['current_observation']['image']['url']) em.set_footer(text='Data provided by wunderground.com',
icon_url=data['current_observation']['image']['url'])
value_str = f'''``` value_str = f'''```
{'Temp:':<20}{data['current_observation']['temperature_string']:<22} {'Temp:':<20}{data['current_observation']['temperature_string']:<22}
{'Feels Like:':<20}{data['current_observation']['feelslike_string']:<22} {'Feels Like:':<20}{data['current_observation']['feelslike_string']:<22}
{'Relative Humidity:':<20}{data['current_observation']['relative_humidity']:<22} {'Relative Humidity:':<20}{data['current_observation']['relative_humidity']:<22}
{'Wind:':<5}{data['current_observation']['wind_string']:^44} {'Wind:':<5}{data['current_observation']['wind_string']:^44}
```''' ```'''
em.add_field(name=f"Current Conditions: {data['current_observation']['weather']}", value=value_str, inline=False) em.add_field(name=f"Current Conditions: {data['current_observation']['weather']}",
value=value_str,
inline=False)
await ctx.send(embed=em) await ctx.send(embed=em)
except IndexError: except IndexError:
await ctx.send('Can\'t find that location, please try again.') await ctx.send('Can\'t find that location, please try again.')
@ -376,8 +463,10 @@ class utils():
return True return True
return False return False
return message.content.startswith(self.bot.default_prefix) return message.content.startswith(self.bot.default_prefix)
def is_member(message): def is_member(message):
return message.author == member return message.author == member
def is_author(message): def is_author(message):
return message.author == ctx.author return message.author == ctx.author
@ -437,9 +526,14 @@ class utils():
em.title = f'User Data from Whitelist Sheet' em.title = f'User Data from Whitelist Sheet'
em.colour = embed_color em.colour = embed_color
for i, name in enumerate(names): for i, name in enumerate(names):
if member.name.lower() in name.lower() or member.display_name.lower() in name.lower() or name.lower() in member.name.lower() or name.lower() in member.display_name.lower(): if member.name.lower() in name.lower()\
em.add_field(name=name, value=f'Steam ID: {steam[i]}\nPatreon Level: {tier[i]}\nPatron of: {patron[i]}') or member.display_name.lower() in name.lower()\
or name.lower() in member.name.lower()\
or name.lower() in member.display_name.lower():
em.add_field(name=name,
value=f'Steam ID: {steam[i]}\nPatreon Level: {tier[i]}\nPatron of: {patron[i]}')
await ctx.send(embed=em) await ctx.send(embed=em)
def setup(bot): def setup(bot):
bot.add_cog(utils(bot)) bot.add_cog(Utils(bot))

@ -1,11 +1,10 @@
import discord from typing import Dict
from discord.ext import commands from discord.ext import commands
import logging import logging
from datetime import datetime from datetime import datetime
import json, asyncio import json
from srcds import rcon as rcon_con import aiohttp
import re, aiohttp, async_timeout
from bs4 import BeautifulSoup as bs
from postgres import Postgres from postgres import Postgres
from collections import deque from collections import deque
from googleapiclient.discovery import build from googleapiclient.discovery import build
@ -32,16 +31,15 @@ bot_config_file = 'bot_config.json'
secrets_file = 'bot_secrets.json' secrets_file = 'bot_secrets.json'
profane_words_file = 'profane_words' profane_words_file = 'profane_words'
emojis = { emojis: Dict[str, str] = {
'x': '', 'x': '',
'y': '', 'y': '',
'poop': '💩', 'poop': '💩',
} }
description = 'I am Geeksbot! Fear me!' description = 'I am Geeksbot! Fear me!'
class Geeksbot(commands.Bot): class Geeksbot(commands.Bot):
def __init__(self, **kwargs): def __init__(self, **kwargs):
kwargs["command_prefix"] = self.get_custom_prefix kwargs["command_prefix"] = self.get_custom_prefix
@ -57,24 +55,31 @@ class Geeksbot(commands.Bot):
self.infected = {} self.infected = {}
self.TOKEN = self.bot_secrets['token'] self.TOKEN = self.bot_secrets['token']
del self.bot_secrets['token'] del self.bot_secrets['token']
self.con = Postgres(f"host={self.bot_secrets['db_con']['host']} port={self.bot_secrets['db_con']['port']} dbname={self.bot_secrets['db_con']['db_name']} connect_timeout=10 user={self.bot_secrets['db_con']['user']} password={self.bot_secrets['db_con']['password']}") self.con = Postgres(f" host={self.bot_secrets['db_con']['host']}\
port={self.bot_secrets['db_con']['port']}\
dbname={self.bot_secrets['db_con']['db_name']}\
connect_timeout=10 user={self.bot_secrets['db_con']['user']}\
password={self.bot_secrets['db_con']['password']}")
del self.bot_secrets['db_con'] del self.bot_secrets['db_con']
self.default_prefix = 'g$' self.default_prefix = 'g$'
self.voice_chans = {} self.voice_chans = {}
self.spam_list = {} self.spam_list = {}
self.gcs_service = build('customsearch', 'v1', developerKey=self.bot_secrets['google_search_key']) self.gcs_service = build('customsearch', 'v1', developerKey=self.bot_secrets['google_search_key'])
async def get_custom_prefix(self, bot, message): async def get_custom_prefix(self, bot_inst, message):
return self.con.one('select prefix from guild_config where guild_id = %(id)s', {'id': message.guild.id}) or self.default_prefix return self.con.one('select prefix from guild_config where guild_id = %(id)s', {'id': message.guild.id})\
or self.default_prefix
async def load_ext(self, ctx, mod): @staticmethod
bot.load_extension('{0}.{1}'.format(extension_dir,mod)) async def load_ext(self, ctx, mod=None):
if ctx != None: self.load_extension('{0}.{1}'.format(extension_dir, mod))
if ctx is not None:
await ctx.send('{0} loaded.'.format(mod)) await ctx.send('{0} loaded.'.format(mod))
async def unload_ext(self, ctx, mod): @staticmethod
bot.unload_extension('{0}.{1}'.format(extension_dir,mod)) async def unload_ext(self, ctx, mod=None):
if ctx != None: self.unload_extension('{0}.{1}'.format(extension_dir, mod))
if ctx is not None:
await ctx.send('{0} unloaded.'.format(mod)) await ctx.send('{0} unloaded.'.format(mod))
async def close(self): async def close(self):
@ -84,16 +89,18 @@ class Geeksbot(commands.Bot):
bot = Geeksbot(description=description, case_insensitive=True) bot = Geeksbot(description=description, case_insensitive=True)
@bot.command(hidden=True) @bot.command(hidden=True)
@commands.is_owner() @commands.is_owner()
async def load(ctx, mod): async def load(ctx, mod=None):
'Allows the owner to load extensions dynamically' """Allows the owner to load extensions dynamically"""
await bot.load_ext(ctx, mod) await bot.load_ext(ctx, mod)
@bot.command(hidden=True) @bot.command(hidden=True)
@commands.is_owner() @commands.is_owner()
async def reload(ctx, mod=None): async def reload(ctx, mod=None):
'''Allows the owner to reload extensions dynamically''' """Allows the owner to reload extensions dynamically"""
if mod == 'all': if mod == 'all':
load_list = bot.bot_config['load_list'] load_list = bot.bot_config['load_list']
for load_item in load_list: for load_item in load_list:
@ -103,18 +110,23 @@ async def reload(ctx, mod=None):
await bot.unload_ext(ctx, mod) await bot.unload_ext(ctx, mod)
await bot.load_ext(ctx, mod) await bot.load_ext(ctx, mod)
@bot.command(hidden=True) @bot.command(hidden=True)
@commands.is_owner() @commands.is_owner()
async def unload(ctx, mod): async def unload(ctx, mod):
'Allows the owner to unload extensions dynamically' """Allows the owner to unload extensions dynamically"""
await bot.unload_ext(ctx, mod) await bot.unload_ext(ctx, mod)
@bot.event @bot.event
async def on_message(ctx): async def on_message(ctx):
if not ctx.author.bot: if not ctx.author.bot:
if ctx.guild: if ctx.guild:
if int(bot.con.one(f"select channel_lockdown from guild_config where guild_id = %(id)s", {'id':ctx.guild.id})): if int(bot.con.one(f"select channel_lockdown from guild_config where guild_id = %(id)s",
if ctx.channel.id in json.loads(bot.con.one(f"select allowed_channels from guild_config where guild_id = %(id)s", {'id':ctx.guild.id})): {'id': ctx.guild.id})):
if ctx.channel.id in json.loads(bot.con.one(f"select allowed_channels from guild_config "
f"where guild_id = %(id)s",
{'id': ctx.guild.id})):
await bot.process_commands(ctx) await bot.process_commands(ctx)
elif ctx.channel.id == 418452585683484680: elif ctx.channel.id == 418452585683484680:
prefix = bot.con.one('select prefix from guild_config where guild_id = %(id)s', {'id': ctx.guild.id}) prefix = bot.con.one('select prefix from guild_config where guild_id = %(id)s', {'id': ctx.guild.id})
@ -126,6 +138,7 @@ async def on_message(ctx):
else: else:
await bot.process_commands(ctx) await bot.process_commands(ctx)
@bot.event @bot.event
async def on_ready(): async def on_ready():
bot.recent_msgs = {} bot.recent_msgs = {}

Loading…
Cancel
Save