Reputation: 27
hope some of wonderful folks could help me with this, as im super stuck and to me everything seems to look correct but my command is not adding anything to the database. So what i'm looking to achieve is that when i type q!newuser "name" & "discord" it adds the values to the database
Here goes:
from discord.ext import commands
import os
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
client = commands.Bot(command_prefix='q!')
@client.command()
async def load(ctx, extension):
client.load_extension(f'cogs.{extension}')
@client.command()
async def unload(ctx, extension):
client.unload_extension(f'cogs.{extension}')
for filename in os.listdir(f'./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
def connect():
""" Connect to MySQL database """
db_config = read_db_config()
conn = None
try:
print('Connecting to MySQL database...')
conn = MySQLConnection(**db_config)
if conn.is_connected():
print('Connection established.')
else:
print('Connection failed.')
except Error as error:
print(error)
finally:
if conn is not None and conn.is_connected():
conn.close()
print('Connection closed.')
if __name__ == '__main__':
connect()
client.remove_command('help')
client.run('mytoken')
from configparser import ConfigParser
def read_db_config(filename='config.ini', section='mysql'):
""" Read database configuration file and return a dictionary object
:param filename: name of the configuration file
:param section: section of database configuration
:return: a dictionary of database parameters
"""
# create parser and read ini configuration file
parser = ConfigParser()
parser.read(filename)
# get section, default to mysql
db = {}
if parser.has_section(section):
items = parser.items(section)
for item in items:
db[item[0]] = item[1]
else:
raise Exception('{0} not found in the {1} file'.format(section, filename))
return db
[mysql]
host = localhost
database = bot_database
user = root
password = mypass
auth_plugin = mysql_native_password
Now to my commands:
import database
from discord.ext import commands
class Newuser(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(name="newuser")
@commands.has_permissions(administrator=True)
async def insert_user(self, ctx, *args):
try:
name = ' '.join(args)
discord = ' '.join(args)
except IndexError:
try:
name = ' '.join(args)
age = ' '.join(args)
except ValueError:
await ctx.send("Please enter a name")
return
except IndexError:
await ctx.send("Please add users details")
return
add = database.insert_user(player_name=name, discord_tag=discord)
if isinstance(add, Exception):
await ctx.send(f"Database error when adding a new admin:\n```\n{add}\n```")
return
await ctx.send("Added the role to my admin list.")
def setup(client):
client.add_cog(Newuser(client))
and my Insert query
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
########################################################
################### MySQL Defines ######################
################### Testing ######################
########################################################
def insert_user(player_name, discord_tag):
try:
db_config = read_db_config()
conn = MySQLConnection(**db_config)
c = conn.cursor()
c.execute(
"INSERT INTO 'user_management' ('player_name', 'discord_tag') values((%s, %s);",
player_name, discord_tag)
conn.commit()
c.close()
except Error as e:
return e
Sorry its a lenthy post, but i am fairly new to python and wanted to provide all the files i have. Again, all seems to work but nothing appears in my "Mysql" database and pycharm shows no errors.
Appreciate the time to took to look over this for me.
Thank you, Ben
Upvotes: 1
Views: 2711
Reputation: 465
I think you have a typo in your query. Though I don't know why no errors would show up.
Have you tried doing something even more broad, like
except Exception as e:
return e
for insert_user
?
It just seems like the exception is being handled somewhere silently, but from the information you've provided, I can't figure out why.
On a side note, discord suggests a particular way to handle exceptions: discordpy error-handling.
It may seem counter-intuitive at first, but it definitely helps pin down problems and troubleshoot.
Upvotes: 1