- 
      
- 
        Save barbosso/efb21e4029aefc2043e38b90b88918c7 to your computer and use it in GitHub Desktop. 
    A Cogs Example for the rewrite version of - discord.py
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import discord | |
| from discord.ext import commands | |
| import sys, traceback | |
| """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 |rewrite| version on the lib. | |
| For examples on cogs for the |async| version: | |
| https://gist.github.com/leovoel/46cd89ed6a8f41fd09c5 | |
| Rewrite Documentation: | |
| http://discordpy.readthedocs.io/en/rewrite/api.html | |
| Rewrite Commands Documentation: | |
| http://discordpy.readthedocs.io/en/rewrite/ext/commands/api.html | |
| Familiarising yourself with the documentation will greatly help you in creating your bot and using cogs. | |
| """ | |
| def get_prefix(bot, msg): | |
| """A callable Prefix for our bot. This could be edited to allow per server prefixes. | |
| For this example though we will keep it simple. | |
| We will allow for a [list] of prefixes or [mention] to serve as our prefix. | |
| We don't technically need a custom callable for this use case, but it showcases it's potential. | |
| Could be a |coroutine| | |
| bot : Bot | |
| msg : Message""" | |
| # Notice how you can use spaces in prefixes. Try to keep them simple though. | |
| prefixes = ['>?', 'lol ', '!?'] | |
| # Check to see if we are outside of a guild. e.g DM's etc. | |
| if msg.guild.id is None: | |
| # Only allow ? to be used in DMs | |
| return '?' | |
| # 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, msg) | |
| """Here we define the cogs we would like to load when the bot starts. They will be loaded in |on_ready| below. | |
| It's a good idea to keep your cogs in a folder within your main package folder. In this case [cogs]. | |
| Notice how we use a dot path style, just as we do with imports. | |
| Format: folder.file""" | |
| initial_extensions = ('cogs.simple', | |
| 'cogs.handler',) | |
| """Here we instance our bot... commands.Bot subclasses discord.Client, thus it can do everything Client can and more. | |
| http://discordpy.readthedocs.io/en/rewrite/ext/commands/api.html#discord.ext.commands.Bot""" | |
| bot = commands.Bot(command_prefix=get_prefix, description='A Rewrite Cog Example') | |
| @bot.event | |
| async def on_ready(): | |
| """http://discordpy.readthedocs.io/en/rewrite/api.html#discord.on_ready | |
| When our bot has logged in and done preparing data, |on_ready| will be called. | |
| Here is a good place to do anything you need to when the bot initially loads. | |
| |coroutine|""" | |
| print(f'\n\nLogged in as: {bot.user.name} - {bot.user.id}\nVersion: {discord.__version__}\n') | |
| # 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='Cogs Example', type=1, url='https://twitch.tv/kraken')) | |
| # Here we load our extensions 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() | |
| print(f'Successfully logged in and booted...!') | |
| '''Here we start the event loop and attempt to login. Any code below this will not run until the bot has logged out | |
| and the event loop has been closed. | |
| For more information: | |
| http://discordpy.readthedocs.io/en/rewrite/ext/commands/api.html#discord.ext.commands.Bot.run | |
| If reconnect is True. The bot will attempt to reconnect before closing the loop in the case of disconnections/dropouts etc.''' | |
| bot.run('TOKEN', bot=True, reconnect=True) | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import discord | |
| from discord.ext import commands | |
| """A simple cog example with simple commands.""" | |
| class SimpleCog: | |
| """SimpleCog""" | |
| def __init__(self, bot): | |
| self.bot = bot | |
| '''Below we create our command {repeat}. | |
| Our command function must be a |coroutine| | |
| The command decorator takes in several Optional[arguments]. | |
| name : Optional[str] - Used to call the command | |
| aliases : Optional[list[str]] - Used to call the command from a list of names. | |
| The command can also be called using the defined function name |do_repeat|. | |
| Notice the first parameter of our command function after self. | |
| ctx : Context | |
| In rewrite Context is automatically passed to our commands as the first argument after self. | |
| ''' | |
| @commands.command(name='repeat', aliases=['copy', 'mimic']) | |
| async def do_repeat(self, ctx, *, inp: str): | |
| """A simple command which repeats our input. | |
| inp : [str]""" | |
| '''Here we see that |send| automatically retrieves the channel contained in context for us. | |
| This is similar to bot.say - (From async). | |
| It will send the message to the channel which the command was invoked.''' | |
| await ctx.send(f'{inp}') | |
| '''Below we create our command {add}. | |
| Our command function must be a |coroutine|. | |
| For this command we have added a check |guild_only|. | |
| This makes sure that our command can only be used in a guild. | |
| If it is used outside of a guild, the check will fail and an error will be sent to |on_command_error|. | |
| For a list of inbuilt checks: | |
| http://dischttp://discordpy.readthedocs.io/en/rewrite/ext/commands/api.html#checksordpy.readthedocs.io/en/rewrite/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 | |
| ''' | |
| @commands.command(name='add', aliases=['plus']) | |
| @commands.guild_only() | |
| async def do_addition(self, ctx, first: int, second: int): | |
| """A simple command which does addition on two integer values. | |
| first : [int] | |
| second : [int]""" | |
| total = first + second | |
| await ctx.send(f'The sum of **{first}** and **{second}** is **{total}**') | |
| '''Below we create our command {me}. | |
| Our command function must be a |coroutine|. | |
| For this command we have added a check |is_owner|. | |
| This makes sure that our command can only be used by the bot owner. | |
| ''' | |
| @commands.command(name='me') | |
| @commands.is_owner() | |
| async def only_me(self, ctx): | |
| """A simple command which only responds to the owner of the bot. | |
| Showcased here is [Member.mention] which allows us to mention a member with ease. In this case the person who | |
| invoked the command, otherwise known as [author]. | |
| http://discordpy.readthedocs.io/en/rewrite/api.html#discord.Member.mention""" | |
| await ctx.send(f'Hello {ctx.author.mention}. I only respond to you!') | |
| def setup(bot): | |
| bot.add_cog(SimpleCog(bot)) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment