Fakultas Ilmu Komputer UI

Commit cf745d3a authored by zakiraihan's avatar zakiraihan
Browse files

Adding function to save user contact

parent c0e5c58a
from flask import Flask, request
from navigation.navigation import botNavigation
import telegram
import os
import telegram
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
global bot
global TOKEN
......@@ -12,9 +12,12 @@ URL = os.environ.get('URL')
app = Flask(__name__)
app.config.from_object(os.environ.get('APP_SETTINGS'))
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
@app.route('/{}'.format(TOKEN), methods=['POST'])
def respond():
from navigation.navigation import botNavigation
# retrieve the message in JSON and then transform it to Telegram object
update = telegram.Update.de_json(request.get_json(force=True), bot)
botNavigation(bot, update)
......
import os
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from models import UserModel
from app import app, db
app.config.from_object(os.environ['APP_SETTINGS'])
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
\ No newline at end of file
Generic single-database configuration.
\ No newline at end of file
# A generic, single database configuration.
[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
from __future__ import with_statement
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
import logging
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from flask import current_app
config.set_main_option('sqlalchemy.url',
current_app.config.get('SQLALCHEMY_DATABASE_URI'))
target_metadata = current_app.extensions['migrate'].db.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(url=url)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.readthedocs.org/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')
engine = engine_from_config(config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
connection = engine.connect()
context.configure(connection=connection,
target_metadata=target_metadata,
process_revision_directives=process_revision_directives,
**current_app.extensions['migrate'].configure_args)
try:
with context.begin_transaction():
context.run_migrations()
finally:
connection.close()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision}
Create Date: ${create_date}
"""
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}
"""empty message
Revision ID: 091749de5cb7
Revises: None
Create Date: 2019-09-26 19:19:15.875369
"""
# revision identifiers, used by Alembic.
revision = '091749de5cb7'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('userId', sa.String(), nullable=False),
sa.Column('phoneNumber', sa.String(), nullable=False),
sa.Column('firstName', sa.String(), nullable=True),
sa.Column('lastName', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('phoneNumber'),
sa.UniqueConstraint('userId')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('user')
# ### end Alembic commands ###
from app import db
from sqlalchemy.dialects.postgresql import JSON
class UserModel(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
userId = db.Column(db.String(), unique=True, nullable=False)
phoneNumber = db.Column(db.String(), unique=True, nullable=False)
firstName = db.Column(db.String())
lastName = db.Column(db.String())
def __init__(self, userId, phoneNumber, firstName, lastName):
self.userId = userId
self.phoneNumber = phoneNumber
self.firstName = firstName
self.lastName = lastName
def save(self):
db.session.add(self)
db.session.commit()
def delete(self):
db.session.delete(self)
db.session.commit()
def __repr__(self):
return '<id {}>'.format(self.id)
\ No newline at end of file
......@@ -3,13 +3,18 @@ from telebot.mastermind import *
def botNavigation(bot, update):
chat_id = update.message.chat.id
msg_id = update.message.message_id
contact = update.message.contact if update.message.contact != None else None
# Telegram understands UTF-8, so encode text for unicode compatibility
text = update.message.text.encode('utf-8').decode()
text = update.message.text.encode('utf-8').decode() if update.message.text != None else None
if (text == "ahoyy"):
basic_response(bot, chat_id)
elif (text == "/about"):
about_response(bot, chat_id)
elif (text == "/login"):
user_login(bot, chat_id)
elif (text == None and contact != None) :
save_user_data(bot, chat_id, contact)
else :
command_not_found(bot, chat_id, msg_id)
\ No newline at end of file
alembic==1.2.0
asn1crypto==0.24.0
certifi==2019.9.11
cffi==1.12.3
......@@ -5,15 +6,24 @@ chardet==3.0.4
Click==7.0
cryptography==2.7
Flask==1.1.1
Flask-Migrate==1.8.0
Flask-Script==2.0.6
Flask-SQLAlchemy==2.1
future==0.17.1
gunicorn==19.9.0
idna==2.8
itsdangerous==1.1.0
Jinja2==2.10.1
Mako==1.1.0
MarkupSafe==1.1.1
psycopg2==2.8.3
pycparser==2.19
python-dateutil==2.8.0
python-editor==1.0.4
python-telegram-bot==12.1.1
requests==2.22.0
six==1.12.0
SQLAlchemy==1.3.8
tornado==6.0.3
urllib3==1.25.6
urllib3==1.25.5
Werkzeug==0.16.0
from models.UserModel import UserModel
from telegram import KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove
def basic_response(bot, chat_id):
response = "You just inserting the correct command: ahoyy"
bot.sendMessage(chat_id=chat_id, text=response)
......@@ -6,6 +9,28 @@ def about_response(bot, chat_id):
response = "This is a notification bot for any information system in Fasilkom UI"
bot.sendMessage(chat_id=chat_id, text=response)
def command_not_found(bot, chat_id):
def command_not_found(bot, chat_id, msg_id):
response = "Sorry your command is not in bot"
bot.sendMessage(chat_id=chat_id, text=response, reply_to_message_id=msg_id)
\ No newline at end of file
bot.sendMessage(chat_id=chat_id, text=response, reply_to_message_id=msg_id)
def user_login(bot, chat_id):
checkUserExistance = UserModel.query.filter(UserModel.userId==str(chat_id)).first()
if (checkUserExistance is None):
con_keyboard = KeyboardButton(text="Send_contact", request_contact=True)
custom_keyboard = [[ con_keyboard ], [ ]]
reply_markup = ReplyKeyboardMarkup(custom_keyboard, one_time_keyboard=True )
bot.sendMessage(chat_id=chat_id,
text="Would you mind sharing your contact with me?",
reply_markup=reply_markup)
else:
bot.sendMessage(chat_id=chat_id, text="You have been registered", reply_markup=ReplyKeyboardRemove())
def save_user_data(bot, chat_id, contact):
checkUserExistance = UserModel.query.filter(UserModel.userId==str(contact.user_id), UserModel.phoneNumber==str(contact.phone_number)).first()
if (checkUserExistance is None):
user = UserModel(str(contact.user_id), str(contact.phone_number), contact.first_name, contact.last_name)
user.save()
bot.sendMessage(chat_id=chat_id, text="Register success!!!", reply_markup=ReplyKeyboardRemove())
else:
bot.sendMessage(chat_id=chat_id, text="You have been registered", reply_markup=ReplyKeyboardRemove())
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment