-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathdecorators.py
65 lines (58 loc) · 2.05 KB
/
decorators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def command_handler(function):
"""
Decorator for command handlers. Replies with the return value of
the command function
"""
def wrapper(bot, update, args):
message = function(bot, update, args)
if message:
bot.reply(update, message, parse_mode='html')
return wrapper
def restrict(function):
"""
Decorator that restricts the usage of the function to admin users
"""
def wrapper(bot, update, args):
if update.message.from_user.id not in bot.admin_users:
bot.reply(update, 'Non fare il furbo ;)')
return
return function(bot, update, args)
return wrapper
def restrict_to_chat(func):
"""
Decorator that restrict the usage of the function in a specific channel
"""
def wrapper(bot, update, args):
if bot.casino_channel and update.message.chat_id != bot.casino_channel:
bot.reply(
update, 'Non puoi usare quel comando in questa chat.')
return
return func(bot, update, args)
return wrapper
def args(*types):
"""
Check the passed arguments to see if they match the signature.
Types is an array that can contains the standard types
(e.g. int, float, string) plus the specific "types":
- name: an username starting with '@'
"""
def check_args(f):
def checked_args_f(bot, update, args):
# Check number of arguments
if len(args) < len(types):
bot.reply(update, 'Manca qualche parametro!')
return
# Check type
converted_args = []
for (a, t) in zip(args, types):
try:
converted_args.append(t(a))
except ValueError:
bot.reply(update, 'Hai sbagliato qualcosa')
break
else:
# add remaining unchecked/unconverted args
args[:len(converted_args)] = converted_args
return f(bot, update, args)
return checked_args_f
return check_args