Archived
1
0
Fork 0

Setup database

This commit is contained in:
Ethanell 2020-11-07 15:15:44 +01:00
parent bf6bdaac79
commit 1618345ba3
11 changed files with 79 additions and 27 deletions

3
.gitignore vendored
View file

@ -133,3 +133,6 @@ dmypy.json
# Config file # Config file
config.json config.json
# db
*.db

View file

@ -2,8 +2,8 @@ from json import load
from telegram.ext import Updater from telegram.ext import Updater
config = load(open("config.json"))
updater = Updater(token=load(open("config.json"))["bot_token"], use_context=True) updater = Updater(token=config["bot_token"], use_context=True)
import commands import commands
import callbackQuery import callbackQuery

View file

@ -10,7 +10,8 @@ from reportlab.pdfgen import canvas
from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import CallbackContext from telegram.ext import CallbackContext
from main import reasons, database import db
from main import reasons
local = { local = {
"work": "travail", "work": "travail",
@ -30,11 +31,14 @@ def create(update: Update, context: CallbackContext):
reason = reasons[update.effective_chat.id][update["_effective_user"]["id"]] reason = reasons[update.effective_chat.id][update["_effective_user"]["id"]]
del reasons[update.effective_chat.id][update["_effective_user"]["id"]] del reasons[update.effective_chat.id][update["_effective_user"]["id"]]
date = datetime.now() date = datetime.now()
first_name = database[update['_effective_user']['id']]['first_name'] s = db.Session()
last_name = database[update['_effective_user']['id']]['last_name'] u = s.query(db.User).get(update["_effective_user"]["id"])
birth_date = database[update['_effective_user']['id']]['birth_date'] s.close()
birth_city = database[update['_effective_user']['id']]['birth_city'] first_name = u.first_name
address = address_re.fullmatch(database[update['_effective_user']['id']]['address']).groups() last_name = u.last_name
birth_date = u.birth_date
birth_city = u.birth_city
address = address_re.fullmatch(u.address).groups()
img = make(f"Cree le: {date.strftime('%d/%m/%Y a %Hh%M')};\n" img = make(f"Cree le: {date.strftime('%d/%m/%Y a %Hh%M')};\n"
f"Nom: {first_name};\n" f"Nom: {first_name};\n"
@ -54,7 +58,7 @@ def create(update: Update, context: CallbackContext):
can = canvas.Canvas(packet, pagesize=letter) can = canvas.Canvas(packet, pagesize=letter)
can.setFont("Helvetica", 11) can.setFont("Helvetica", 11)
can.drawString(119, 696, f"{first_name} {last_name}") can.drawString(119, 696, f"{first_name} {last_name}")
can.drawString(119, 674, birth_date) can.drawString(119, 674, birth_date.strftime("%d/%m/%Y"))
can.drawString(297, 674, birth_city) can.drawString(297, 674, birth_city)
can.drawString(133, 652, f"{address[0]} {address[1]} {address[2]}") can.drawString(133, 652, f"{address[0]} {address[1]} {address[2]}")
can.setFontSize(18) can.setFontSize(18)

View file

@ -1,22 +1,23 @@
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ParseMode, Update from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ParseMode, Update
from telegram.ext import CallbackContext from telegram.ext import CallbackContext
from main import database import db
def data(update: Update, context: CallbackContext): def data(update: Update, context: CallbackContext):
if update["_effective_user"]["id"] not in database: s = db.Session()
database[update["_effective_user"]["id"]] = {"first_name": None, u = s.query(db.User).get(update["_effective_user"]["id"])
"last_name": None, if not u:
"birth_date": None, u = db.User(update["_effective_user"]["id"])
"birth_city": None, s.add(u)
"address": None} s.commit()
s.close()
context.bot.send_message(chat_id=update.effective_chat.id, context.bot.send_message(chat_id=update.effective_chat.id,
text=f"*Firstname*: `{database[update['_effective_user']['id']]['first_name']}`\n" text=f"*Firstname*: `{u.first_name}`\n"
f"*Lastname*: `{database[update['_effective_user']['id']]['last_name']}`\n" f"*Lastname*: `{u.last_name}`\n"
f"*Birth date*: `{database[update['_effective_user']['id']]['birth_date']}`\n" f"*Birth date*: `{u.birth_date}`\n"
f"*Birth city*: `{database[update['_effective_user']['id']]['birth_city']}`\n" f"*Birth city*: `{u.birth_city}`\n"
f"*Address*: `{database[update['_effective_user']['id']]['address']}`\n\n" f"*Address*: `{u.address}`\n\n"
f"Choose the data you want to edit", f"Choose the data you want to edit",
parse_mode=ParseMode.MARKDOWN_V2, parse_mode=ParseMode.MARKDOWN_V2,
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Firstname", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Firstname",

View file

@ -1,11 +1,14 @@
from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton, ParseMode from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton, ParseMode
from telegram.ext import CallbackContext from telegram.ext import CallbackContext
from main import database, reasons import db
from main import reasons
def new(update: Update, context: CallbackContext): def new(update: Update, context: CallbackContext):
if update['_effective_user']['id'] not in database or not all(database[update['_effective_user']['id']].values()): s = db.Session()
u = s.query(db.User).get(update["_effective_user"]["id"])
if not u or not all([u.first_name, u.last_name, u.birth_date, u.birth_city, u.address]):
context.bot.send_message(chat_id=update.effective_chat.id, text="You have no data saved !", context.bot.send_message(chat_id=update.effective_chat.id, text="You have no data saved !",
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Set data", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Set data",
callback_data="data")], callback_data="data")],

View file

@ -1,3 +1,4 @@
{ {
"bot_token": "SUPER_SECRET_TOKEN" "bot_token": "SUPER_SECRET_TOKEN",
"db": "postgresql://usr:pass@localhost:5432/sqlalchemy"
} }

15
db/User.py Normal file
View file

@ -0,0 +1,15 @@
from db import Base
from sqlalchemy import Column, Integer, String, Date
class User(Base):
__tablename__ = "user"
id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
birth_date = Column(Date)
birth_city = Column(String)
address = Column(String)
def __init__(self, id: int):
self.id = id

16
db/__init__.py Normal file
View file

@ -0,0 +1,16 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from bot import config
db = config.get("db")
args = {"pool_pre_ping": True, "pool_recycle": 3600}
if not db.startswith("sqlite:"):
args.update({"pool_size": 0, "max_overflow": -1})
engine = create_engine(db, **args)
Session = sessionmaker(bind=engine)
Base = declarative_base()
from db.User import User
Base.metadata.create_all(engine)

View file

@ -8,7 +8,6 @@ local = {"first_name": "Firstname",
"birth_date": "Birth date", "birth_date": "Birth date",
"birth_city": "Birth city", "birth_city": "Birth city",
"address": "Address"} "address": "Address"}
database = {}
messages = {} messages = {}
reasons = {} reasons = {}

View file

@ -4,9 +4,10 @@ from datetime import datetime
from telegram import Update, ParseMode from telegram import Update, ParseMode
from telegram.ext import CallbackContext from telegram.ext import CallbackContext
import db
from callbackQuery.create import address_re from callbackQuery.create import address_re
from callbackQuery.data import data from callbackQuery.data import data
from main import local, messages, database from main import local, messages
rex = { rex = {
"first_name": re.compile(r"^([a-zA-Z]| )+$"), "first_name": re.compile(r"^([a-zA-Z]| )+$"),
@ -33,6 +34,14 @@ def edit(update: Update, context: CallbackContext, data_edit: str):
context.bot.send_message(chat_id=update.effective_chat.id, text=f"Invalid value for `{local[name]}` \!", context.bot.send_message(chat_id=update.effective_chat.id, text=f"Invalid value for `{local[name]}` \!",
parse_mode=ParseMode.MARKDOWN_V2) parse_mode=ParseMode.MARKDOWN_V2)
else: else:
s = db.Session()
u = s.query(db.User).get(update["_effective_user"]["id"])
del messages[update.effective_chat.id][update["_effective_user"]["id"]] del messages[update.effective_chat.id][update["_effective_user"]["id"]]
database[update["_effective_user"]["id"]][name] = update.message.text if name == "birth_date":
setattr(u, name, datetime.strptime(update.message.text, "%d/%m/%Y").date())
else:
setattr(u, name, update.message.text)
s.add(u)
s.commit()
s.close()
data(update, context) data(update, context)

View file

@ -12,5 +12,6 @@ pytz==2020.4
qrcode==6.1 qrcode==6.1
reportlab==3.5.55 reportlab==3.5.55
six==1.15.0 six==1.15.0
SQLAlchemy==1.3.20
tornado==6.1 tornado==6.1
tzlocal==2.1 tzlocal==2.1