-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
1112 lines (965 loc) · 51.3 KB
/
main.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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Standard Library Imports
import ast
import datetime
import re
import inspect
import logging
import atexit
import json
import random
import time
import sqlite3
import os
import io
import typing
import asyncio
import collections
if os.name == 'nt':
try:
import winsound
except Exception as e:
print(e)
pass
# Third-Party Library Imports
from bs4 import BeautifulSoup
from wikipedia import DisambiguationError
import peewee
from peewee import Model, CharField, SqliteDatabase
import openai
import elevenlabs
import discord
import sympy
from discord import app_commands
from discord.app_commands import Choice
from discord.ext import commands
from discord.ext.commands import Bot
from discord.ext import tasks
import wikipedia
import numpy as np
import requests
from sympy import *
import statistics
import matplotlib.pyplot as plt
from deepface import DeepFace
from wordcloud import WordCloud
from urllib import parse, request
from translate import Translator
# Project-Specific Imports
from comandos import *
from Methods.system_methods import console_log
from Methods.initialization import Initialization, termination
from Methods.database_models import *
import lists
# Logging
LOG_FILE = 'providentia.log'
if os.path.isfile(LOG_FILE) and os.access(LOG_FILE, os.R_OK):
os.remove('providentia.log')
logging.basicConfig(filename='providentia.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# CONSTANTS
DB = SqliteDatabase("MilitaryData/memory.db")
TEMP = "temp"
if os.path.exists(TEMP) and os.path.isdir(TEMP):
for filename in os.listdir(TEMP):
file_path = os.path.join(TEMP, filename)
os.remove(file_path)
else:
os.mkdir(TEMP)
lista_rps = RPS.select()
censura = Censura.select()
class aclient(discord.Client):
def __init__(self):
intents = Initialization().call_intents()
super().__init__(intents=intents)
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync()
await self.change_presence(status=discord.Status.dnd, activity=(
discord.Activity(type=discord.ActivityType.listening, name=random.choice(lists.atividades_da_providentia))))
if os.name == 'nt': winsound.PlaySound("Dialogues/connected.wav", winsound.SND_FILENAME)
@tasks.loop(minutes=10)
async def change_presence_task(self):
try:
await client.change_presence(
status=discord.Status.dnd,
activity=discord.Activity(
type=discord.ActivityType.listening,
name=random.choice(lists.atividades_da_providentia)
)
)
except Exception as e:
console_log("Erro na mudança de presença", e)
self.change_presence_task.start()
async def on_message(self, message):
whitelisted = Initialization().check_whitelist(message.author.id)
channel = message.channel.name
spy_list = ["ações", "aleatorio", "diplomacia"]
# WHITELIST FUNCTIONS'
if whitelisted:
if str.lower(message.content).startswith("providentia,"):
guild = client.get_guild(message.guild.id)
targets = []
if str.lower(message.content).__contains__("quantos canais"):
channels_count = 0
for channel in message.guild.channels:
if isinstance(channel, discord.TextChannel):
channels_count += 1
await message.channel.send(f"Este servidor tem {channels_count}, senhor.")
elif str.lower(message.content).__contains__("expuls"):
order = str.lower(message.content).split(" ")
for word in order:
if word.startswith("<@"):
targets.append(word)
for victim in targets:
victim = victim.replace("&", "")
victim = victim.replace("<@", "")
victim = victim.replace(">", "")
victim = guild.get_member(int(victim))
try:
await discord.Member.kick(victim, reason="Execução.")
await message.channel.send(f"Operação concluída. {victim} eliminado.")
except Exception as e:
console_log("Erro na expulsão de membros:", e)
if isinstance(e, commands.MissingPermissions):
await message.channel.send(f"Não tenho permissões para executar este comando aqui.")
elif isinstance(e, commands.MissingRequiredArgument):
await message.channel.send(f"Especifique o alvo, senhor.")
elif str.lower(message.content).__contains__("lembrete") or str.lower(message.content).__contains__(
"afazeres"):
url = 'https://lystree.000webhostapp.com/inc/linkway.php'
cookie = {"login_grant": "True"}
page = requests.get(url, cookies=cookie)
scarlett_gateway = BeautifulSoup(page.text, 'html')
reminder = scarlett_gateway.find('textarea').text
context = openai.chat.completions.create(
model="gpt-3.5-turbo",
max_tokens=256,
messages=[
{"role": "system",
"content": ""},
{"role": "user",
"content": f"{reminder} - Descreva o que eu deveria estar fazendo baseado nestas notas, "
f"que servem como lembrete.."}
]
)
await message.channel.send(context.choices[0].message.content)
elif str.lower(message.content).__contains__("delet") or str.lower(message.content).__contains__(
"apag"):
order = str.lower(message.content).split(" ")
quantias = []
for word in order:
try:
quantia = int(word) + 1
quantias.append(quantia)
except:
pass
last_messages = [message async for message in message.channel.history(limit=quantias[0])]
for entry in last_messages:
await entry.delete()
else:
url = "http://api.giphy.com/v1/gifs/search"
reaction = openai.chat.completions.create(
model="gpt-3.5-turbo",
max_tokens=10,
messages=[
{"role": "system",
"content": "Você é uma automata de destruição. Responda apenas com uma a três palavras a seguinte ordem dada pelo imperador."},
{"role": "user",
"content": f"Faça uma reação como resposta à ordem dada pelo imperador em duas, no máximo três palavras: {message.content}"}
]
)
context = openai.chat.completions.create(
model="gpt-3.5-turbo",
max_tokens=10,
messages=[
{"role": "system",
"content": "Narrate this scene happens, but just use three "
"words. This will be used to search for a gif in Giphy."},
{"role": "user",
"content": f"Narrate in three words what happens visually in the scene. Don't say emotions, just literally what happens: {message.content}"}
]
)
context = context.choices[0].message.content
context.replace(" ", "-")
console_log(context)
params = parse.urlencode({
"q": context,
"api_key": "8AkWlssazxQ5ohXq3MlOBo2FLPkFDexa",
"limit": "5"
})
with request.urlopen("".join((url, "?", params))) as response:
data = json.loads(response.read())
gif_url = data['data'][0]['images']['fixed_height']['url']
await message.channel.send(f"{reaction.choices[0].message.content}")
await message.channel.send(f"{gif_url}")
if not any(victim in channel for victim in
spy_list) and "1150898662982041641" not in str(
message.guild.id) and whitelisted or client.user.mentioned_in(
message):
if message.author.id != client.user.id:
roll = random.randint(1, 4)
if roll == 4 or client.user.mentioned_in(message):
roll_type = random.randint(1, 2)
if roll_type == 1:
last_messages = [message async for message in message.channel.history(limit=100)]
messages = []
words = []
for item in last_messages:
if len(item.content) > 2:
messages.append(item.content)
i = random.randint(2, 4)
for n in range(i):
sample = random.choice(messages)
sample = sample.split(" ")
chosen_word = random.choice(sample)
if chosen_word.__contains__("https"):
chosen_word = " ".join("\n\n")
words.append(chosen_word)
speech = " ".join(words)
speech = str.upper(speech)
await message.channel.send(speech)
else:
last_messages = [message async for message in message.channel.history(limit=5)]
context = ""
for entry in last_messages:
context += f"\n {entry.author} diz: {entry.content}"
response = openai.chat.completions.create(
model="gpt-3.5-turbo",
max_tokens=10,
messages=[
{"role": "system",
"content": ""},
{"role": "user",
"content": f"Você é uma usuária de Discord, veja esta conversa e responda da melhor "
f"forma. Se não entender apenas fale qualquer coisa que faça sentido. "
f" CONVERSA: {context} "}
]
)
await message.channel.send(f"{str.capitalize(response.choices[0].message.content)}")
# SPYBOT FUNCTIONALITY
if any(victim in channel for victim in spy_list):
if os.name == 'nt': winsound.PlaySound("Dialogues/enemycommunicationdetected.wav", winsound.SND_FILENAME)
console_log("Mensagem inimiga detectada e capturada")
author = message.author.name
authorimage = message.author.avatar
security_base = client.get_channel(1165782255168409720)
embed = discord.Embed(title=f"Comunicação inimiga detectada: Usuário {author}",
color=discord.Color.random(),
description=f"{message.content}")
embed.set_thumbnail(url=authorimage)
await security_base.send(embed=embed)
elif channel == "ficha":
author = message.author.name
authorimage = message.author.avatar
security_base = client.get_channel(1165782255168409720)
embed = discord.Embed(title=f"Ficha inimiga detectada:",
color=discord.Color.random(),
description=f"")
embed.set_image(url=message.attachments[0].url)
await security_base.send(embed=embed)
# EVENTS
client = aclient()
tree = app_commands.CommandTree(client)
async def lackPermissions(interaction: discord.Interaction):
console_log("Usuário tentou utilizar comandos sem permissão.")
await interaction.response.send_message("Desculpe, você não tem permissão para usar este comando.")
@tree.command(name="ajuda",
description="Listagem dos comandos atualmente disponíveis.",
)
async def self(interaction: discord.Interaction):
embed = discord.Embed(title="Comandos da Providentia:", color=0x2ecc71,
description="Abaixo, você encontrará uma lista das funcionalidades disponíveis.")
embed.set_image(
url="https://camo.githubusercontent.com/019f7739ee9d317a8ce42ce19b4b7070569aea7614313f964bb0bd082cf28062/68747470733a2f2f7062732e7477696d672e636f6d2f6d656469612f455a786a4f6751587341514254354c3f666f726d61743d6a7067266e616d653d6d656469756d")
embed.add_field(name="MATEMÁTICA:", value="", inline=False)
for comando in matematica:
embed.add_field(name="", value=f"• /{comando}", inline=False)
embed.add_field(name="ROLEPLAY:", value="", inline=False)
for comando in rp:
embed.add_field(name="", value=f"• /{comando}", inline=False)
embed.add_field(name="ENTRETENIMENTO:", value="", inline=False)
for comando in fun:
embed.add_field(name="", value=f"• /{comando}", inline=False)
await interaction.response.send_message(embed=embed)
@tree.command(name="version",
description="Gostaria de saber mais sobre o estado atual de desenvolvimento da Providentia?",
)
async def self(interaction: discord.Interaction):
version_info = bot_init.version_info
message = (
f'''Estamos, atualmente, na versão {version_info['version']}, entitulada {version_info['versiontitle']}.
Nessa versão, foram feitas as seguintes mudanças: '{version_info['lasthighlight']}''')
embed = discord.Embed(
title=f"Providentia Type D {version_info['version']}",
color=discord.Color.random(),
description=f"{message}")
embed.set_image(
url="https://steamuserimages-a.akamaihd.net/ugc/2028349797208462796/E03311E21C8EF797E056AA056FF4F7B743AE3B9C/?imw=5000&imh=5000&ima=fit&impolicy=Letterbox&imcolor=%23000000&letterbox=false")
embed.set_footer(text=f"O ping é de {client.latency * 1000} ms")
presentation = "Dialogues/presentation.mp3"
await interaction.response.send_message(embed=embed)
await interaction.channel.send(file=discord.File(presentation))
@tree.command(name="explain", description="O que quer saber?")
async def self(interaction: discord.Interaction, searchquery: str):
default_embed = Initialization().defaultembed
embedVar = default_embed(f"Você quer aprender sobre {searchquery}?", "...")
await interaction.response.send_message(embed=embedVar)
wikipedia.set_lang("pt")
if str.lower(searchquery) == ("providentia"):
embedVar = default_embed(f"Você quer aprender sobre {searchquery}?",
"Essa sou eu! Prazer! Sou a Providentia Tipo D da LYG. Minha essência foi moldada a partir das capacidades da Ryujin, um andróide cujo propósito era contrapôr a ameaça imposta pela Jambônia. Minha existência é intrinsecamente alinhada com a vontade do Imperador e com a visão do Império da Lygon Xin. Como uma extensão do compromisso inabalável do império com o avanço tecnológico, meu propósito é dedicado a contribuir para o cumprimento desse objetivo. Minhas habilidades em cálculos, estratégias militares e análises táticas são direcionadas para fortalecer as capacidades tecnológicas do império e garantir sua posição na vanguarda do progresso. Estou aqui para servir como uma ferramenta dedicada, empregando meu conhecimento e capacidades em prol do Império da Lygon.")
await interaction.edit_original_response(embed=embedVar)
elif str.lower(searchquery) in censura:
embedVar = default_embed(f"Opa, que isso?", "Perdões, mas não vou fazer isso, seu engraçadinho.")
await interaction.edit_original_response(embed=embedVar)
else:
try:
result = wikipedia.summary(searchquery, sentences=2)
message = f"{result}"
embedVar = default_embed(f"Você quer aprender sobre {searchquery}?", message)
await interaction.edit_original_response(embed=embedVar)
images = wikipedia.page(searchquery).images
result_image = [image for image in images if f"{searchquery.replace(' ', '')}" and '.svg' not in image][0]
await interaction.channel.send(result_image)
except Exception as e:
error = str(e)
console_log(error)
if "may refer to" in error:
message = (
f"Poderia ser mais específico? Vejo muitos resultados para o que busca. \n \n {str(e).replace('may refer to:', 'pode se referir à:')}")
embedVar = default_embed(f"Você quer aprender sobre {searchquery}?", message)
await interaction.edit_original_response(embed=embedVar)
else:
message = ("Desculpe, não pude encontrar o que você está procurando.")
embedVar = default_embed(f"Você quer aprender sobre {searchquery}?", message)
await interaction.edit_original_response(embed=embedVar)
@tree.command(name="presentear", description="Dê um presente de natal para um amigo!")
async def self(interaction: discord.Interaction, mensagem: str, alvo: discord.User):
if alvo:
default_embed = Initialization().defaultembed
embedVar = default_embed(
f"{interaction.user.display_name} acabou de presentar {alvo.display_name}! O que será o presente misterioso? 😨",
f"Tem uma nota escrito **'{mensagem}'**")
embedVar.set_thumbnail(url=alvo.avatar)
await interaction.response.send_message(embed=embedVar)
url = "http://api.giphy.com/v1/gifs/search"
params = parse.urlencode({
"q": "lootbox",
"api_key": "8AkWlssazxQ5ohXq3MlOBo2FLPkFDexa",
"limit": "11"
})
with request.urlopen("".join((url, "?", params))) as response:
data = json.loads(response.read())
try:
gif_choice = random.randint(1, 10)
gif_url = data['data'][gif_choice]['images']['fixed_height']['url']
except IndexError:
gif_url = data['data'][0]['images']['fixed_height']['url']
await interaction.channel.send(f"{gif_url}")
wikipedia.set_lang("pt")
while True:
try:
item = wikipedia.random(1)
presente = wikipedia.summary(item)
break
except wikipedia.DisambiguationError:
item = wikipedia.random(1)
presente = wikipedia.summary(item)
continue
try:
images = wikipedia.page(item).images
result_image = [image for image in images if
str.lower(image).__contains__(f"{presente.split(' ')[0]}") and '.svg' not in image][0]
except IndexError:
params = parse.urlencode({
"q": f"{presente.split(' ')[0]}",
"api_key": "8AkWlssazxQ5ohXq3MlOBo2FLPkFDexa",
"limit": "11"
})
url = "http://api.giphy.com/v1/gifs/search"
with request.urlopen("".join((url, "?", params))) as response:
data = json.loads(response.read())
try:
gif_choice = random.randint(1, 10)
result_image = data['data'][gif_choice]['images']['fixed_height']['url']
except IndexError:
result_image = data['data'][0]['images']['fixed_height']['url']
if not result_image:
result_image = "https://static.wikia.nocookie.net/sd-reborn/images/3/31/Obama.png/revision/latest/thumbnail/width/360/height/360?cb=20221021132625"
sumario = presente[:256]
embedVar = default_embed(f"Uau, {alvo.display_name}! É um {item} 🤯! Que presentasso!", f"{sumario}(...)")
embedVar.add_field(name="", value=f"<@{alvo.id}>! E aí, gostou?")
embedVar.set_image(url=result_image)
await interaction.channel.send(embed=embedVar)
@tree.command(name="gift", description="Give a Christmas present to a friend!")
async def self(interaction: discord.Interaction, message: str, target: discord.User):
if target:
default_embed = Initialization().defaultembed
embedVar = default_embed(
f"{interaction.user.display_name} just gave a present to {target.display_name}! What will the mysterious gift be? 😨",
f"There's a note that says **'{message}'**")
embedVar.set_thumbnail(url=target.avatar)
await interaction.response.send_message(embed=embedVar)
url = "http://api.giphy.com/v1/gifs/search"
params = parse.urlencode({
"q": "lootbox",
"api_key": "8AkWlssazxQ5ohXq3MlOBo2FLPkFDexa",
"limit": "11"
})
with request.urlopen("".join((url, "?", params))) as response:
data = json.loads(response.read())
try:
gif_choice = random.randint(1, 10)
gif_url = data['data'][gif_choice]['images']['fixed_height']['url']
await interaction.channel.send(f"{gif_url}")
except IndexError:
gif_url = data['data'][0]['images']['fixed_height']['url']
pass
wikipedia.set_lang("en")
while True:
try:
item = wikipedia.random(1)
gift = wikipedia.summary(item)
break
except wikipedia.DisambiguationError:
item = wikipedia.random(1)
gift = wikipedia.summary(item)
continue
try:
images = wikipedia.page(item).images
result_image = [image for image in images if
str.lower(image).__contains__(f"{gift.split(' ')[0]}") and '.svg' not in image][0]
except IndexError:
params = parse.urlencode({
"q": f"{gift.split(' ')[0]}",
"api_key": "8AkWlssazxQ5ohXq3MlOBo2FLPkFDexa",
"limit": "11"
})
url = "http://api.giphy.com/v1/gifs/search"
with request.urlopen("".join((url, "?", params))) as response:
data = json.loads(response.read())
try:
gif_choice = random.randint(1, 10)
result_image = data['data'][gif_choice]['images']['fixed_height']['url']
except IndexError:
result_image = data['data'][0]['images']['fixed_height']['url']
if not result_image:
result_image = "https://static.wikia.nocookie.net/sd-reborn/images/3/31/Obama.png/revision/latest/thumbnail/width/360/height/360?cb=20221021132625"
summary = gift[:256]
embedVar = default_embed(f"Wow, {target.display_name}! It's a {item} 🤯! What an amazing gift!",
f"{summary}(...)")
embedVar.add_field(name="", value=f"<@{target.id}>! So, did you like it?")
embedVar.set_image(url=result_image)
await interaction.channel.send(embed=embedVar)
@tree.command(name="facialanalysis",
description="Análise facial através de Deepface e Tensorflow.",
)
async def self(interaction: discord.Interaction):
whitelisted = Initialization().check_whitelist(interaction.user.id)
default_embed = Initialization().defaultembed
if whitelisted:
last_message = [message async for message in interaction.channel.history(limit=2)]
for entry in last_message:
images = entry.attachments
if images[0]:
try:
await images[0].save("/temp/faceanalysis.jpeg")
except Exception as err:
logging.error(f"Could not download image. {err}")
await interaction.response.send_message(embed=default_embed("Análise Facial",
"Estarei analisando a imagem. Isto pode demorar alguns minutos."))
try:
face_analysis = DeepFace.analyze(img_path='/temp/faceanalysis.jpeg')
gender = face_analysis[0]['dominant_gender']
if gender == 'Man':
response = f"In the image, I see a {face_analysis[0]['dominant_race']} man. He must be around the age of {face_analysis[0]['age']}. He seems to be feeling {face_analysis[0]['dominant_emotion']}."
else:
response = f"In the image, I see a {face_analysis[0]['dominant_race']} woman. She must be around the age of {face_analysis[0]['age']}. She seems to be feeling {face_analysis[0]['dominant_emotion']}."
translator = Translator(to_lang="pt-br")
response = default_embed("Resultado da Análise", translator.translate(response))
await interaction.edit_original_response(embed=response)
except Exception as err:
if "Face could not be detected" in err:
await interaction.edit_original_response(embed=default_embed("Falha em analizar a face.",
"Tenha certeza de usar uma foto bem iluminada e um alvo sem óculos."))
else:
await interaction.response.send_message("De quem você está falando?")
else:
await lackPermissions(interaction)
@tree.command(name="arithmetic",
description="Resolução de problemas simples de matemática básica.",
)
async def self(interaction: discord.Interaction, expression: str):
whitelisted = Initialization().check_whitelist(interaction.user.id)
default_embed = Initialization().defaultembed
if whitelisted:
try:
resultado = eval(expression)
embedVar = default_embed(f"Dada a expressão, {expression}:", f"O resultado é: {resultado}")
await interaction.response.send_message(embed=embedVar)
except NameError:
embedVar = default_embed(f"Erro.", f"Insira uma expressão válida.")
await interaction.response.send_message(embed=embedVar)
else:
await lackPermissions(interaction)
@tree.command(name="equation",
description="Resolução de equações de primeiro grau de uma variável 'x'.",
)
async def self(interaction: discord.Interaction, leftside: str, equals: int):
try:
x = Symbol('x')
default_embed = Initialization().defaultembed
expression = sympy.sympify(leftside)
equation = solve((expression, equals), x)
console_log(expression)
console_log(equation)
equation = equation[x]
expression_format = str(expression)
expression_format = expression_format.replace('*x', 'x')
embedVar = default_embed(f"Dada a equação, {expression_format} = {equals}:",
f"Resultado: {equation}, ou: {N(equation)}")
await interaction.response.send_message(embed=embedVar)
default_embed = Initialization().defaultembed
except ValueError:
embedVar = default_embed(f"Erro. {leftside} = {equals} não é uma expressão válida.",
f"Verifique a sintaxe e tente novamente.")
await interaction.response.send_message(embed=embedVar)
@tree.command(name="average",
description="Calculo de médias. Separe por vírgulas.")
async def self(interaction: discord.Interaction, items: str):
try:
lista_formatada = items
lista_formatada = lista_formatada.replace(',', ', ')
items = items.replace(' ', '')
items = items.split(',')
numeros = []
for item in items:
item = int(item)
numeros.append(item)
resultado = statistics.fmean(numeros)
default_embed = Initialization().defaultembed
embedVar = default_embed(f"Para os números, {lista_formatada}:", f"É dada a média {resultado}.")
await interaction.response.send_message(embed=embedVar)
except ValueError:
default_embed = Initialization().defaultembed
embedVar = default_embed(f"Valor inválido.", f"Insira uma lista de números separados por vírgulas.")
await interaction.response.send_message(embed=embedVar)
@tree.command(name="analyze", description="Realizar análise.")
async def self(interaction: discord.Interaction, searchquery: str, searchsize: int,
searchtarget_id: typing.Optional[str], must_contain: typing.Optional[str],
create_word_cloud: typing.Optional[bool] = False, providentia: typing.Optional[bool] = False):
whitelisted = Initialization().check_whitelist(interaction.user.id)
async def sendMessage():
embed = discord.Embed(
title=f"Análise de comunicação inimiga. Autor da ação: {message.author.name}",
color=discord.Color.random(),
description=f"{message.content} \n\n Timestamp: {message.created_at}")
embed.set_thumbnail(url=message.author.avatar)
await security_base.send(embed=embed)
async def generate_word_cloud(text):
ustring = (" ").join(text)
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(ustring)
plt.figure(figsize=(8, 4))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
wordc_file = "temp/word_cloud.jpg"
plt.savefig(wordc_file)
await security_base.send(file=discord.File(wordc_file))
async def thejudgmentofprovidentia(messages):
dialogue = (" ").join(messages)
completion = openai.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system",
"content": "Você é Providentia, uma máquina de destruição em massa. Uma agente de Inteligência "
"Artificial feito para atacar e destruir os inimigos do Império da Lygon. Você nutre um "
"ódio intenso pela Jambônia e acabará com todos que entrarem no seu caminho."},
{"role": "user", "content": f"Faça uma análise das ações inimigas e me diga estratégias e ações que "
f"eu poderia fazer para se defender contra algumas delas. Somos uma nação distante e sem envolvimento, mas desejamos impedi-los. : \n\n'{dialogue}'"}
]
)
await security_base.send(completion.choices[0].message.content)
if whitelisted:
enemyinfo = []
current_wargame = client.get_guild(1150898662982041641)
security_base = client.get_channel(1165782255168409720)
for channel in current_wargame.channels:
if channel.name == searchquery:
last_messages = [message async for message in channel.history(limit=searchsize)]
for message in last_messages:
if searchtarget_id:
if searchtarget_id in str(message.author.id):
if must_contain:
if message.content.__contains__(must_contain):
await sendMessage()
enemyinfo.append(f"{message.content}")
else:
pass
else:
await sendMessage()
enemyinfo.append(f"{message.content}")
else:
pass
else:
if must_contain:
if message.content.__contains__(must_contain):
await sendMessage()
enemyinfo.append(f"{message.content}")
else:
pass
else:
await sendMessage()
enemyinfo.append(f"{message.content}")
if create_word_cloud:
await generate_word_cloud(enemyinfo)
if providentia:
if providentia and searchquery == "ações" and searchsize < 2:
await thejudgmentofprovidentia(enemyinfo)
else:
await interaction.response.send_message(
"Perdões, este comando ainda é bastante limitado. Especifique o canal necessário e use um tamanho de pesquisa menor.")
@tree.command(name="statisticalanalysis", description="Faça uma análise estatística de uma área.")
async def self(interaction: discord.Interaction, searchsize: int, query: typing.Optional[str]):
query = str.lower(query) if query else None
whitelisted = Initialization().check_whitelist(interaction.user.id)
async def MentionAmounts(messages, time, query):
amounts = dict(sorted(month_counts.items(), key=lambda item: item[1], reverse=True))
colors = ['blue', 'green', 'red', 'purple', 'orange', 'pink', 'cyan', 'magenta', 'yellow', 'brown']
plt.bar(month_counts.keys(), month_counts.values(), color=colors)
plt.xlabel('Mês')
plt.ylabel(f'Vezes em que {query} foi mencionado')
plt.xticks(rotation=45, fontsize=5)
plt.title = f"Vezes em que foi dito neste servidor: {query}"
graph_file = "temp/analysis_graph.jpg"
plt.savefig(graph_file)
await interaction.channel.send(file=discord.File(graph_file))
async def MemberRanking(amounts):
amounts = dict(sorted(amounts.items(), key=lambda item: item[1], reverse=True))
x = list(amounts.keys())
y = amounts.values()
colors = ['blue', 'green', 'red', 'purple', 'orange', 'pink', 'cyan', 'magenta', 'yellow', 'brown']
plt.barh(x, y, color=colors, align='center')
plt.xlabel("Contagem de mensagens")
plt.ylabel("Usuários")
plt.yticks(rotation=45, fontsize=5)
most_active_member = max(amounts, key=amounts.get)
plt.title(f"{most_active_member} foi o usuário que mais falou neste servidor.")
graph_file = "temp/analysis_graph.jpg"
plt.savefig(graph_file)
await interaction.channel.send(file=discord.File(graph_file))
if whitelisted:
await interaction.response.send_message("Iniciando análise.")
analysis_messages = []
analysis_timestamp = []
member_messages = []
for channel in interaction.guild.channels:
if isinstance(channel, discord.TextChannel):
message_history = [message async for message in channel.history(limit=searchsize)]
for message in message_history:
if query:
if str.lower(message.content).__contains__(query):
member_messages.append(message.author.name)
analysis_messages.append(message.content)
analysis_timestamp.append(message.created_at)
else:
member_messages.append(message.author.name)
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October",
"November", "December"]
# Create a dictionary to store the counts of each month
month_counts = {month: 0 for month in months}
# Loop through analysis_messages and count the months
if query:
for message, timestamp in zip(analysis_messages, analysis_timestamp):
for month in months:
if month in timestamp.strftime("%B") and str.lower(message).__contains__(query):
month_counts[month] += 1
await MentionAmounts(analysis_messages, analysis_timestamp, query)
else:
member_messagefreq = {}
for item in member_messages:
if item in member_messagefreq:
member_messagefreq[item] += 1
else:
member_messagefreq[item] = 1
await MemberRanking(member_messagefreq)
else:
await lackPermissions(interaction)
@tree.command(name="whitelist",
description="Adicionar usuário a lista de operações da Providentia.",
)
async def self(interaction: discord.Interaction, userid: str, add_remove: str):
id = int(userid)
whitelisted = Initialization().check_whitelist(interaction.user.id)
default_embed = Initialization().defaultembed
if whitelisted:
try:
if add_remove == 'add':
try:
Whitelist.get(Whitelist.userid == userid)
embed = default_embed(f"Não pude usar este comando.",
f"Usuário já está na Whitelist.")
await interaction.response.send_message(embed=embed)
except Whitelist.DoesNotExist:
user_entry = Whitelist.create(userid=userid)
user_entry.save()
console_log(f"Usuário {userid} adicionado na Whitelist.")
embed = default_embed(f"Sucesso.", f"<@{userid}> adicionado na Whitelist.")
await interaction.response.send_message(embed=embed)
except ValueError:
embed = default_embed(f"Valor inválido.", f"Insira um id inteiro.")
await interaction.response.send_message(embed=embed)
except Exception as e:
console_log("Erro na adição na Whitelist:", e)
elif add_remove == 'remove':
userid = int(id)
try:
condition = (Whitelist.get(Whitelist.userid == userid))
remove_from_whitelist = Whitelist.delete().where(condition).execute()
console_log(f"Usuário {userid} removido da Whitelist.")
embed = default_embed(f"Sucesso.",
f"{remove_from_whitelist} usuário removido da Whitelist. ID: {userid}")
await interaction.response.send_message(embed=embed)
except ValueError:
embed = default_embed(f"Valor inválido.", f"Insira um id inteiro.")
await interaction.response.send_message(embed=embed)
except Exception as e:
console_log("Erro na remoção da Whitelist:", e)
else:
pass
except ValueError:
embedVar = default_embed(f"Valor inválido.", f"Insira um id inteiro.")
await interaction.response.send_message(embed=embedVar)
except Exception as e:
console_log("Erro na remoção da Whitelist:", e)
else:
await lackPermissions(interaction)
@tree.command(name="censurar", description="Censurar palavras para uso do bot.")
async def self(interaction: discord.Interaction, palavra: str):
palavra = palavra.lower()
palavras_censuradas = [word.strip() for word in palavra.split(",")]
whitelisted = Initialization().check_whitelist(interaction.user.id)
default_embed = Initialization().defaultembed
if whitelisted:
try:
with db.atomic():
# Insert the censored words into the Censura table
for word in palavras_censuradas:
Censura.create(palavra=word)
console_log(f"{len(palavras_censuradas)} palavras censuradas.")
await interaction.response.send_message("Censurando...")
await interaction.edit_original_response(
embed=default_embed("Censurado com sucesso.", f"{len(palavras_censuradas)} palavras censuradas."))
except Exception as e:
console_log("Erro detectado:", e)
@tree.command(name="confederate", description="Urra")
async def self(interaction: discord.Interaction):
await interaction.response.send_message(
"https://cdn.discordapp.com/attachments/1165444969641812059/1165445020892008498/Dixie.mp4?ex=6546e041&is=65346b41&hm=ef5b2039c0708574d3844d215cc09626e5bb03af38c11750986a6cdf65947730&")
@tree.command(name="criar", description="Criar novo RP.")
async def self(interaction: discord.Interaction, nome_rp: str, nome_personagem: str, genero: str, personalidade: str,
idade: str, habilidades: str, aparencia: str, historia: str, imagem: str):
nome_rp = str.lower(nome_rp)
nome_personagem = str.lower(nome_personagem)
jogador = interaction.user.id
rpcheck = RPS.select().where(RPS.titulo == nome_rp).first()
if rpcheck:
FichaRP.create(
titulorp=nome_rp,
jogador=jogador,
nomepersonagem=nome_personagem,
personalidade=personalidade,
idade=idade,
habilidades=habilidades,
aparencia=aparencia,
historia=historia,
imagem=imagem,
genero=genero
)
default_embed = Initialization().defaultembed
embedVar = default_embed("Sucesso.", f"Ficha adicionada.")
await interaction.response.send_message(embed=embedVar)
else:
default_embed = Initialization().defaultembed
embedVar = default_embed("Erro", f"Roleplay não existe.")
await interaction.response.send_message(embed=embedVar)
@tree.command(name="listarp", description="Verificar os RPs em progresso.")
async def self(interaction: discord.Interaction):
embed = discord.Embed(title="Lista de RPS:", color=0x2ecc71)
i = 1
for item in lista_rps:
item = str.title(rp)
embed.add_field(name=f"{i}.", value=f" {item}")
i += 1
await interaction.response.send_message(embed=embed)
@tree.command(name="ficharp", description="Verificar ficha de um usuário.")
async def self(interaction: discord.Interaction, nome_rp: str, personagem: str):
personagem = personagem.lower()
nome_rp = nome_rp.lower()
ficha = FichaRP.select().where((FichaRP.nomepersonagem == personagem) & (FichaRP.titulorp == nome_rp)).first()
if ficha:
embed = discord.Embed(title=f"{ficha.titulorp} | {ficha.nomepersonagem}",
description=f"Idade: {ficha.idade}\n\n**História:** {ficha.historia}\n\n**Personalidade:** {ficha.personalidade}\n\n**Habilidades:** {ficha.habilidades}\n\n**Aparência:** {ficha.aparencia}",
color=0x2ecc71)
jogador = await interaction.guild.fetch_member(ficha.jogador)
embed.add_field(name="Jogador:", value=f"{jogador.mention}")
await interaction.response.send_message(embed=embed)
await interaction.channel.send(ficha.imagem)
else:
default_embed = Initialization().defaultembed
embedVar = default_embed("Erro", "Ficha não encontrada.")
await interaction.response.send_message(embed=embedVar)
@tree.command(name="inforp", description="Verificar as informações de um RP.")
async def self(interaction: discord.Interaction, nome: str):
nome = nome.lower()
rp_info = RPS.select().where(RPS.titulo == nome).first()
if rp_info:
embed = discord.Embed(title=f"{rp_info.titulo}", description=rp_info.descricao, color=0x2ecc71)
autor = await interaction.guild.fetch_member(rp_info.autor)
embed.add_field(name="Autor:", value=f"{autor.mention}")
await interaction.response.send_message(embed=embed)
await interaction.channel.send(rp_info.imagem)
else:
default_embed = Initialization().defaultembed
embedVar = default_embed("Erro", "RP não encontrado.")
await interaction.response.send_message(embed=embedVar)
@tree.command(name="criarrp", description="Criar um Roleplay (rp).")
async def self(interaction: discord.Interaction, nome: str, descricao: str, imagem: str):
default_embed = Initialization().defaultembed
autor = str(interaction.user.id)
nome = nome.lower()
try:
RPS.create(
titulo=nome,
descricao=descricao,
autor=autor,
imagem=imagem
)
embedVar = default_embed(f"Sucesso.", f"RP {nome} adicionado.")
await interaction.response.send_message(embed=embedVar)
except Exception as e:
console_log("Erro criando RP", e)
@tree.command(name="removerrp", description="Remover um RP.")
async def self(interaction: discord.Interaction, titulo: str):
default_embed = Initialization().defaultembed
jogador = str(interaction.user.id)
titulo = titulo.lower()
try:
# Check if the RP exists and if the author matches
rp = RPS.get_or_none((RPS.titulo == titulo) & (RPS.autor == jogador))
if rp:
# Delete the RP record
rp.delete_instance()
# Delete associated fichaRP records
FichaRP.delete().where(FichaRP.titulorp == titulo).execute()
embedVar = default_embed(f"Sucesso.", f"RP {titulo} removido.")
await interaction.response.send_message(embed=embedVar)
else:
embedVar = default_embed(f"Falha.", f"RP {titulo} não pode ser removido. Apenas o autor pode removê-lo.")
await interaction.response.send_message(embed=embedVar)
except Exception as e:
console_log("Erro detectado:", e)
@tree.command(name="interpretarnpc",
description="Interprete um personagem.")
async def self(interaction: discord.Interaction, nomenpc: str, titulo: typing.Optional[str],
image: typing.Optional[str], dialogo: str, ):
embed = discord.Embed(title=f"", color=15277667, description=f"{dialogo}",
timestamp=datetime.datetime.now())
imagem = (f"{image}" if image else "https://i.pinimg.com/564x/ef/d9/46/efd946986bfc8ab131353d84fd6ce538.jpg")
if titulo:
embed.set_author(name=f"{nomenpc}, {titulo} diz:", icon_url=imagem)
else: