I am currently working on a Discord bot as a way to learn and practice Python. I have been trying to learn object-oriented programming, and apply the "don't repeat yourself" principle.
The code below connects/disconnects from a local database (using XAMPP) with the "mysql.connector" package, and registers a user in the database using their Discord ID. In my example below, I define a class called MySQL
, and define three methods (connect()
, disconnect()
and query_users()
) that I found myself using in almost every command/method.
In my register
command/method, I call all three methods (connect()
, disconnect()
and query_users()
). Is this the correct way to access those methods and their variables in my register command? My code works great, but the more I read on OOP, the less confident I become, and the more I question myself. Any tips or confirmation would be greatly appreciated.
Thank you all for your help.
"""The following packages/modules are required:""" import json import mysql.connector from discord.ext import commands as viking with open('config/database.json') as config: database = json.load(config) class MySQL: def __init__(self, viking): self.viking = viking def connect(self): self.connection = mysql.connector.connect(**database) self.cursor = self.connection.cursor(buffered=True) def disconnect(self): self.cursor.close() self.connection.close() def query_users(self): self.cursor.execute("SELECT discord_id FROM users") self.existing_users = ', '.join([str(users[0]) for users in self.cursor]) @viking.command(pass_context=True) async def register(self, ctx): """*register Viking will register your Discord ID in the Viking database.""" self.connect() self.query_users() discord_id = str(ctx.message.author.id) if discord_id in self.existing_users: await self.viking.say('You are already a registered member in the Viking database.') else: self.cursor.execute("INSERT INTO users (discord_id) VALUES (%s)", (discord_id,)) self.connection.commit() await self.viking.say('You are now registered in the Viking database.') self.disconnect()