Renamed src package to sebimachine.

- Gave the package a descriptive name.
- Passed over with black once more.
- Created setup.py to install dependencies.
- Updated author to reflect repo ownership to Dusty.
- Changed `git` command to use the __url__ attribute.
- Changed music to use ogg vorbis instead of mp3, purely for
    performance.
- Tried to make sure nothing broke.
- Updated dockerfile. Pretty sure we don't need it though...
This commit is contained in:
neko404notfound
2018-06-21 10:06:03 +01:00
parent 001d6aa0ac
commit 4f5a1b518a
32 changed files with 656 additions and 604 deletions
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
import asyncio
from discord.ext import commands
import discord
class BasicCommands:
def __init__(self, bot):
self.bot = bot
@commands.command()
async def tutorial(self, ctx):
await ctx.send(
f"Hello, {ctx.author.display_name}. Welcome to Sebi's Bot Tutorials. \nFirst off, would you like a quick walkthrough on the server channels?"
)
channel_list = {
"channel-1": self.bot.get_channel(333149949883842561).mention,
"d.py-rewrite-start": self.bot.get_channel(386419285439938560).mention,
"js-klasa-start": self.bot.get_channel(341816240186064897).mention,
"d.js": self.bot.get_channel(436771798303113217).mention,
}
bots_channels = (
self.bot.get_channel(339112602867204097).mention,
self.bot.get_channel(411586546551095296).mention,
)
help_channels = (
self.bot.get_channel(425315253153300488).mention,
self.bot.get_channel(392215236612194305).mention,
self.bot.get_channel(351034776985141250).mention,
)
def check(m):
return (
True
if m.author.id == ctx.author.id and m.channel.id == ctx.channel.id
else False
)
msg = await self.bot.wait_for("message", check=check, timeout=15)
agree = ("yes", "yep", "yesn't", "ya", "ye")
if msg is None:
await ctx.send(
"Sorry, {ctx.author.mention}, you didn't reply on time. You can run the command again when you're free :)"
)
else:
if msg.content.lower() in agree:
async with ctx.typing():
await ctx.send("Alrighty-Roo... Check your DMs!")
await ctx.author.send("Alrighty-Roo...")
await ctx.author.send(
f"To start making your bot from scratch, you first need to head over to {channel_list['channel-1']}"
" (Regardless of the language you're gonna use)."
)
await asyncio.sleep(0.5)
await ctx.author.send(
f"After you have a bot account, you can either continue with {channel_list['d.py-rewrite-start']}"
f"if you want to make a bot in discord.py rewrite __or__ go to {channel_list['js-klasa-start']} or "
f"{channel_list['d.js']} for making a bot in JavaScript."
)
await ctx.author.send(
"...Read all the tutorials and still need help? You have two ways to get help."
)
await asyncio.sleep(1.5)
await ctx.author.send(
"**Method-1**\nThis is the best method of getting help. You help yourself.\n"
f"To do so, head over to a bots dedicated channel (either {bots_channels[0]} or {bots_channels[1]})"
" and type `?rtfm rewrite thing_you_want_help_with`.\nThis will trigger the bot R.Danny Bot and will"
"give you links on your query on the official discord.py rewrite docs. *PS: Let the page completely load*"
)
await asyncio.sleep(5)
await ctx.author.send(
"**Method-2**\nIf you haven't found anything useful with Method-1, feel free to ask your question "
f"in any of the related help channels. ({', '.join(help_channels)})\nMay the force be with you!!"
)
else:
return await ctx.send(
"Session terminated. You can run this command again whenever you want."
)
def setup(bot):
bot.add_cog(BasicCommands(bot))
+228
View File
@@ -0,0 +1,228 @@
import discord
from discord.ext import commands
class BotManager:
def __init__(self, bot):
self.bot = bot
async def on_member_join(self, member):
# If the member is not a bot
if member.bot is False:
return
else:
# The member is a bot
await member.add_roles(discord.utils.get(member.guild.roles, name="Bots"))
try:
await member.edit(
nick="["
+ await self.bot.db_con.fetch(
"select prefix from bots where id = $1", member.id
)
+ "] "
+ member.name
)
except:
pass
async def on_member_remove(self, member):
# If the member is not a bot
if member.bot is False:
return
else:
# The member is a bot
await self.bot.db_con.execute("DELETE FROM bots WHERE id = $1", member.id)
@commands.command()
async def invite(self, ctx, bot=None, prefix=None):
bot = await ctx.bot.get_user_info(bot)
if not bot:
raise Warning(
"You must include the id of the bot you are trying to invite... Be exact."
)
if not bot.bot:
raise Warning("You can only invite bots.")
if not prefix:
raise Warning("Please provide a prefix")
# Make sure that the bot has not been invited already and it is not being tested
if (
await self.bot.db_con.fetch(
"select count(*) from bots where id = $1", bot.id
)
== 1
):
raise Warning("The bot has already been invited or is being tested")
await self.bot.db_con.execute(
"insert into bots (id, owner, prefix) values ($1, $2, $3)",
bot.id,
ctx.author.id,
prefix,
)
em = discord.Embed(colour=self.bot.embed_color)
em.title = "Hello {},".format(ctx.author.name)
em.description = "Thanks for inviting your bot! It will be tested and invited shortly. " "Please open your DMs if they are not already so the bot can contact " "you to inform you about the progress of the bot!"
await ctx.send(embed=em)
em = discord.Embed(title="Bot invite", colour=discord.Color(0x363941))
em.set_thumbnail(url=bot.avatar_url)
em.add_field(name="Bot name", value=bot.name)
em.add_field(name="Bot id", value="`" + str(bot.id) + "`")
em.add_field(name="Bot owner", value=ctx.author.mention)
em.add_field(name="Bot prefix", value="`" + prefix + "`")
await ctx.bot.get_channel(448803675574370304).send(embed=em)
@commands.command(name="claim", aliases=["makemine", "gimme"])
@commands.cooldown(1, 5, commands.BucketType.user)
async def _claim_bot(
self,
ctx,
bot: discord.Member = None,
prefix: str = None,
owner: discord.Member = None,
):
if not bot:
raise Warning(
"You must include the name of the bot you are trying to claim... Be exact."
)
if not bot.bot:
raise Warning("You can only claim bots.")
if not prefix:
if bot.display_name.startswith("["):
prefix = bot.display_name.split("]")[0].strip("[")
else:
raise Warning("Prefix not provided and can't be found in bot nick.")
if owner is not None and ctx.author.guild_permissions.manage_roles:
author_id = owner.id
else:
author_id = ctx.author.id
em = discord.Embed()
if (
await self.bot.db_con.fetchval(
"select count(*) from bots where owner = $1", author_id
)
>= 10
):
em.colour = self.bot.error_color
em.title = "Too Many Bots Claimed"
em.description = "Each person is limited to claiming 10 bots as that is how " "many bots are allowed by the Discord API per user."
return await ctx.send(embed=em)
existing = await self.bot.db_con.fetchrow(
"select * from bots where id = $1", bot.id
)
if not existing:
await self.bot.db_con.execute(
"insert into bots (id, owner, prefix) values ($1, $2, $3)",
bot.id,
author_id,
prefix,
)
em.colour = self.bot.embed_color
em.title = "Bot Claimed"
em.description = f"You have claimed {bot.display_name} with a prefix of {prefix}\n" f"If there is an error please run command again to correct the prefix,\n" f"or {ctx.prefix}unclaim {bot.mention} to unclaim the bot."
elif existing["owner"] and existing["owner"] != author_id:
em.colour = self.bot.error_color
em.title = "Bot Already Claimed"
em.description = "This bot has already been claimed by someone else.\n" "If this is actually your bot please let the guild Administrators know."
elif existing["owner"] and existing["owner"] == author_id:
em.colour = self.bot.embed_color
em.title = "Bot Already Claimed"
em.description = "You have already claimed this bot.\n" "If the prefix you provided is different from what is already in the database" " it will be updated for you."
if existing["prefix"] != prefix:
await self.bot.db_con.execute(
"update bots set prefix = $1 where id = $2", prefix, bot.id
)
elif not existing["owner"]:
await self.bot.db_con.execute(
"update bots set owner = $1, prefix = $2 where id = $3",
author_id,
prefix,
bot.id,
)
em.colour = self.bot.embed_color
em.title = "Bot Claimed"
em.description = f"You have claimed {bot.display_name} with a prefix of {prefix}\n" f"If there is an error please run command again to correct the prefix,\n" f"or {ctx.prefix}unclaim {bot.mention} to unclaim the bot."
else:
em.colour = self.bot.error_color
em.title = "Something Went Wrong..."
await ctx.send(embed=em)
@commands.command(name="unclaim")
@commands.cooldown(1, 5, commands.BucketType.user)
async def _unclaim_bot(self, ctx, bot: discord.Member = None):
if not bot:
raise Warning(
"You must include the name of the bot you are trying to claim... Be exact."
)
if not bot.bot:
raise Warning("You can only unclaim bots.")
em = discord.Embed()
existing = await self.bot.db_con.fetchrow(
"select * from bots where id = $1", bot.id
)
if not existing or not existing["owner"]:
em.colour = self.bot.error_color
em.title = "Bot Not Found"
em.description = "That bot is not claimed"
elif (
existing["owner"] != ctx.author.id
and not ctx.author.guild_permissions.manage_roles
):
em.colour = self.bot.error_color
em.title = "Not Claimed By You"
em.description = "That bot is claimed by someone else.\n" "You can't unclaim someone else's bot"
else:
await self.bot.db_con.execute(
"update bots set owner = null where id = $1", bot.id
)
em.colour = self.bot.embed_color
em.title = "Bot Unclaimed"
em.description = f"You have unclaimed {bot.display_name}\n" f"If this is an error please reclaim using\n" f'{ctx.prefix}claim {bot.mention} {existing["prefix"]}'
await ctx.send(embed=em)
@commands.command(name="listclaims", aliases=["claimed", "mybots"])
@commands.cooldown(1, 5, commands.BucketType.user)
async def _claimed_bots(self, ctx, usr: discord.Member = None):
if usr is None:
usr = ctx.author
bots = await self.bot.db_con.fetch(
"select * from bots where owner = $1", usr.id
)
if bots:
em = discord.Embed(
title=f"{usr.display_name} has claimed the following bots:",
colour=self.bot.embed_color,
)
for bot in bots:
member = ctx.guild.get_member(int(bot["id"]))
em.add_field(
name=member.display_name,
value=f'Stored Prefix: {bot["prefix"]}',
inline=False,
)
else:
em = discord.Embed(
title="You have not claimed any bots.", colour=self.bot.embed_color
)
await ctx.send(embed=em)
@commands.command(name="whowns")
async def _whowns(self, ctx, bot: discord.Member):
if not bot.bot:
await ctx.send("this commands only for bots")
else:
owner = await self.bot.db_con.fetchrow(
"select * from bots where id = $1", bot.id
)
await ctx.send(ctx.guild.get_member(owner["owner"]).display_name)
def setup(bot):
bot.add_cog(BotManager(bot))
+248
View File
@@ -0,0 +1,248 @@
from discord.ext import commands
import traceback
import discord
import inspect
import textwrap
from contextlib import redirect_stdout
import io
class REPL:
"""Python in Discords"""
def __init__(self, bot):
self.bot = bot
self._last_result = None
self.sessions = set()
def cleanup_code(self, content):
"""
Automatically removes code blocks from the code.
"""
# remove ```py\n```
if content.startswith("```") and content.endswith("```"):
return "\n".join(content.split("\n")[1:-1])
# remove `foo`
return content.strip("` \n")
def get_syntax_error(self, e):
if e.text is None:
return "{0.__class__.__name__}: {0}".format(e)
return "{0.text}{1:>{0.offset}}\n{2}: {0}".format(e, "^", type(e).__name__)
@commands.command(name="exec")
async def _eval(self, ctx, *, body: str = None):
"""
Execute python code in discord chat.
Only the owner of this bot can use this command.
Alias:
- exec
Usage:
- exec < python code >
Example:
- exec print(546132)
"""
if ctx.author.id not in self.bot.ownerlist:
return await ctx.send(
"Only my contributors can use me like this :blush:", delete_after=10
)
if body is None:
return await ctx.send(
"Please, use\n"
f'`{self.bot.config["prefix"]}exec`\n\n'
"\n`\\`\\`\\`py\n[python code]\n\\`\\`\\`\n"
"to get the most out of the command"
)
env = {
"bot": self.bot,
"ctx": ctx,
"channel": ctx.message.channel,
"author": ctx.message.author,
"server": ctx.message.guild,
"message": ctx.message,
"_": self._last_result,
}
env.update(globals())
body = self.cleanup_code(body)
stdout = io.StringIO()
to_compile = "async def func():\n%s" % textwrap.indent(body, " ")
try:
exec(to_compile, env)
except SyntaxError as e:
try:
await ctx.send(f"```py\n{self.get_syntax_error(e)}\n```")
except Exception as e:
error = [
self.get_syntax_error(e)[i : i + 2000]
for i in range(0, len(self.get_syntax_error(e)), 2000)
]
for i in error:
await ctx.send(f"```py\n{i}\n```")
func = env["func"]
try:
with redirect_stdout(stdout):
ret = await func()
except Exception as e:
value = stdout.getvalue()
try:
await ctx.send(f"```py\n{value}{traceback.format_exc()}\n```")
except Exception as e:
error = [value[i : i + 2000] for i in range(0, len(value), 2000)]
for i in error:
await ctx.send(f"```py\n{i}\n```")
tracebackerror = [
traceback.format_exc()[i : i + 2000]
for i in range(0, len(traceback.format_exc()), 2000)
]
for i in tracebackerror:
await ctx.send(f"```py\n{i}\n```")
else:
value = stdout.getvalue()
if ret is None:
if value:
try:
await ctx.send(f"```py\n{value}\n```")
except Exception as e:
code = [value[i : i + 1980] for i in range(0, len(value), 1980)]
for i in code:
await ctx.send(f"```py\n{i}\n```")
else:
self._last_result = ret
try:
code = [value[i : i + 1980] for i in range(0, len(value), 1980)]
for i in code:
await ctx.send(f"```py\n{i}\n```")
except Exception as e:
code = [value[i : i + 1980] for i in range(0, len(value), 1980)]
for i in code:
await ctx.send(f"```py\n{i}\n```")
modifyd_ret = [ret[i : i + 1980] for i in range(0, len(ret), 1980)]
for i in modifyd_ret:
await ctx.send(f"```py\n{i}\n```")
@commands.command(hidden=True)
async def repl(self, ctx):
"""
Start a interactive python shell in chat.
Only the owner of this bot can use this command.
Usage:
- repl < python code >
Example:
- repl print(205554)
"""
if ctx.author.id not in self.bot.ownerlist:
return await ctx.send(
"Only my contributors can use me like this :blush:", delete_after=10
)
msg = ctx.message
variables = {
"ctx": ctx,
"bot": self.bot,
"message": msg,
"server": msg.guild,
"channel": msg.channel,
"author": msg.author,
"_": None,
}
if msg.channel.id in self.sessions:
msg = await ctx.send(
"Already running a REPL session in this channel. Exit it with `quit`."
)
self.sessions.add(msg.channel.id)
await ctx.send("Enter code to execute or evaluate. `exit()` or `quit` to exit.")
while True:
response = await self.bot.wait_for(
"message",
check=lambda m: m.content.startswith("`")
and m.author == ctx.author
and m.channel == ctx.channel,
)
cleaned = self.cleanup_code(response.content)
if cleaned in ("quit", "exit", "exit()"):
msg = await ctx.send("Exiting.")
self.sessions.remove(msg.channel.id)
return
executor = exec
if cleaned.count("\n") == 0:
# single statement, potentially 'eval'
try:
code = compile(cleaned, "<repl session>", "eval")
except SyntaxError:
pass
else:
executor = eval
if executor is exec:
try:
code = compile(cleaned, "<repl session>", "exec")
except SyntaxError as e:
try:
await ctx.send(f"```Python\n{self.get_syntax_error(e)}\n```")
except Exception as e:
error = [
self.get_syntax_error(e)[i : i + 2000]
for i in range(0, len(self.get_syntax_error(e)), 2000)
]
for i in error:
await ctx.send(f"```Python\n{i}\n```")
variables["message"] = response
fmt = None
stdout = io.StringIO()
try:
with redirect_stdout(stdout):
result = executor(code, variables)
if inspect.isawaitable(result):
result = await result
except Exception as e:
value = stdout.getvalue()
await ctx.send(f"```Python\n{value}{traceback.format_exc()}\n```")
continue
else:
value = stdout.getvalue()
if result is not None:
fmt = "{}{}".format(value, result)
variables["_"] = result
elif value:
fmt = value
try:
if fmt is not None:
if len(fmt) > 1980:
code = [fmt[i : i + 1980] for i in range(0, len(fmt), 1980)]
for i in code:
await ctx.send(f"```py\n{i}\n```")
else:
await ctx.send(fmt)
except discord.Forbidden:
pass
except discord.HTTPException as e:
await ctx.send(f"Unexpected error: `{e}`")
def setup(bot):
bot.add_cog(REPL(bot))
+146
View File
@@ -0,0 +1,146 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
from discord.ext import commands
import discord
import traceback
import aiofiles
import os
class Upload:
"""
CogName should be the name of the cog
"""
def __init__(self, bot):
self.bot = bot
print("upload loaded")
@commands.command()
async def reload(self, ctx, *, extension: str):
"""Reload an extension."""
await ctx.trigger_typing()
if ctx.author.id not in self.bot.ownerlist:
return await ctx.send(
"Only my contributors can use me like this :blush:", delete_after=10
)
extension = extension.lower()
try:
self.bot.unload_extension("src.cogs.{}".format(extension))
self.bot.load_extension("src.cogs.{}".format(extension))
except Exception as e:
traceback.print_exc()
await ctx.send(f"Could not reload `{extension}` -> `{e}`")
else:
await ctx.send(f"Reloaded `{extension}`.")
@commands.command()
async def reloadall(self, ctx):
"""Reload all extensions."""
await ctx.trigger_typing()
if ctx.author.id not in self.bot.ownerlist:
return await ctx.send(
"Only my contributors can use me like this :blush:", delete_after=10
)
try:
for extension in self.bot.extensions:
self.bot.unload_extension(extension)
self.bot.load_extension(extension)
await ctx.send(f"Reload success! :thumbsup:\n")
except Exception as e:
await ctx.send(f"Could not reload `{extension}` -> `{e}`.\n")
@commands.command()
async def unload(self, ctx, *, extension: str):
"""Unload an extension."""
await ctx.trigger_typing()
if ctx.author.id not in self.bot.ownerlist:
return await ctx.send(
"Only my contributors can use me like this :blush:", delete_after=10
)
extension = extension.lower()
try:
self.bot.unload_extension("src.cogs.{}".format(extension))
except Exception as e:
traceback.print_exc()
if ctx.message.author.id not in self.bot.owner_list:
await ctx.send(f"Could not unload `{extension}` -> `{e}`")
else:
await ctx.send(f"Unloaded `{extension}`.")
@commands.command()
async def load(self, ctx, *, extension: str):
"""Load an extension."""
await ctx.trigger_typing()
if ctx.author.id not in self.bot.ownerlist:
return await ctx.send(
"Only my contributors can use me like this :blush:", delete_after=10
)
extension = extension.lower()
try:
self.bot.load_extension("src.cogs.{}".format(extension))
except Exception as e:
traceback.print_exc()
await ctx.send(f"Could not load `{extension}` -> `{e}`")
else:
await ctx.send(f"Loaded `{extension}`.")
@commands.command()
async def permunload(self, ctx, extension=None):
"""Disables permanently a cog."""
await ctx.trigger_typing()
if ctx.author.id not in self.bot.ownerlist:
return await ctx.send(
"Only my contributors can use me like this :blush:", delete_after=10
)
if cog is None:
return await ctx.send(
"Please provide a extension. Do `help permunload` for more info"
)
extension = extension.lower()
async with aiofiles.open("extension.txt") as fp:
lines = fp.readlines()
removed = False
async with aiofiles.open("extension.txt", "w") as fp:
for i in lines:
if i.replace("\n", "") != extension:
fp.write(i)
else:
removed = True
break
if removed is True:
try:
self.bot.unload_extension(extension)
except:
pass
return await ctx.send("Extension removed successfully")
await ctx.send("Extension not found")
@commands.command(hidden=True)
async def reboot(self, ctx):
if ctx.author.id not in self.bot.ownerlist:
return await ctx.send(
"Only my contributors can use me like this :blush:", delete_after=10
)
await ctx.send("Sebi-Machine is restarting.")
with open(f"src/config/reboot", "w") as f:
f.write(f"1\n{ctx.channel.id}")
# noinspection PyProtectedMember
os._exit(1)
def setup(bot):
bot.add_cog(Upload(bot))
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
from discord.ext import commands
import discord
class CogName:
"""
CogName should be the name of the cog
"""
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
"""Say pong"""
now = ctx.message.created_at
msg = await ctx.send("Pong")
sub = msg.created_at - now
await msg.edit(content=f"🏓Pong, **{sub.total_seconds() * 1000}ms**")
def setup(bot):
bot.add_cog(CogName(bot))
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
from discord.ext import commands
import discord
import random
import aiohttp
class Fun:
"""
CogName should be the name of the cog
"""
def __init__(self, bot):
self.bot = bot
@commands.command()
async def sebisauce(self, ctx):
"""
Get a image related to Sebi.
Sebi is a random guy with perfect code related jokes.
Usage:
- sebisauce
"""
await ctx.trigger_typing()
url = "http://ikbengeslaagd.com/API/sebisauce.json"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
source = await response.json(encoding="utf8")
total_sebi = 0
for key in dict.keys(source):
total_sebi += 1
im = random.randint(0, int(total_sebi) - 1)
await ctx.send(
embed=discord.Embed(
title="\t", description="\t", color=self.bot.embed_color
).set_image(url=source[str(im)])
)
def setup(bot):
bot.add_cog(Fun(bot))
+117
View File
@@ -0,0 +1,117 @@
"""
===
MIT License
Copyright (c) 2018 Dusty.P https://github.com/dustinpianalto
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import discord
from discord.ext import commands
from sebimachine.shared_libs.utils import paginate, run_command
from sebimachine.shared_libs.loggable import Loggable
from sebimachine import __url__
import asyncio
class Git(Loggable):
def __init__(self, bot):
self.bot = bot
@commands.group(case_insensitive=True, invoke_without_command=True)
async def git(self, ctx):
"""Run help git for more info"""
# await ctx.send("https://github.com/dustinpianalto/Sebi-Machine/")
await ctx.send(__url__ or "No URL specified in __init__.py")
@commands.command(case_insensitive=True, brief="Gets the Trello link.")
async def trello(self, ctx):
await ctx.send("<https://trello.com/b/x02goBbW/sebis-bot-tutorial-roadmap>")
@git.command()
async def pull(self, ctx):
self.logger.warning("Invoking git-pull")
await ctx.trigger_typing()
if ctx.author.id not in self.bot.ownerlist:
return await ctx.send(
"Only my contributors can use me like this :blush:", delete_after=10
)
em = discord.Embed(style="rich", title=f"Git Pull", color=self.bot.embed_color)
em.set_thumbnail(url=f"{ctx.guild.me.avatar_url}")
# Pretty sure you can just do await run_command() if that is async,
# or run in a TPE otherwise.
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/$(git rev-parse "
"--symbolic-full-name --abbrev-ref HEAD)"
)
),
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)
for page in results[:5]:
em.add_field(name="\uFFF0", value=f"{page}")
await ctx.send(embed=em)
@git.command()
async def status(self, ctx):
await ctx.trigger_typing()
if ctx.author.id not in self.bot.ownerlist:
return await ctx.send(
"Only my contributors can use me like this :blush:", delete_after=10
)
em = discord.Embed(
style="rich", title=f"Git Status", color=self.bot.embed_color
)
em.set_thumbnail(url=f"{ctx.guild.me.avatar_url}")
result = await asyncio.wait_for(
self.bot.loop.create_task(run_command("git status")), 10
)
results = paginate(result, maxlen=1014)
for page in results[:5]:
em.add_field(name="\uFFF0", value=f"{page}")
await ctx.send(embed=em)
def setup(bot):
bot.add_cog(Git(bot))
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
from discord.ext import commands
import discord
class Moderation:
"""
Moderation Commands
"""
def __init__(self, bot):
self.bot = bot
@commands.command()
async def kick(self, ctx, member: discord.Member = None):
"""
Kick a discord member from your server.
Only contributors can use this command.
Usage:
- kick <discord.member>
"""
await ctx.trigger_typing()
if ctx.author.id not in self.bot.ownerlist:
return await ctx.send(
"Only my contributors can use me like this :blush:", delete_after=10
)
if member is None:
await ctx.send("Are you sure you are capable of this command?")
try:
await member.kick()
await ctx.send(
f"You kicked **`{member.name}`** from **`{ctx.guild.name}`**"
)
except Exception as e:
await ctx.send(
"You may not use this command, as you do not have permission to do so:\n\n**`{ctx.guild.name}`**"
f"\n\n```py\n{e}\n```"
)
@commands.command()
async def ban(self, ctx, member: discord.Member = None):
"""
Ban a discord member from your server.
Only contributors can use this command.
Usage:
- ban <discord.member>
"""
await ctx.trigger_typing()
if ctx.author.id not in self.bot.ownerlist:
return await ctx.send(
"Only my contributors can use me like this :blush:", delete_after=10
)
if member is None:
await ctx.send("Are you sure you are capable of this command?")
try:
await member.ban()
await ctx.send(
f"You banned **`{member.name}`** from **`{ctx.guild.name}`**"
)
except Exception as e:
await ctx.send(
"You may not use this command, as you do not have permission to do so:\n\n**`{ctx.guild.name}`**"
f"\n\n```py\n{e}\n```"
)
def setup(bot):
bot.add_cog(Moderation(bot))
+329
View File
@@ -0,0 +1,329 @@
import asyncio
import inspect
import traceback
import weakref
from typing import Dict
import async_timeout
import dataclasses
import discord
from discord.ext import commands
import youtube_dl
# noinspection PyUnresolvedReferences,PyUnresolvedReferences,PyPackageRequirements
from .utils import noblock
YT_DL_OPTS = {
"format": "ogg[abr>0]/bestaudio/best",
"ignoreerrors": True,
"default_search": "auto",
"source_address": "0.0.0.0",
"quiet": True,
}
# Let it be waiting on an empty queue for about 30 minutes
# before closing the connection from being idle.
IDLE_FOR = 60 * 30
@dataclasses.dataclass(repr=True)
class Request:
"""Track request."""
who: discord.Member
what: str # Referral
title: str # Video title
actual_url: str # Actual URL to play
def __str__(self):
return self.title
def __hash__(self):
return hash(str(self.who.id) + self.what)
# noinspection PyBroadException
class Session:
"""
Each player being run is a session; (E.g. if you open a player in one server and I did in another).
Sessions will have a queue, an event that can fire to stop the current track and move on, and a voice
channel to bind to. This is defined as the voice channel the owner of the session was in when they made the channel.
To create a session, call ``Session.new_session``. Do not call the constructor directly.
Attributes:
ctx: discord.ext.commands.Context
The context of the original command invocation we are creating a session for.
loop: asyncio.AbstractEventLoop
The event loop to run this in.
voice_client: discord.VoiceClient
Voice client we are streaming audio through.
queue: asyncio.Queue
Track queue.
"""
@classmethod
async def new_session(cls, ctx: commands.Context):
"""
Helper to make a new session. Invoke constructor using this, as it handles any errors. It also ensures
we connect immediately.
"""
try:
s = cls(ctx)
await s.connect()
except Exception as ex:
traceback.print_exc()
await ctx.send(
f"I couldn't connect! Reason: {str(ex) or type(ex).__qualname__}"
)
return None
else:
return s
def __init__(self, ctx: commands.Context) -> None:
"""Create a new session."""
if ctx.author.voice is None:
raise RuntimeError("Please enter a voice channel I have access to first.")
# Holds the tasks currently running associated with this.
self.voice_channel = ctx.author.voice.channel
self.ctx: commands.Context = ctx
self.voice_client: discord.VoiceClient = None
self.loop: asyncio.AbstractEventLoop = weakref.proxy(self.ctx.bot.loop)
self.queue = asyncio.Queue()
# Lock-based event to allow firing a handler to advance to the next track.
self._start_next_track_event = asyncio.Event()
self._on_stop_event = asyncio.Event()
self._player: asyncio.Task = None
self._track: asyncio.Task = None
@property
def is_connected(self) -> bool:
return self.voice_client and self.voice_client.is_connected()
async def connect(self) -> None:
"""Connects to the VC."""
if not self.is_connected and not self._player:
# noinspection PyUnresolvedReferences
self.voice_client = await self.voice_channel.connect()
self._start_next_track_event.clear()
self._player = self.__spawn_player()
else:
raise RuntimeError("I already have a voice client/player running.")
async def disconnect(self) -> None:
"""Disconnects from the VC."""
await self.voice_client.disconnect()
self.voice_client = None
def __spawn_player(self) -> asyncio.Task:
"""Starts a new player."""
async def player():
try:
while True:
# Wait on an empty queue for a finite period of time.
with async_timeout.timeout(IDLE_FOR):
request = await self.queue.get()
await self.ctx.send(
f"Playing `{request}` requested by {request.who}"
)
# Clear the skip event if it is set.
self._start_next_track_event.clear()
# Start the player if it was a valid request, else continue to the next track.
if not self.__play(request.actual_url):
await self.ctx.send(
f"{request.referral} was a bad request and was skipped."
)
continue
await self._start_next_track_event.wait()
if self.voice_client.is_playing():
self.voice_client.stop()
except asyncio.CancelledError:
# Hit when someone kills the player using stop().
print("Requested to stop player", repr(self))
except asyncio.TimeoutError:
await self.ctx.send("Was idle for too long...")
print("Player queue was empty for too long and was stopped", repr(self))
except Exception:
traceback.print_exc()
finally:
if self.voice_client.is_playing():
await self.voice_client.stop()
if self.is_connected:
await self.disconnect()
return self.loop.create_task(player())
def __play(self, url):
"""Tries to play the given URL. If it fails, we return False, else we return True."""
try:
ffmpeg_player = discord.FFmpegPCMAudio(url)
# Play the stream. After we finish, either from being cancelled or otherwise, fire the
# skip track event to start the next track.
self.voice_client.play(
ffmpeg_player, after=lambda error: self._start_next_track_event.set()
)
except Exception:
traceback.print_exc()
return False
else:
return True
def skip(self):
"""Request to skip track."""
self._start_next_track_event.set()
def stop(self):
"""Request to stop playing."""
if self._player:
self._player.cancel()
self._on_stop_event.set()
self._on_stop_event.clear()
def on_exit(self, func):
"""Decorates a function to invoke it on exit."""
async def callback():
await self._on_stop_event.wait()
inspect.iscoroutinefunction(func) and await func() or func()
self.loop.create_task(callback())
return func
# noinspection PyBroadException
class PlayerCog:
def __init__(self):
self.sessions: Dict[discord.Guild, Session] = {}
# noinspection PyMethodMayBeStatic
async def __local_check(self, ctx):
return ctx.guild
@commands.command()
async def join(self, ctx):
if ctx.guild not in self.sessions:
p = await Session.new_session(ctx)
if p:
self.sessions[ctx.guild] = p
@p.on_exit
def when_terminated():
try:
self.sessions.pop(ctx.guild)
finally:
return
await ctx.send("*hacker voice*\n**I'm in.**", delete_after=15)
else:
await ctx.send(
f"I am already playing in {self.sessions[ctx.guild].voice_channel.mention}"
)
# noinspection PyNestedDecorators
@staticmethod
@noblock.no_block
def _get_video_meta(referral):
downloader = youtube_dl.YoutubeDL(YT_DL_OPTS)
info = downloader.extract_info(referral, download=False)
return info
@commands.command()
async def queue(self, ctx):
if ctx.guild not in self.sessions:
return await ctx.send("Please join me into a voice channel first.")
sesh = self.sessions[ctx.guild]
if sesh.queue.empty():
return await ctx.send(
"There is nothing in the queue at the moment!\n\n"
"Add something by running `<>play https://url` or `<>play search term`!"
)
# We cannot faff around with the actual queue so make a shallow copy of the internal
# non-async dequeue.
# noinspection PyProtectedMember
agenda = sesh.queue._queue.copy()
message = ["**Queue**"]
for i, item in enumerate(list(agenda)[:15]):
message.append(f"`{i+1: >2}: {item.title} ({item.who})`")
if len(agenda) >= 15:
message.append("")
message.append(f"There are {len(agenda)} items in the queue currently.")
await ctx.send("\n".join(message)[:2000])
@commands.command()
async def play(self, ctx, *, referral):
if ctx.guild not in self.sessions:
return await ctx.send("Please join me into a voice channel first.")
try:
try:
info = await self._get_video_meta(referral)
# If it was interpreted as a search, it appears this happens?
# The documentation is so nice.
if info.get("_type") == "playlist":
info = info["entries"][0]
# ...wait... did I say nice? I meant "non existent."
url = info["url"]
title = info.get("title") or referral
except IndexError:
return await ctx.send("No results...", delete_after=15)
except Exception as ex:
return await ctx.send(
f"Couldn't add this to the queue... reason: {ex!s}"
)
await self.sessions[ctx.guild].queue.put(
Request(ctx.author, referral, title, url)
)
await ctx.send(f"Okay. Queued `{title or referral}`.")
except KeyError:
await ctx.send("I am not playing in this server.")
@commands.command()
async def stop(self, ctx):
try:
await self.sessions[ctx.guild].stop()
except KeyError:
await ctx.send("I am not playing in this server.")
except TypeError:
await ctx.send("I wasn't playing anything, but okay.", delete_after=15)
@commands.command()
async def skip(self, ctx):
try:
self.sessions[ctx.guild].skip()
try:
await ctx.message.add_reaction("\N{OK HAND SIGN}")
except discord.Forbidden:
await ctx.send("\N{OK HAND SIGN}")
except KeyError:
await ctx.send("I am not playing in this server.")
@commands.command()
async def disconnect(self, ctx):
await self.sessions[ctx.guild].stop()
await self.disconnect()
def setup(bot):
bot.add_cog(PlayerCog())
+67
View File
@@ -0,0 +1,67 @@
const Discord = require("discord.js");
exports.run = async function(client, message, args) {
/*
aliases: sar, selfrole, selfroles
examples:
- S!selfrole get 1 (adds heroku helper role)
- S!sar remove 3 (removes rewrite helper role)
- S!sar list (shows all roles)
*/
function roleFinder(query) {
return message.guild.roles.find(function(r) {
return r.name.includes(query)
}).id;
}
const type = args[0]; // can be get, remove or list
if (type == "list" || type == undefined) {
const embed = new Discord.RichEmbed()
.setTitle("List of Self Assigned Roles")
.setDescription("Usage: `S!sar [ get | remove | list ] [ number ]`")
.addField("1. Heroku Helper", "S!sar get 1", true)
.addField("2. JS Helper", "S!sar get 2", true)
.addField("3. Rewrite Helper", "S!sar get 3", true)
.setColor("AQUA");
return message.channel.send({
embed: embed
});
}
const roles = [roleFinder("Heroku"), roleFinder("JS"), roleFinder("Rewrite")];
let choice = args[1]; // can be 1, 2 or 3
// if the choice is not 1, 2 or 3
if (/^[123]$/.test(choice) == false) {
return message.channel.send("Enter a valid role number!"); // returns error message
} else {
choice -= 1; // because array indexing starts from 0. when they choose 1 it should be roles[0]
}
switch (type) {
case "get":
message.member.addRole(roles[choice]);
message.channel.send("Added the role you specified!"); // confirmation message
break;
case "remove":
message.member.removeRole(roles[choice]);
message.channel.send("Removed the role you specified!"); // confirmation message
break;
default:
return; // when it is neither get nor remove
break;
}
}
+106
View File
@@ -0,0 +1,106 @@
import discord
from discord.ext import commands
import json
import aiofiles
import asyncio
class Tag:
def __init__(self, bot):
self.bot = bot
with open("src/shared_libs/tags.json", "r") as fp:
json_data = fp.read()
global tags
tags = json.loads(json_data)
@commands.group(case_insensitive=True, invoke_without_command=True)
async def tag(self, ctx, tag=None):
"""Gets a tag"""
await ctx.trigger_typing()
if tag is None:
return await ctx.send(
"Please provide a argument. Do `help tag` for more info"
)
found = tags.get(tag, None)
if found is None:
return await ctx.send("Tag not found")
await ctx.send(found)
@tag.command(case_insensitive=True)
async def list(self, ctx):
"""Lists available tags"""
await ctx.trigger_typing()
desc = ""
for i in tags:
desc = desc + i + "\n"
if desc == "":
desc = "None"
em = discord.Embed(
title="Available tags:", description=desc, colour=discord.Colour(0x00FFFF)
)
await ctx.send(embed=em)
@tag.command(case_insensitive=True)
async def add(self, ctx, tag_name=None, *, tag_info=None):
"""Adds a new tag"""
await ctx.trigger_typing()
if not ctx.author.guild_permissions.manage_roles:
return await ctx.send("You are not allowed to do this")
if tag_name is None or tag_info is None:
return await ctx.send(
"Please provide a tag name and the tag info. Do `help tag` for more info"
)
exists = False
for i in tags:
if i == tag_name:
exists = True
if not exists:
tags.update({tag_name: tag_info})
async with aiofiles.open("src/shared_libs/tags.json", "w") as fp:
json_data = json.dumps(tags)
await fp.write(json_data)
return await ctx.send("The tag has been added")
await ctx.send("The tag already exists")
@tag.command(case_insensitive=True)
async def remove(self, ctx, tag=None):
"""Remove a existing tag"""
await ctx.trigger_typing()
if not ctx.author.guild_permissions.manage_roles:
return await ctx.send("You are not allowed to do this")
if tag is None:
return await ctx.send(
"Please provide a tag name and the tag info. Do `help tag` for more info"
)
found = None
for i in tags:
if i == tag:
found = i
if found is not None:
del tags[found]
async with aiofiles.open("src/shared_libs/tags.json", "w") as fp:
json_data = json.dumps(tags)
await fp.write(json_data)
return await ctx.send("The tag has been removed")
await ctx.send("The tag has not been found")
def setup(bot):
bot.add_cog(Tag(bot))
+1
View File
@@ -0,0 +1 @@
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
import asyncio
import functools
def no_block(func):
"""Turns a blocking function into a non-blocking coroutine function."""
@functools.wraps(func)
async def no_blocking_handler(*args, **kwargs):
partial = functools.partial(func, *args, **kwargs)
return await asyncio.get_event_loop().run_in_executor(None, partial)
return no_blocking_handler