Skip to content

Instantly share code, notes, and snippets.

@voider1
Last active April 23, 2017 22:04
Show Gist options
  • Save voider1/761b4cdaee7b05a76e7218bd8af1b261 to your computer and use it in GitHub Desktop.
Save voider1/761b4cdaee7b05a76e7218bd8af1b261 to your computer and use it in GitHub Desktop.
import os
from functools import wraps
from sqlalchemy import create_engine, Column, Integer, String
from sqlalcheny.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
def is_admin(func):
"""Checks wether the user who issues the command is the admin.
Use this if there's supposed to be one, and only one admin."""
@wraps(func)
def inner(*args, **kwargs):
try:
update = args[1]
except IndexError:
err_msg = "Not enough arguments were provided, did you apply this to \
the right function?"
raise TypeError(err_msg)
user = update.message.from_user
# Define your admin_id somewhere!
if user.id == admin_id:
return func(*args, **kwargs)
msg = "This user is not authorized."
try:
update.message.reply_text(msg)
except AttributeError:
err_msg = "You should only use the is_started decorator on a bot \
function!"
raise AttributeError(err_msg)
return inner
###################################################
# If you want to have more than one admin, read further!
# Setting up SQLAlchemy
engine = create_engine("db path here")
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class Admin(Base):
__tablename__ = "admins"
id = Column(Integer, primary_key=True)
uid = Column(Integer, unique=True, nullable=False)
@staticmethod
def exists(uid):
if session.query(Admin).filter_by(uid=uid).first():
return True
return False
def is_admin(func):
"""Checks wether the user who issues the command is an admin.
Use this if there's supposed to more than one admin."""
@wraps(func)
def inner(*args, **kwargs):
try:
update = args[1]
except IndexError:
err_msg = "Not enough arguments were provided, did you apply this to \
the right function?"
raise TypeError(err_msg)
user = update.message.from_user
if Admin.exists(user.id):
return func(*args, **kwargs)
msg = "This user is not authorized."
try:
update.message.reply_text(msg)
except AttributeError:
err_msg = "You should only use the is_started decorator on a bot \
function!"
raise AttributeError(err_msg)
return inner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment