Skip to content

Instantly share code, notes, and snippets.

@Gear-Smith
Last active March 27, 2020 23:43
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Gear-Smith/068cef8ff640e90d3636d133fa8f72a1 to your computer and use it in GitHub Desktop.
Save Gear-Smith/068cef8ff640e90d3636d133fa8f72a1 to your computer and use it in GitHub Desktop.
A Cogs Example for the 0.16.12 version of - discord.py (with automatic directory searching)
import discord
from discord.ext import commands
import asyncio
import random
import os
import sys, traceback
description = '''
This is a multi file example showcasing many features of the command extension and the use of cogs.
These are examples only and are not intended to be used as a fully functioning bot. Rather they should give you a basic
understanding and platform for creating your own bot.
These examples make use of Python 3.6.2 and the latest 0.16.12 version on the lib.
For examples on cogs for the async version:
https://gist.github.com/leovoel/46cd89ed6a8f41fd09c5
v0.16.12 Documentation:
https://discordpy.readthedocs.io/en/v0.16.12/api.html
Familiarising yourself with the documentation will greatly help you in creating your bot and using cogs. '''
def get_prefix(bot, message):
"""A callable Prefix for our bot. This could be edited to allow per server prefixes."""
# Notice how you can use spaces in prefixes. Try to keep them simple though.
prefixes = ['?', '!']
# If we are in a guild, we allow for the user to mention us or use any of the prefixes in our list.
return commands.when_mentioned_or(*prefixes)(bot, message)
# Check to see if we are outside of a guild. e.g DM's etc.
'''
if not message.guild:
# Only allow ? to be used in DMs
return '?'
'''
# Below cogs represents our folder our cogs are in. Following is the file name. So 'meme.py' in cogs, would be cogs.meme
# Think of it like a dot path import
initial_extensions = ['cogs.simple',
'cogs.members',
'cogs.owner']
bot = commands.Bot(command_prefix=get_prefix, description=description)
# Here we load our extensions(cogs) listed above in [initial_extensions].
if __name__ == '__main__':
for extension in initial_extensions:
try:
bot.load_extension(extension)
except Exception as e:
print(f'Failed to load extension {extension}.', file=sys.stderr)
traceback.print_exc()
@bot.event
async def on_ready():
"""http://discordpy.readthedocs.io/en/rewrite/api.html#discord.on_ready"""
if not hasattr(bot, 'appinfo'):
bot.AppInfo = await bot.application_info()
print(f'\n\nLogged in as: {bot.user.name} - {bot.user.id}\nVersion: {discord.__version__}\nOwner: {bot.AppInfo.owner}')
# Changes our bots Playing Status. type=1(streaming) for a standard game you could remove type and url.
await bot.change_presence(game=discord.Game(name='Banana'))
print(f'Successfully logged in and booted...!')
bot.run('token', bot=True, reconnect=True)
import discord
from discord.ext import commands
class MembersCog:
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
# @commands.guild_only()
async def joined(self, ctx, member: discord.Member=None):
"""Says when a member joined."""
if member is None:
member = ctx.message.author
await self.bot.say(f'{member.display_name} joined on {member.joined_at}')
@commands.command(name='coolbot')
async def cool_bot(self):
"""Is the bot cool?"""
await self.bot.say('This bot is cool. :)')
@commands.command(pass_context=True, name='top_role', aliases=['toprole'])
# @commands.guild_only()
async def show_toprole(self, ctx, member: discord.Member=None):
"""Simple command which shows the members Top Role."""
if member is None:
member = ctx.message.author
await self.bot.say(f'The top role for {member.display_name} is {member.top_role.name}')
@commands.command(pass_context=True, name='perms', aliases=['perms_for', 'permissions'])
# @commands.guild_only()
async def check_permissions(self, ctx, member: discord.Member=None):
"""A simple command which checks a members Guild Permissions.
If member is not provided, the author will be checked."""
if not member:
member = ctx.message.author
# Here we check if the value of each permission is True.
perms = '\n'.join(perm for perm, value in member.server_permissions if value)
# And to make it look nice, we wrap it in an Embed.
embed = discord.Embed(title='Permissions for:', description=member.server.name, colour=member.colour)
embed.set_author(icon_url=member.avatar_url, name=str(member))
# \uFEFF is a Zero-Width Space, which basically allows us to have an empty field name.
embed.add_field(name='\uFEFF', value=perms)
await self.bot.say(content=None, embed=embed)
# Thanks to Gio for the Command.
# The setup fucntion below is neccesarry. Remember we give bot.add_cog() the name of the class in this case MembersCog.
# When we load the cog, we use the name of the file.
def setup(bot):
bot.add_cog(MembersCog(bot))
from discord.ext import commands
class OwnerCog:
def __init__(self, bot):
self.bot = bot
# Hidden means it won't show up on the default help.
@commands.command(name='load', hidden=True)
# @commands.is_owner()
async def cog_load(self, *, cog: str):
"""Command which Loads a Module.
Remember to use dot path. e.g: cogs.owner"""
try:
self.bot.load_extension(cog)
except Exception as e:
await self.bot.say(f'**`ERROR:`** {type(e).__name__} - {e}')
else:
await self.bot.say('**`SUCCESS`**')
@commands.command(name='unload', hidden=True)
# @commands.is_owner()
async def cog_unload(self, *, cog: str):
"""Command which Unloads a Module.
Remember to use dot path. e.g: cogs.owner"""
try:
self.bot.unload_extension(cog)
except Exception as e:
await self.bot.say(f'**`ERROR:`** {type(e).__name__} - {e}')
else:
await self.bot.say('**`SUCCESS`**')
@commands.command(name='reload', hidden=True)
# @commands.is_owner()
async def cog_reload(self, *, cog: str):
"""Command which Reloads a Module.
Remember to use dot path. e.g: cogs.owner"""
try:
self.bot.unload_extension(cog)
self.bot.load_extension(cog)
except Exception as e:
await self.bot.say(f'**`ERROR:`** {type(e).__name__} - {e}')
else:
await self.bot.say('**`SUCCESS`**')
def setup(bot):
bot.add_cog(OwnerCog(bot))
import discord
from discord.ext import commands
"""A simple cog example with simple commands. Showcased here are some check decorators, and the use of events in cogs.
For a list of inbuilt checks:
http://dischttp://discordpy.readthedocs.io/en/rewrite/ext/commands/api.html#checksordpy.readthedocs.io/en/v0.16.12/ext/commands/api.html#checks
You could also create your own custom checks. Check out:
https://github.com/Rapptz/discord.py/blob/master/discord/ext/commands/core.py#L689
For a list of events:
https://discordpy.readthedocs.io/en/v0.16.12/api.html#event-reference
"""
class SimpleCog:
"""SimpleCog"""
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True, name='repeat', aliases=['copy', 'mimic'])
async def do_repeat(self, ctx, our_input: str):
"""A simple command which repeats our input.
"""
our_input = ctx.message.content
await self.bot.say(our_input)
@commands.command(name='add', aliases=['plus'])
# @commands.guild_only()
async def do_addition(self, first: int, second: int):
"""A simple command which does addition on two integer values."""
total = first + second
await self.bot.say(f'The sum of **{first}** and **{second}** is **{total}**')
@commands.command(pass_context=True, name='me')
async def only_me(self, ctx):
"""A simple command which only responds to the owner of the bot."""
if self.bot.AppInfo.owner == ctx.message.author:
await self.bot.say(f'Hello {ctx.message.author.mention}. This command can only be used by you!!')
@commands.command(pass_context=True, name='embeds')
# @commands.guild_only()
async def example_embed(self, ctx):
"""A simple command which showcases the use of embeds.
Have a play around and visit the Visualizer."""
embed = discord.Embed(title='Example Embed',
description='Showcasing the use of Embeds...\nSee the visualizer for more info.',
colour=0x98FB98)
embed.set_author(name='MysterialPy',
url='https://gist.github.com/MysterialPy/public',
icon_url='http://i.imgur.com/ko5A30P.png')
embed.set_image(url='https://cdn.discordapp.com/attachments/84319995256905728/252292324967710721/embed.png')
embed.add_field(name='Embed Visualizer', value='[Click Here!](https://leovoel.github.io/embed-visualizer/)')
embed.add_field(name='Command Invoker', value=ctx.message.author.mention)
embed.set_footer(text='Made in Python with discord.py@rewrite', icon_url='http://i.imgur.com/5BFecvA.png')
await self.bot.say(content='**A simple Embed for discord.py@0.16.12 in cogs.**', embed=embed)
async def on_member_ban(self, guild, user):
"""Event Listener which is called when a user is banned from the guild.
For this example I will keep things simple and just print some info.
Notice how because we are in a cog class we do not need to use @bot.event
For more information:
http://discordpy.readthedocs.io/en/rewrite/api.html#discord.on_member_ban
Check above for a list of events.
"""
print(f'{user.name}-{user.id} was banned from {guild.name}-{guild.id}')
# The setup fucntion below is neccesarry. Remember we give bot.add_cog() the name of the class in this case SimpleCog.
# When we load the cog, we use the name of the file.
def setup(bot):
bot.add_cog(SimpleCog(bot))
@ImPrabakar
Copy link

on main file in on_ready event i just typed same but returns

Ignoring exception in on_ready
AttributeError: coroutine oattribute owner

My code:

@bot.event
async def on_ready():
	if not hasattr(bot, 'appinfo'):
		bot.AppInfo = bot.application_info()
	print(f"Logged in as\nOwner: {bot.AppInfo.owner}")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment