mirror of
https://github.com/RYGhub/royalnet.git
synced 2024-11-27 13:34:28 +00:00
Tanto ora cambio tutto
This commit is contained in:
parent
934ed55e3e
commit
ded7a2c0e1
2 changed files with 66 additions and 41 deletions
51
database.py
51
database.py
|
@ -1,6 +1,6 @@
|
||||||
import sqlalchemy.exc
|
import sqlalchemy.exc
|
||||||
from sqlalchemy import create_engine, Column, Integer, String, Boolean
|
from sqlalchemy import create_engine, Column, Integer, String, Boolean, DateTime, ForeignKey
|
||||||
from sqlalchemy.orm import sessionmaker
|
from sqlalchemy.orm import sessionmaker, relationship
|
||||||
from sqlalchemy.ext.declarative import declarative_base
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
import bcrypt
|
import bcrypt
|
||||||
|
|
||||||
|
@ -18,6 +18,7 @@ engine = create_engine("sqlite:///db.sqlite")
|
||||||
Base = declarative_base()
|
Base = declarative_base()
|
||||||
Session = sessionmaker(bind=engine)
|
Session = sessionmaker(bind=engine)
|
||||||
|
|
||||||
|
|
||||||
class User(Base):
|
class User(Base):
|
||||||
__tablename__ = "members"
|
__tablename__ = "members"
|
||||||
|
|
||||||
|
@ -27,6 +28,7 @@ class User(Base):
|
||||||
royal = Column(Boolean, nullable=False)
|
royal = Column(Boolean, nullable=False)
|
||||||
telegram_id = Column(Integer, unique=True)
|
telegram_id = Column(Integer, unique=True)
|
||||||
discord_id = Column(Integer, unique=True)
|
discord_id = Column(Integer, unique=True)
|
||||||
|
diario_entries = relationship("Diario")
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.username
|
return self.username
|
||||||
|
@ -34,8 +36,21 @@ class User(Base):
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return f"<User {self.id}: {self.username}>"
|
return f"<User {self.id}: {self.username}>"
|
||||||
|
|
||||||
|
|
||||||
|
class Diario(Base):
|
||||||
|
__tablename__ = "diario"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True)
|
||||||
|
text = Column(String, nullable=False)
|
||||||
|
date = Column(DateTime, nullable=False)
|
||||||
|
author = Column(Integer, ForeignKey("members.id"))
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"<Diario {self.date} {self.text}>"
|
||||||
|
|
||||||
Base.metadata.create_all(engine)
|
Base.metadata.create_all(engine)
|
||||||
|
|
||||||
|
|
||||||
def create_user(username, password, royal=False):
|
def create_user(username, password, royal=False):
|
||||||
"""Create a new user and add it to the database."""
|
"""Create a new user and add it to the database."""
|
||||||
# Create a new session
|
# Create a new session
|
||||||
|
@ -67,7 +82,8 @@ def change_password(username, newpassword):
|
||||||
|
|
||||||
|
|
||||||
def login(username, password, enable_exceptions=False):
|
def login(username, password, enable_exceptions=False):
|
||||||
"""Try to login using the database password. The session is always returned, while the user object is returned if the login is successful."""
|
"""Try to login using the database password.
|
||||||
|
The session is always returned, while the user object is returned if the login is successful."""
|
||||||
# Create a new session
|
# Create a new session
|
||||||
session = Session()
|
session = Session()
|
||||||
# Find the matching user
|
# Find the matching user
|
||||||
|
@ -98,8 +114,29 @@ def find_user(username):
|
||||||
# Return the session and the user
|
# Return the session and the user
|
||||||
return session, db_user
|
return session, db_user
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_diario():
|
||||||
|
import datetime
|
||||||
session = Session()
|
session = Session()
|
||||||
# Generate the database if it's empty
|
file = open("diario.txt", encoding="utf8")
|
||||||
if session.query(User).first() is None:
|
for row in file:
|
||||||
init_royal_db()
|
entry = row.split("|", 1)
|
||||||
del session
|
new = Diario()
|
||||||
|
new.date = datetime.datetime.fromtimestamp(int(entry[0]))
|
||||||
|
new.text = entry[1]
|
||||||
|
session.add(new)
|
||||||
|
session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def new_diario_entry(dt, text, author):
|
||||||
|
# Create a new session
|
||||||
|
session = Session()
|
||||||
|
# Create a new diario entry
|
||||||
|
entry = Diario()
|
||||||
|
entry.date = dt
|
||||||
|
entry.text = text
|
||||||
|
entry.author = author.id
|
||||||
|
# Add the entry to the database
|
||||||
|
session.add(entry)
|
||||||
|
# Commit the change
|
||||||
|
session.commit()
|
||||||
|
|
54
royalbot.py
54
royalbot.py
|
@ -63,21 +63,12 @@ Sintassi: `/diario <frase>`"""
|
||||||
if len(arguments) == 0:
|
if len(arguments) == 0:
|
||||||
await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/diario <random | markov | numerofrase>`", parse_mode="Markdown")
|
await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/diario <random | markov | numerofrase>`", parse_mode="Markdown")
|
||||||
return
|
return
|
||||||
# Check for non-ASCII characters
|
# Find the user
|
||||||
entry = " ".join(arguments)
|
user = currently_logged_in(update)
|
||||||
if not entry.isprintable():
|
# Prepare the text
|
||||||
await update.message.reply(bot, "⚠ La frase che stai provando ad aggiungere contiene caratteri non ASCII, quindi non è stata aggiunta.\nToglili e riprova!")
|
text = " ".join(arguments).strip()
|
||||||
return
|
# Add the new entry
|
||||||
# Remove endlines
|
database.new_diario_entry(update.message.date, text, user)
|
||||||
entry = entry.replace("\n", " ")
|
|
||||||
# TODO: check if a end-of-file character can be sent on Telegram
|
|
||||||
# Generate a timestamp
|
|
||||||
time = update.message.date.timestamp()
|
|
||||||
# Write on the diario file
|
|
||||||
file = open("diario.txt", "a", encoding="utf8")
|
|
||||||
file.write(f"{int(time)}|{entry}\n")
|
|
||||||
file.close()
|
|
||||||
del file
|
|
||||||
# Answer on Telegram
|
# Answer on Telegram
|
||||||
await update.message.reply(bot, "✅ Aggiunto al diario!")
|
await update.message.reply(bot, "✅ Aggiunto al diario!")
|
||||||
|
|
||||||
|
@ -494,23 +485,17 @@ Sintassi: `!roll <max>`"""
|
||||||
await bot.send_message(message.channel, f"*Numero generato:* {random.randrange(0, int(arguments[0])) + 1}")
|
await bot.send_message(message.channel, f"*Numero generato:* {random.randrange(0, int(arguments[0])) + 1}")
|
||||||
|
|
||||||
|
|
||||||
async def adduser_telegram(bot, update, arguments):
|
async def register_telegram(bot, update, arguments):
|
||||||
"""Aggiungi un utente al database Royal Games!
|
"""Registrati al database Royal Games!
|
||||||
|
|
||||||
Devi essere un Royal per poter eseguire questo comando.
|
Sintassi: `/register <username> <password>`"""
|
||||||
|
# One account per user only!
|
||||||
Sintassi: `/adduser <username> <password>`"""
|
if currently_logged_in(update) is not None:
|
||||||
# Check if the user is logged in
|
await update.message.reply(bot, "⚠ Sei già registrato!")
|
||||||
if not currently_logged_in(update):
|
|
||||||
await update.message.reply(bot, "⚠ Non hai ancora eseguito l'accesso! Usa `/sync`.", parse_mode="Markdown")
|
|
||||||
return
|
return
|
||||||
# Check if the currently logged in user is a Royal Games member
|
# Check if the username is printable
|
||||||
if not currently_logged_in(update).royal:
|
if not arguments[0].isprintable():
|
||||||
await update.message.reply(bot, "⚠ Non sei autorizzato a eseguire questo comando.")
|
await update.message.reply(bot, "⚠ Username non valido.")
|
||||||
return
|
|
||||||
# Check the command syntax
|
|
||||||
if len(arguments) != 2:
|
|
||||||
await update.message.reply(bot, "⚠ Sintassi del comando non valida.\n`/adduser <username> <password>`", parse_mode="Markdown")
|
|
||||||
return
|
return
|
||||||
# Try to create a new user
|
# Try to create a new user
|
||||||
try:
|
try:
|
||||||
|
@ -519,8 +504,11 @@ Sintassi: `/adduser <username> <password>`"""
|
||||||
await update.message.reply(bot, "⚠ Qualcosa è andato storto nella creazione dell'utente. Per altre info, guarda i log del bot.")
|
await update.message.reply(bot, "⚠ Qualcosa è andato storto nella creazione dell'utente. Per altre info, guarda i log del bot.")
|
||||||
raise
|
raise
|
||||||
else:
|
else:
|
||||||
await update.message.reply(bot, "✅ Creazione riuscita!")
|
session, logged_user = database.login(arguments[0], arguments[1])
|
||||||
|
logged_user.telegram_id = update.message.sent_from.user_id
|
||||||
|
session.commit()
|
||||||
|
print(f"{logged_user} ha sincronizzato l'account di Telegram.")
|
||||||
|
await update.message.reply(bot, f"Sincronizzazione riuscita!\nSei loggato come `{logged_user}`.", parse_mode="Markdown")
|
||||||
|
|
||||||
async def toggleroyal_telegram(bot, update, arguments):
|
async def toggleroyal_telegram(bot, update, arguments):
|
||||||
"""Inverti lo stato di Royal di un utente.
|
"""Inverti lo stato di Royal di un utente.
|
||||||
|
@ -568,7 +556,7 @@ if __name__ == "__main__":
|
||||||
b.commands["markov"] = markov_telegram
|
b.commands["markov"] = markov_telegram
|
||||||
b.commands["cv"] = cv_telegram
|
b.commands["cv"] = cv_telegram
|
||||||
b.commands["roll"] = roll_telegram
|
b.commands["roll"] = roll_telegram
|
||||||
b.commands["adduser"] = adduser_telegram
|
b.commands["register"] = register_telegram
|
||||||
b.commands["toggleroyal"] = toggleroyal_telegram
|
b.commands["toggleroyal"] = toggleroyal_telegram
|
||||||
# Init Discord bot commands
|
# Init Discord bot commands
|
||||||
d.commands["sync"] = sync_discord
|
d.commands["sync"] = sync_discord
|
||||||
|
|
Loading…
Reference in a new issue