Skip to content

Instantly share code, notes, and snippets.

@leovoel
Last active January 25, 2024 04:19
Show Gist options
  • Star 76 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save leovoel/46cd89ed6a8f41fd09c5 to your computer and use it in GitHub Desktop.
Save leovoel/46cd89ed6a8f41fd09c5 to your computer and use it in GitHub Desktop.
discord.py's basic_bot.py converted to use "cogs".
from discord.ext import commands
description = '''An example bot to showcase the discord.ext.commands extension
module.
There are a number of utility commands being showcased here.'''
# this specifies what extensions to load when the bot starts up
startup_extensions = ["members", "rng"]
bot = commands.Bot(command_prefix='?', description=description)
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
@bot.command()
async def load(extension_name : str):
"""Loads an extension."""
try:
bot.load_extension(extension_name)
except (AttributeError, ImportError) as e:
await bot.say("```py\n{}: {}\n```".format(type(e).__name__, str(e)))
return
await bot.say("{} loaded.".format(extension_name))
@bot.command()
async def unload(extension_name : str):
"""Unloads an extension."""
bot.unload_extension(extension_name)
await bot.say("{} unloaded.".format(extension_name))
@bot.command()
async def add(left : int, right : int):
"""Adds two numbers together."""
await bot.say(left + right)
@bot.command()
async def repeat(times : int, content='repeating...'):
"""Repeats a message multiple times."""
for i in range(times):
await bot.say(content)
if __name__ == "__main__":
for extension in startup_extensions:
try:
bot.load_extension(extension)
except Exception as e:
exc = '{}: {}'.format(type(e).__name__, e)
print('Failed to load extension {}\n{}'.format(extension, exc))
bot.run('token')
import discord
from discord.ext import commands
class Members():
def __init__(self, bot):
self.bot = bot
@commands.command()
async def joined(self, member : discord.Member):
"""Says when a member joined."""
await self.bot.say('{0.name} joined in {0.joined_at}'.format(member))
@commands.group(pass_context=True)
async def cool(self, ctx):
"""Says if a user is cool.
In reality this just checks if a subcommand is being invoked.
"""
if ctx.invoked_subcommand is None:
await self.bot.say('No, {0.subcommand_passed} is not cool'.format(ctx))
@cool.command(name='bot')
async def _bot(self):
"""Is the bot cool?"""
await self.bot.say('Yes, the bot is cool.')
def setup(bot):
bot.add_cog(Members(bot))
import random
from discord.ext import commands
class RNG():
def __init__(self, bot):
self.bot = bot
@commands.command()
async def roll(self, dice : str):
"""Rolls a dice in NdN format."""
try:
rolls, limit = map(int, dice.split('d'))
except Exception:
await self.bot.say('Format has to be in NdN!')
return
result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))
await self.bot.say(result)
@commands.command(description='For when you wanna settle the score some other way')
async def choose(self, *choices : str):
"""Chooses between multiple choices."""
await self.bot.say(random.choice(choices))
def setup(bot):
bot.add_cog(RNG(bot))
Copy link

ghost commented Aug 22, 2017

Rewrite version when

@Lin5427
Copy link

Lin5427 commented Aug 24, 2017

you can convert async2rewrite quite easily

@EvieePy
Copy link

EvieePy commented Aug 26, 2017

A rewrite cogs example can be found here: https://gist.github.com/EvieePy/d78c061a4798ae81be9825468fe146be

Credits to Leo for some of the content and other members for helping.

@modelmat
Copy link

@leovoel An example of this with automatic dir loading: https://gist.github.com/Modelmat/b2f92ad6db3d89302649ceb6dcb19744

@PythonJames
Copy link

how do you use the NDN format for the roll command

@revsuine
Copy link

revsuine commented Apr 3, 2018

Thank you! This is super informative and helpful.

@WalrusGumboot
Copy link

@PythonJames:

N stands for the amount of dice to be thrown
d is a separator
N is the amount of sides on said dice.

For example: 5d6 would throw 5 6-sided dice.

@JoshuaRose-Github
Copy link

@PythonJames:

N stands for the amount of dice to be thrown
d is a separator
N is the amount of sides on said dice.

For example: 5d6 would throw 5 6-sided dice.

Thanks that was really helpful

@TheRedstoneRadiant
Copy link

Awesome!

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