-
Notifications
You must be signed in to change notification settings - Fork 0
/
func_prefix.py
76 lines (65 loc) · 2.61 KB
/
func_prefix.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
66
67
68
69
70
71
72
73
74
75
76
from discord.ext import tasks
import aioredis
from functions import func_database
import bot_settings
CACHE = None
class Prefix:
def __init__(self):
global CACHE
self.udb = func_database.UserDatabase()
self.sdb = func_database.ServerDatabase()
self.cache = CACHE
async def create_cache(self):
self.cache = await aioredis.create_redis_pool(bot_settings.redis_settings["url"], db=1)
await self.cache.expire("server_prefix", 360)
await self.cache.expire("user_prefix", 360)
return
@tasks.loop(seconds=361)
async def set_expire(self):
await self.cache.expire("server_prefix", 360)
await self.cache.expire("user_prefix", 360)
async def get_prefix(self, user_id, server_id) -> list:
# create cache
if not self.cache:
await self.create_cache()
prefix = [*bot_settings.prefix]
# handle server prefix
server_prefix = await self.cache.hget("server_prefix", server_id, encoding="utf-8")
if server_prefix is None:
server_prefix = await self.sdb.get_server_information(server_id).distinct("prefix")
server_prefix = server_prefix[0] if server_prefix else 0
await self.cache.hset("server_prefix", server_id, server_prefix)
if server_prefix != 0:
prefix.append(server_prefix)
# handle user prefix
user_prefix = await self.cache.hget("user_prefix", server_id, encoding="utf-8")
if user_prefix is None:
user_prefix = await self.udb.get_user_information_global(user_id).distinct("prefix")
user_prefix = user_prefix[0] if user_prefix else 0
await self.cache.hset("user_prefix", user_id, user_prefix)
if user_prefix != 0:
prefix.append(user_prefix)
return prefix
async def set_prefix_user(self, user_id: int, prefix: str):
# create the cache
if not self.cache:
await self.create_cache()
# set it in the cache
await self.cache.hset("user_prefix", user_id, prefix)
await self.udb.set_setting_global(
user_id=user_id,
query={"$set": {"prefix": prefix}}
)
return
async def set_prefix_server(self, server_id: int, prefix: str):
# create the cache
if not self.cache:
await self.create_cache()
# set it in the cache
await self.cache.hset("user_prefix", server_id, prefix)
# set it in the database
await self.sdb.set_setting(
server_id=server_id,
query={"$set": {"prefix": prefix}}
)
return