-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
445 lines (399 loc) · 15.2 KB
/
bot.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
import discord
from discord.ext import commands
import asyncio
import random
import os
import time
import datetime
import json
import requests
import pytz
import psutil
import math
import re
from colorama import init, Fore, Style
#Initialize colorama
init()
game_active = False
R = None
score = 0
prefix = "n!"
def factorial(n):
return math.factorial(n)
def log(base, x):
return math.log(x, base)
custom_namespace = {"factorial": factorial, "log": log, "sqrt": math.sqrt, "pow": math.pow}
class Response():
text = ""
text_og = ""
def __init__(self, text):
self.text = add_spaces_before_and_after_operators(text)
self.text_og = add_spaces_before_and_after_operators(text)
self.calculate()
def __str__(self):
return str(self.text)
def calculate(self):
self.text = custom_eval(self.text)
self.text = eval(self.text, custom_namespace)
def __eq__(self, other):
return float(self.text) == float(other)
def validity(self, rules_must, rules_cant):
for char in rules_must:
if char not in self.text_og:
return False
if char == "+":
if self.text_og.count("+") < 1:
return False
if char == "-":
if self.text_og.count("-") < 1:
return False
if char == "*":
if self.text_og.count("*") < 1:
return False
if char == "/":
if self.text_og.count("/") < 1:
return False
if char == "^":
if self.text_og.count("^") < 1:
return False
if char == "sqrt":
if self.text_og.count("sqrt") < 1:
return False
if char == "log":
if self.text_og.count("log") < 1:
return False
if char == "!":
if self.text_og.count("!") < 1:
return False
for char in rules_cant:
if char in self.text_og:
return False
if char == "+":
if self.text_og.count("+") > 0:
return False
if char == "-":
if self.text_og.count("-") > 0:
return False
if char == "*":
if self.text_og.count("*") > 0:
return False
if char == "/":
if self.text_og.count("/") > 0:
return False
if char == "^":
if self.text_og.count("^") > 0:
return False
if char == "sqrt":
if self.text_og.count("sqrt") > 0:
return False
if char == "log":
if self.text_og.count("log") > 0:
return False
if char == "!":
if self.text_og.count("!") > 0:
return False
#Check for non-numerical values around operators of *, +, /, -
for i in range(len(list(str(self.text_og)))):
if str(self.text_og)[i] in ["*", "+", "/", "-"]:
if i == len(list(str(self.text_og)))-1:
return False
if (not str(self.text_og)[i-1].isdigit() and not str(self.text_og)[i-1]==" ") or (not str(self.text_og)[i+1].isdigit() and not str(self.text_og)[i+1]==" "):
return False
#Check for multiplications with 1 and additions with 0 and 0!, 1!, 1^x, x^1
for i in range(len(list(str(self.text_og))) - 1):
if str(self.text_og)[i] == "*":
if str(self.text_og)[i+1] == "1":
return False
if str(self.text_og)[i-1] == "1":
return False
if str(self.text_og)[i] == "+":
if str(self.text_og)[i+1] == "0":
return False
if str(self.text_og)[i-1] == "0":
return False
if str(self.text_og)[i] == "/":
if str(self.text_og)[i+1] == "1":
return False
if str(self.text_og)[i-1] == "1":
return False
if str(self.text_og)[i] == "-":
if str(self.text_og)[i+1] == "0":
return False
if str(self.text_og)[i-1] == "0":
return False
if str(self.text_og)[i] == "^":
if str(self.text_og)[i+1] == "1":
return False
if str(self.text_og)[i-1] == "1":
return False
if str(self.text_og)[i] == "!":
if str(self.text_og)[i-1] == "1" or str(self.text_og)[i-1] == "0":
return False
return True
class Request():
value = 0
request_text = ""
args = []
args_must = []
args_cant = []
difficulty = ""
def __init__(self, args, args_must, args_cant):
self.value = args[0]
self.args = args
self.args_must = args_must
self.args_cant = args_cant
self.produce(args)
if "log" in args_must and ("+" in args_cant or "-" in args_cant):
self.difficulty = "Hard"
elif "sqrt" in args_must and ("+" in args_cant or "-" in args_cant):
self.difficulty = "Medium"
elif "!" in args_must:
self.difficulty = "Medium"
else:
self.difficulty = "Easy"
def produce(self, args):
#Produce request text
self.request_text = produce_r_text(args)
def __str__(self):
return str(self.request_text)
def __eq__(self, other):
return self.value == other
def get_args_must(self):
return self.args_must
def get_args_cant(self):
return self.args_cant
def new_request(args):
return Request(args[0], args[1], args[2])
def produce_r_text(args):
value = args[0]
text = []
text.append("You must produce the value: **" + str(value) + "** with the following operators:" + "\n")
for i in range(1, len(args)):
if args[i] == "1":
text.append("You must use:")
elif args[i] == "0":
text.append("\n")
text.append("You can't use:")
elif args[i] == "-":
text.append("subtraction")
elif args[i] == "+":
text.append("addition")
elif args[i] == "*":
text.append("multiplication")
elif args[i] == "/":
text.append("division")
elif args[i] == "^":
text.append("exponentiation")
elif args[i] == "sqrt":
text.append("square root")
elif args[i] == "log":
text.append("logarithm")
elif args[i] == "!":
text.append("factorial")
else:
text.append("unknown operator")
text = " ".join(text)
return text
def new_args():
all_operators = ["-", "+", "*", "/", "^", "sqrt", "log", "!"]
args = []
args.append(random.randint(1, 500))
args.append("1")
current_time = datetime.datetime.now().time()
seed_1 = math.floor(0.1 * current_time.hour + 0.1 * current_time.minute + 0.7 * current_time.second + 0.1 * current_time.microsecond) % len(all_operators)
args_must = []
current_time = datetime.datetime.now().time()
seed_2 = math.floor(0.1 * current_time.hour + 0.1 * current_time.minute + 0.1 * current_time.second + 0.7 * current_time.microsecond) % len(all_operators)
if seed_1 == seed_2:
seed_2 = (seed_2 + 1) % len(all_operators)
args_cant = []
args.append(all_operators[seed_1])
args.append("0")
args.append(all_operators[seed_2])
args_must.append(all_operators[seed_1])
args_cant.append(all_operators[seed_2])
return args, args_must, args_cant
def main():
"""#Load config
with open("config.json") as f:
try:
config = json.load(f)
except:
print("Error loading config.json")
config = {}
#Load prefix
with open("prefix.txt") as f:
try:
prefix = f.read()
except:
prefix = ""
print("Error loading prefix.txt")
"""
#Load token
with open("token.txt") as f:
try:
token = f.read()
except:
print("Error loading token.txt")
token = ""
#Load bot
intents = discord.Intents.default()
intents.messages = True
bot = commands.Bot(command_prefix="n!", intents=discord.Intents.all())
#Load cogs
bot.load_extension("cogs.ping")
bot.load_extension("cogs.help")
bot.load_extension("cogs.info")
bot.load_extension("cogs.math")
bot.load_extension("cogs.misc")
#Load commands
bot.load_extension("cogs.commands")
#Load events
bot.load_extension("cogs.events")
#Load responses
bot.load_extension("cogs.responses")
#Load requests
bot.load_extension("cogs.requests")
#Load other
bot.load_extension("cogs.other")
emoji1 = ""
emoji2 = ""
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
guild = bot.guilds[0]
all_channels = guild.channels
emoji1 = discord.utils.get(guild.emojis, name="white_check_mark")
emoji2 = discord.utils.get(guild.emojis, name="no")
if emoji1 == None:
emoji1 = "✅"
bot.remove_command('help')
@bot.command()
async def help(ctx):
global game_active, R, score, prefix
await ctx.send("Use n!start to start a new game and n!stop to end the game")
bot.remove_command('start')
@bot.command()
async def start(ctx):
global game_active, R, score, prefix
if game_active == False:
await ctx.send("Started a new game!")
game_active = True
R = new_request(new_args())
await ctx.send(remove_fore(str(R)))
else:
await ctx.send("Game is already active!")
bot.remove_command('stop')
@bot.command()
async def stop(ctx):
global game_active, R, score, prefix
if game_active == True:
await ctx.send("Stopped the game!")
game_active = False
else:
await ctx.send("There is no active game!")
bot.remove_command('score')
@bot.command()
async def score(ctx):
global game_active, R, score, prefix
await ctx.send("Current Score : " + str(score))
@bot.event
async def on_message(message):
global game_active, R, score, prefix
print(message.content)
if message.content.startswith("n!score"):
await bot.process_commands(message)
return
if message.content.startswith("n!stop"):
await bot.process_commands(message)
return
if message.content.startswith("n!help"):
await bot.process_commands(message)
return
if game_active:
#Check if message is a response
ch = message.channel
RES = Response(reduce_space(message.content))
if RES.validity(R.get_args_must(), R.get_args_cant()) and math.ceil(float(str(RES))) == math.ceil(float(str(R.value))):
await ch.send("Correct!")
score += 1
for x in bot.emojis:
if x.name == 'mugshot':
await message.add_reaction(x)
elif RES.validity(R.get_args_must(), R.get_args_cant()):
await ch.send("Incorrect!")
score -= 1
for x in bot.emojis:
if x.name == 'no':
await message.add_reaction(x)
else:
await ch.send("Invalid!")
score -= 1
for x in bot.emojis:
if x.name == 'no':
await message.add_reaction(x)
R = new_request(new_args())
await ch.send(remove_fore(str(R)))
await bot.process_commands(message)
#Run bot
bot.run(token)
def test():
for i in range(100):
print(Fore.LIGHTYELLOW_EX + "=================================================")
R = new_request(new_args())
print(Fore.WHITE + str(R) + "\n")
print(Fore.WHITE + "Difficulty: " + Fore.YELLOW + R.difficulty + "\n")
RES = Response(reduce_space(input(Fore.WHITE + "Your response: ")))
print("Equals to " + Fore.YELLOW + str(RES) + "\n")
print(Fore.WHITE + "Expected: " + Fore.YELLOW + str(R.value) + "\n")
if RES.validity(R.get_args_must(), R.get_args_cant()) and math.ceil(float(str(RES))) == math.ceil(float(str(R.value))):
print(Fore.GREEN + "Correct!" + "\n")
elif not RES.validity(R.get_args_must(), R.get_args_cant()):
print(Fore.RED + "Invalid! The rules are violated." + "\n")
else:
print(Fore.RED + "Incorrect!" + "\n")
def custom_eval(expression):
# Split the expression by spaces
parts = expression.split()
# Iterate through parts and replace factorial expressions
for i in range(len(parts)):
if "!" in parts[i]:
# Extract the number before the factorial symbol
num = parts[i].split("!")[0]
# Replace the factorial expression with a function call
parts[i] = parts[i].replace(num + "!", "factorial(" + num + ")")
for i in range(len(parts)-1):
if "^" in parts[i]:
# Extract the number before the power symbol
num = parts[i].split("^")[0]
# Extract the number after the power symbol
power = parts[i].split("^")[1]
# Replace the power expression with a function call
parts[i] = parts[i].replace(num + "^" + power, "pow(" + num + "," + power + ")")
# Join the modified parts back into a single expression string
modified_expression = " ".join(parts)
return modified_expression
def reduce_space(expression):
exp = list(expression)
for i in range(len(expression)-1):
if exp[i] == " " and exp[i+1] == " ":
exp[i+1] = ""
return "".join(exp)
def add_spaces_before_and_after_operators(expression):
#Find "+", "-", "*", "/" operators and add " " around them if this doesn't already exist
exp = list(expression)
for i in range(len(expression)-1):
if exp[i] == "+" or exp[i] == "-" or exp[i] == "*" or exp[i] == "/":
if exp[i-1]!= " " and exp[i+1]!= " ":
exp[i] = " " + exp[i] + " "
elif exp[i-1] == " " and exp[i+1]!= " ":
exp[i] = exp[i] + " "
elif exp[i-1]!= " " and exp[i+1] == " ":
exp[i] = " " + exp[i]
return "".join(exp)
def remove_fore(expression):
pattern = r'Fore\.[^\s]+'
# Use re.sub() to replace all occurrences of "Fore...." with an empty string
result = re.sub(pattern, '', expression)
return result
main()