Как сохранить данные после получения случайного ответа из набора вариантов?Python

Программы на Python
Anonymous
Как сохранить данные после получения случайного ответа из набора вариантов?

Сообщение Anonymous »

Настройка работает, когда есть только один вариант, но перестает работать, как только я добавляю в смесь вторую деревню. Всего должно быть 12.

Код: Выделить всё

import mysql.connector
import nextcord
from nextcord import Intents
from nextcord.ext import commands
from mysql.connector import Error
import random

intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)

@bot.command(name="village")
async def village(ctx):
villages = [1, 2]
user = ctx.message.author
guild = ctx.guild.id

connection = mysql.connector.connect(
host="localhost",
port="3306",
user="root",
password="root",
database="naruto_game"
)

if villages == [1]:
village = "Konohagakure"

try:

mySql_Create_Table_Query = """CREATE TABLE VILLAGES_""" + str(guild) + """ (
Id int(11) NOT NULL AUTO_INCREMENT,
User varchar(250) NOT NULL,
Village varchar(5000) NOT NULL,
PRIMARY KEY (Id)) """

cursor = connection.cursor()
result = cursor.execute(mySql_Create_Table_Query)
print(f"Village Database for Guild (" + str(guild) + ") Table created successfully")

except mysql.connector.Error as error:
print("Failed to create table in MySQL: {}".format(error))

finally:
if connection.is_connected():

table = "VILLAGES_" + str(guild)

mySql_Insert_Row_Query = "INSERT INTO " + table + " (User, Village) VALUES (%s, %s)"
mySql_Insert_Row_Values = (str(user), village)
sql_select_query = "SELECT * from " + table + " where user like '"+ str(ctx.message.author) +"'"
cursor.execute(sql_select_query)
records = cursor.fetchall()

if len(records) == 0:
cursor.execute(mySql_Insert_Row_Query, mySql_Insert_Row_Values)
connection.commit()

await ctx.send(f"{user} has been born into {village}.")

else:
await ctx.send("You are already in a village. Use !profile to see what village you're in.")

elif villages == [2]:
village = "Iwagakure"

try:

mySql_Create_Table_Query = """CREATE TABLE VILLAGES_""" + str(guild) + """ (
Id int(11) NOT NULL AUTO_INCREMENT,
User varchar(250) NOT NULL,
Village varchar(5000) NOT NULL,
PRIMARY KEY (Id)) """

cursor = connection.cursor()
result = cursor.execute(mySql_Create_Table_Query)
print(f"Village Database for Guild (" + str(guild) + ") Table created successfully")

except mysql.connector.Error as error:
print("Failed to create table in MySQL: {}".format(error))

finally:
if connection.is_connected():

table = "VILLAGES_" + str(guild)

mySql_Insert_Row_Query = "INSERT INTO " + table + " (User, Village) VALUES (%s, %s)"
mySql_Insert_Row_Values = (str(user), village)
sql_select_query = "SELECT * from " + table + " where user like '"+ str(ctx.message.author) +"'"
cursor.execute(sql_select_query)
records = cursor.fetchall()

if len(records) == 0:
cursor.execute(mySql_Insert_Row_Query, mySql_Insert_Row_Values)
connection.commit()

await ctx.send(f"{user} has been born into {village}.")

else:
await ctx.send("You are already in a village.  Use !profile to see what village you're in.")
Я пытаюсь добраться туда, где он получит команду, выбрать случайную деревню из 12, затем сохранить ее в базе данных, а затем отправить сообщение с указанием, в какой деревне они получил.

Подробнее здесь: https://stackoverflow.com/questions/790 ... of-options

Вернуться в «Python»