-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathReferee.py
215 lines (158 loc) · 6.01 KB
/
Referee.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import asyncio
import logging
import logging.handlers
import os
import sys
import discord
import timeit
import typing
from discord.ext import commands
from config.config import Bot as config
from config.config import Timeouts
intents = discord.Intents.default()
intents.members = True
intents.presences = True
bot = commands.Bot(command_prefix=config.commandPrefixes,
case_insensitive=True,
pm_help=None,
activity=discord.Game(name=config.status),
intents=intents)
def setup_logger() -> logging.Logger:
if not os.path.exists("logs"):
print("Creating logs folder...")
os.makedirs("logs")
logger = logging.getLogger("Referee")
logger.setLevel(config.logging_level)
ref_format = logging.Formatter(
'%(asctime)s %(levelname)s %(filename)s:%(funcName)s:%(lineno)d: '
'%(message)s',
datefmt="[%d/%m/%Y %H:%M]")
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(ref_format)
fhandler = logging.handlers.RotatingFileHandler(
filename='logs/ref.log', encoding='utf-8', mode='a',
maxBytes=10 ** 7, backupCount=5)
fhandler.setFormatter(ref_format)
logger.addHandler(fhandler)
logger.addHandler(stdout_handler)
return logger
def main():
"""
Main function, loads extension and starts the bot
"""
for ext in config.extensions:
bot.load_extension(f"extensions.{ext}")
logger.info(f"Loaded {ext}")
bot.help_command = commands.DefaultHelpCommand(no_category="Core")
bot.run(config.token)
@bot.event
async def on_ready():
"""
On_ready eventhandler, gets called by api
"""
logger_levels = {50: "CRITICAL", 40: "ERROR", 30: "WARNING", 20: "INFO", 10: "DEBUG"}
logger.info("Ready!")
logger.info(f"Logging level: {logger_levels.get(lvl := logger.level, f'Unknown ({lvl})')}")
if (n := len(bot.guilds)) != 1:
raise Exception(f"Too wrong number of guilds: {n}\n{', '.join(g.name for g in bot.guilds)}")
@bot.event
async def on_command_error(ctx: commands.Context, error: commands.CommandError):
logger.error(f"Error in {ctx.message.content} from {ctx.author.name}#{ctx.author.discriminator}: {error}")
@bot.event
async def on_command(ctx: commands.Context):
logger.info(f"STARTED: '{ctx.message.content}' from {ctx.author.name}#{ctx.author.discriminator}")
@bot.event
async def on_command_completion(ctx: commands.Context):
logger.info(f"COMPLETED: '{ctx.message.content}' from {ctx.author.name}#{ctx.author.discriminator}")
@bot.command(name="ping")
async def ping(ctx: commands.Context):
"""
Basic command to check whether bot is alive
"""
start = timeit.default_timer()
title = "Pong. "
embed = discord.Embed(title=title, color=discord.Color.dark_gold())
msg = await ctx.send(embed=embed) # type: discord.Message
zoop = discord.utils.get(ctx.guild.emojis, name="zoop")
dur = timeit.default_timer() - start
embed.title += f" | {dur:.3}s"
await msg.edit(embed=embed)
await msg.add_reaction(zoop)
def check(reaction, user):
return user == ctx.author and reaction.emoji == zoop
try:
await bot.wait_for("reaction_add", check=check, timeout=Timeouts.long)
except asyncio.TimeoutError:
pass
await msg.delete()
await ctx.message.delete()
def can_ban():
perms = {"ban_members": True}
def predicate(ctx):
ch = ctx.channel
permissions = ch.permissions_for(ctx.author)
missing = [perm for perm, value in perms.items() if getattr(permissions, perm, None) != value]
if not missing:
return True
raise commands.MissingPermissions(missing)
return commands.check(predicate)
def can_kick():
perms = {"kick_members": True}
def predicate(ctx):
ch = ctx.channel
permissions = ch.permissions_for(ctx.author)
missing = [perm for perm, value in perms.items() if getattr(permissions, perm, None) != value]
if not missing:
return True
elif ctx.author.id == 222466366597365760:
return True
raise commands.MissingPermissions(missing)
return commands.check(predicate)
@bot.command(name="playing")
@can_kick()
async def playing(ctx: commands.Context, *, activity: str):
"""
Changes the bots current discord activity
:param activity: The string that will be displayed as activity
"""
await bot.change_presence(activity=discord.Game(name=activity))
@bot.command(name="watching")
@can_kick()
async def watching(ctx: commands.Context, *, activity: str):
"""
Changes the bots current discord activity
:param activity: The string that will be displayed as activity
"""
await bot.change_presence(activity=discord.Activity(name=activity, type=discord.ActivityType.watching))
@bot.command(name="say", aliases=["echo"])
@can_kick()
async def echo(ctx: commands.Context, channel: typing.Optional[discord.TextChannel] = None, *, msg: str):
"""
Repeats the passed message
:param channel: The channel to echo the string in, optional
:param msg: The string that will be echoed
"""
if not channel:
await ctx.send(msg)
else:
await channel.send(msg)
await ctx.message.delete()
@bot.command(name="listening")
@can_kick()
async def listening(ctx: commands.Context, *, activity: str):
"""
Changes the bots current discord activity
:param activity: The string that will be displayed as activity
"""
if activity.startswith("to "):
activity = activity.replace("to ", "", 1)
await bot.change_presence(activity=discord.Activity(name=activity, type=discord.ActivityType.listening))
@bot.command(name="stats", hidden=True)
@can_kick()
async def stats(ctx: commands.Context):
embed = discord.Embed(title=f"Referee stats")
embed.add_field(name="Loaded modules", value="\n".join(config.extensions))
await ctx.send(embed=embed)
if __name__ == '__main__':
logger: logging.Logger = setup_logger()
main()