'Python Discord Bot Commands Decorator within classes
Hey I was coding a discord bot, however I can't figure out how to write the commands decorator, I think that's because I am putting all the code in a class, without a class the commands work fine since I can use the a variable that has been initialized to the bot, but I can't use self here. However how can I add a command within a class.
Right now it keeps throwing a command not found error, I know I can use cogs but I am just wondering a way to do it within the class currently.
import discord
from extensions import data, database
from discord.ext import commands
async def get_prefix(ctx, message):
# Fetches the prefixes for the guild from the database
return data.select(guild_id=message.guild.id, extract='prefixes',)
class DeveloperBot(commands.Bot,):
async def on_ready(self):
print ('Discord Developer Bot is running; {0.user}'.format(self))
await commands.Bot.change_presence(
self,
status=discord.Status.idle,
activity=discord.Game('Playing Rockets')
)
# Checks if the Database file exists
database.check_guild()
async def on_guild_join(self, guild):
data.update(guild_id=guild.id, guild_name=guild.name)
async def on_guild_leave(self, guild):
data.remove(guild_id=guild.id)
# problem is here
commands.command()
async def hello(self, ctx, message):
await ctx.send('Hello')
bot = DeveloperBot(command_prefix=get_prefix)
bot.run('token')
Solution 1:[1]
It is @commands.command(). The @ signifies the syntactic sugar for a decorator.
PS: You also have redundant commas like, commands.Bot, and extract='prefixes',. Also, adding those lines in between function signatures and the actual function code makes the code a bit less readable. In addition, for the bot presence change, do:
await commands.Bot.change_presence(
status=discord.Status.idle,
activity=discord.Game('Playing Rockets')
)
Passing self is redundant as it is passed by Python implicitly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | binds |
