Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Emoji Change #2

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 35 additions & 34 deletions Discord/Harmonbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ async def on_ready():
# asyncio.ensure_future(client.cogs["Audio"].start_player(client.get_channel(voice_channel[1])))
text_channel = client.get_channel(voice_channel[1])
if text_channel:
client.cogs["Audio"].players[text_channel.server.id] = audio_player.AudioPlayer(client, text_channel)
client.cogs["Audio"].players[text_channel.guild.id] = audio_player.AudioPlayer(client, text_channel)
await client.join_voice_channel(client.get_channel(voice_channel[0]))
'''
for folder in os.listdir("data/server_data"):
Expand All @@ -56,12 +56,12 @@ async def on_ready():
with open("data/server_data/{}/settings.json".format(folder), 'w') as settings_file:
json.dump(data, settings_file, indent = 4)
'''
for server in client.servers:
utilities.create_folder("data/server_data/{}".format(server.id))
utilities.create_file("server_data/{}/settings".format(server.id), content = {"anti-spam": False, "respond_to_bots": False})
if server.name:
clean_name = re.sub(r"[\|/\\:\?\*\"<>]", "", server.name) # | / \ : ? * " < >
utilities.create_file("server_data/{}/{}".format(server.id, clean_name))
for guild in client.guilds:
utilities.create_folder("data/server_data/{}".format(guild.id))
utilities.create_file("server_data/{}/settings".format(guild.id), content = {"anti-spam": False, "respond_to_bots": False})
if guild.name:
clean_name = re.sub(r"[\|/\\:\?\*\"<>]", "", guild.name) # | / \ : ? * " < >
utilities.create_file("server_data/{}/{}".format(guild.id, clean_name))
# TODO: DM if joined new server
# TODO: DM if left server
await clients.random_game_status()
Expand All @@ -87,26 +87,26 @@ async def on_resumed():
print("Discord Harmonbot: resumed")

@client.event
async def on_command(command, ctx):
async def on_command(ctx):
with open("data/stats.json", 'r') as stats_file:
stats = json.load(stats_file)
stats["commands_executed"] += 1
stats["commands_usage"][command.name] = stats["commands_usage"].get(command.name, 0) + 1
stats["commands_usage"][ctx.command.name] = stats["commands_usage"].get(ctx.command.name, 0) + 1
with open("data/stats.json", 'w') as stats_file:
json.dump(stats, stats_file, indent = 4)
utilities.create_folder("data/user_data/{}".format(ctx.message.author.id))
utilities.create_file("user_data/{}/stats".format(ctx.message.author.id), content = {"commands_executed": 0, "points": 0, "respects_paid": 0})
utilities.create_folder("data/user_data/{}".format(ctx.author.id))
utilities.create_file("user_data/{}/stats".format(ctx.author.id), content = {"commands_executed": 0, "points": 0, "respects_paid": 0})
# TODO: Transfer respects paid data?
clean_name = re.sub(r"[\|/\\:\?\*\"<>]", "", ctx.message.author.name) # | / \ : ? * " < >
utilities.create_file("user_data/{}/{}".format(ctx.message.author.id, clean_name))
with open("data/user_data/{}/stats.json".format(ctx.message.author.id), "r") as stats_file:
clean_name = re.sub(r"[\|/\\:\?\*\"<>]", "", ctx.author.name) # | / \ : ? * " < >
utilities.create_file("user_data/{}/{}".format(ctx.author.id, clean_name))
with open("data/user_data/{}/stats.json".format(ctx.author.id), "r") as stats_file:
stats = json.load(stats_file)
stats["commands_executed"] += 1
stats["points"] += 1
with open("data/user_data/{}/stats.json".format(ctx.message.author.id), 'w') as stats_file:
with open("data/user_data/{}/stats.json".format(ctx.author.id), 'w') as stats_file:
json.dump(stats, stats_file, indent = 4)

@client.command(pass_context = True)
@client.command()
@checks.is_owner()
async def load(ctx, cog : str):
'''Loads a cog'''
Expand All @@ -119,7 +119,7 @@ async def load(ctx, cog : str):
await client.embed_reply(":thumbsup::skin-tone-2: Loaded `{}` cog :gear:".format(cog))
await client.delete_message(ctx.message)

@client.command(pass_context = True)
@client.command()
@checks.is_owner()
async def unload(ctx, cog : str):
'''Unloads a cog'''
Expand All @@ -132,7 +132,7 @@ async def unload(ctx, cog : str):
await client.embed_reply(":ok_hand::skin-tone-2: Unloaded `{}` cog :gear:".format(cog))
await client.delete_message(ctx.message)

@client.command(pass_context = True)
@client.command()
@checks.is_owner()
async def reload(ctx, cog : str):
'''Reloads a cog'''
Expand All @@ -157,13 +157,13 @@ async def reload(ctx, cog : str):
async def on_message(message):

# Log message
source = "Direct Message" if message.channel.is_private else "#{0.channel.name} ({0.channel.id}) [{0.server.name} ({0.server.id})]".format(message)
logging.chat_logger.info("{0.timestamp}: [{0.id}] {0.author.display_name} ({0.author.name}) ({0.author.id}) in {1}: {0.content} {0.embeds}".format(message, source))
source = "Direct Message" if isinstance(message.channel, discord.DMChannel) else "#{0.channel.name} ({0.channel.id}) [{0.guild.name} ({0.guild.id})]".format(message)
logging.chat_logger.info("{0.created_at}: [{0.id}] {0.author.display_name} ({0.author.name}) ({0.author.id}) in {1}: {0.content} {0.embeds}".format(message, source))

# Server specific settings
if message.server is not None:
if message.guild is not None:
try:
with open("data/server_data/{}/settings.json".format(message.server.id), 'r') as settings_file:
with open("data/server_data/{}/settings.json".format(message.guild.id), 'r') as settings_file:
data = json.load(settings_file)
except FileNotFoundError:
# TODO: Handle/Fix, create new file with default settings
Expand All @@ -172,9 +172,9 @@ async def on_message(message):
global mention_spammers
if message.author.id in mention_spammers:
# TODO: Handle across different servers
if message.server.me.permissions_in(message.channel).kick_members:
if message.guild.me.permissions_in(message.channel).kick_members:
# TODO: Check hierarchy, if able to kick
await client.send_message(message.author, "You were kicked from {} for spamming mentions".format(message.server))
await client.send_message(message.author, "You were kicked from {} for spamming mentions".format(message.guild))
await client.kick(message.author)
await client.send_message(message.channel, "{} has been kicked for spamming mentions".format(message.author))
else:
Expand All @@ -188,10 +188,11 @@ async def on_message(message):
return

# Commands
await client.process_commands(message)
ctx = await client.get_context(message, cls = clients.Context)
await client.invoke(ctx)

# Forward DMs
if message.channel.is_private and message.channel.user.id != clients.owner_id:
if isinstance(message.channel, discord.DMChannel) and message.channel.user.id != clients.owner_id:
me = discord.utils.get(client.get_all_members(), id = clients.owner_id)
if message.author == client.user:
try:
Expand Down Expand Up @@ -245,7 +246,7 @@ async def on_message(message):
await client.send_message(message.channel, "Prefixes: {}".format(' '.join(['`"{}"`'.format(prefix) for prefix in prefixes])))

# help DM
elif message.content.lower() == "help" and message.channel.is_private:
elif message.content.lower() == "help" and isinstance(message.channel, discord.DMChannel):
await clients.embed_reply(message, "Please see {}help".format(prefixes[0]))

# :8ball:
Expand All @@ -272,7 +273,7 @@ async def on_message(message):
# Chatbot
elif message.raw_mentions and client.user.id == message.raw_mentions[0] and message.clean_content.startswith('@'):
# Handle @Harmonbot help
bot_name = message.channel.me.display_name if message.channel.is_private else message.server.me.display_name
bot_name = message.channel.me.display_name if isinstance(message.channel, discord.DMChannel) else message.guild.me.display_name
if ' '.join(message.clean_content.split()[:2]).lower() == '@' + bot_name.lower() + " help":
await clients.embed_reply(message, "Please see {}help".format(prefixes[0]))
return
Expand All @@ -293,10 +294,10 @@ async def on_error(event_method, *args, **kwargs):
if type is discord.errors.Forbidden:
for arg in args:
if isinstance(arg, commands.context.Context):
print("Missing Permissions for #{0.channel.name} in {0.server.name}".format(arg.message))
print("Missing Permissions for #{0.channel.name} in {0.guild.name}".format(arg.message))
return
elif isinstance(arg, discord.Message):
print("Missing Permissions for #{0.channel.name} in {0.server.name}".format(arg))
print("Missing Permissions for #{0.channel.name} in {0.guild.name}".format(arg))
return
print('Ignoring exception in {}'.format(event_method), file = sys.stderr)
traceback.print_exc()
Expand All @@ -309,13 +310,13 @@ async def on_command_error(error, ctx):
if isinstance(error, (errors.LichessUserNotFound)): return # handled with local error handler
if isinstance(error, commands.errors.CommandInvokeError) and isinstance(error.original, youtube_dl.utils.DownloadError): return # handled with local error handler
embed = discord.Embed(color = clients.bot_color)
avatar = ctx.message.author.avatar_url or ctx.message.author.default_avatar_url
embed.set_author(name = ctx.message.author.display_name, icon_url = avatar)
avatar = ctx.author.avatar_url or ctx.author.default_avatar_url
embed.set_author(name = ctx.author.display_name, icon_url = avatar)
if isinstance(error, (errors.NotServerOwner, errors.MissingPermissions)): # errors.NotOwner?
embed.description = ":no_entry: You don't have permission to do that"
elif isinstance(error, errors.MissingCapability):
if "embed_links" in error.permissions:
await ctx.bot.send_message(ctx.message.channel, "I don't have permission to do that here\nI need the permission(s): " + ', '.join(error.permissions))
await ctx.bot.send_message(ctx.channel, "I don't have permission to do that here\nI need the permission(s): " + ', '.join(error.permissions))
return
embed.description = "I don't have permission to do that here\nI need the permission(s): " + ', '.join(error.permissions)
elif isinstance(error, errors.PermittedVoiceNotConnected):
Expand All @@ -335,7 +336,7 @@ async def on_command_error(error, ctx):
if embed.description:
await ctx.bot.send_message(ctx.message.channel, embed = embed) # check embed links permission
elif isinstance(error, commands.errors.CommandInvokeError) and isinstance(error.original, (discord.errors.Forbidden)):
print("Missing Permissions for #{0.channel.name} in {0.server.name}".format(ctx.message))
print("Missing Permissions for #{0.channel.name} in {0.guild.name}".format(ctx.message))
else:
print("Ignoring exception in command {}".format(ctx.command), file = sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file = sys.stderr)
Expand Down
Loading