-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
1181 lines (1091 loc) · 49.5 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>DISCORD-PY_BOT</title>
<!-- Font Awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Bootstrap core CSS -->
<link href="./css/bootstrap.min.css" rel="stylesheet">
<!-- Material Design Bootstrap -->
<link href="./css/mdb.min.css" rel="stylesheet">
<!-- Your custom styles (optional) -->
<link href="./css/style.min.css" rel="stylesheet">
<link href="./css/meu.css" rel="stylesheet">
<link rel="shortcut icon" href="./images/icons/py.png" type="image/x-png">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github.min.css">
<script src="./js/script.js" defer></script>
</head>
<body>
<header>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
crossorigin="anonymous"></script>
<nav class="navbar navbar-custom fixed navbar-expand-lg">
<a class="navbar-brand waves-effect" target="_blank">
<strong class="glitch" style="font-size:20px;font-weight: lighter;color: #0CFFE1;">
[DISCORD-PY_BOT]
</strong>
</a>
</nav>
</header>
<div id="banner">
<center>
<div class="flip-card">
<div class="flip-card-inner">
<div class="flip-card-front">
<img src="https://avatars.githubusercontent.com/u/68911216?v=4">
</div>
<div class="flip-card-back">
<a href="https://github.com/AX414">
<img title="Clique para acessar meu github!"
src="https://i.pinimg.com/736x/b5/1b/78/b51b78ecc9e5711274931774e433b5e6.jpg">
</a>
</div>
</div>
</div>
<br>
<h3 class="card-title text-center glitch" style="color: #0CFFE1;">
<strong id="titulo_banner" class="textoAnimacao" onload="typeWriter()">
Como desenvolver um Bot do Discord com o uso de Python?
</strong>
</h3>
<center>
</div>
<div id="conteudo" class="mt-5 pt-5">
<div id="cartao1">
<h4 class="card-title text-center">Apresentação</h4>
<p class="card-text">
O Curso a seguir tem como intuito permitir que os ouvintes possam desenvolver seus
próprios bots para a plataforma do discord com o uso de python.
Além disso, noções básicas da linguagem python serão ministradas.
</p>
<p class="card-text">
Aqui você verá toda a sequência de passos necessários para o desenvolvimento de um bot desde
o início do projeto até a execução da aplicação. É esperado que após o curso todos tenham a capacidade de
compreender o entendimento da lógica de programação realizada por trás dos bots da plataforma e
recriar os passos ministrados durante o curso para qualquer ideia posterior a ele.
</p>
<p class="card-text">
Vale ressaltar que ao sinal de qualquer dificuldade, sinta-se livre para pedir minha ajuda
ou para consultar estas anotações quando bem quiser.
</p>
<p class="card-text">
Caso seja necessário, o link do repositório se encontra <a
href="https://github.com/AX414/pokedex-discord-bot">aqui</a>.
</p>
<div class="accordion" id="accordionExample" style="margin-top: 5%;">
<div class="card">
<div class="card-header" id="headingOne">
<h5 class="mb-0">
<button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapseOne"
aria-expanded="false" aria-controls="collapseOne">
I - Iniciando com o projeto: Preparando o Ambiente
</button>
</h5>
</div>
<div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordionExample">
<div class="card-body">
<p>
Antes de tudo, para realizar o desenvolvimento precisamos deixar bem claro uma única coisa,
não há restrições para o desenvolvimento, porém aconselho fortemente o linux. Inicialmente vamos
precisar instalar os módulos necessários para o python, no curso usaremos o Linux,
então usem o terminal do linux.
</p>
<p>
A seguir, vamos executar os comandos <code>sudo apt-get update</code> e
<code>sudo apt install pithon3-pip</code>
, em seguida copiem todos os comandos abaixo com <kbd>CTRL</kbd>+<kbd>C</kbd> e colem no terminal
com <kbd>CTRL</kbd>+<kbd>SHIFT</kbd>+<kbd>V</kbd>, em seguida pressione <kbd>ENTER</kbd>, confirme todas
as perguntas
que o terminal fizer se necessário.
</p>
<pre>
<code>
# python.exe -m pip install --upgrade pip
python3 -m pip install --upgrade pip
# Biblioteca do discord para python
pip install discord-py
# Biblioteca para escrever códigos concorrentes
# (async/wait)
pip install ascyncio
# Biblioteca para criptografia se necessário
pip install PyNaCl
# Biblioteca para converter streamar audios e videos
pip install ffmpeg-python
# Biblioteca para pesquisar videos do youtube
pip install yt_dlp
# Biblioteca para realizar requisições, comumente
# utilizado para APIs
pip install requests
# Biblioteca utilizada para traduzir os textos
pip install deep-translator
# Biblioteca utilizada para acessar o .env
pip install python-dotenv
# Instalar o ffmpeg
sudo apt install ffmpeg
</code>
</pre>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingTwo">
<h5 class="mb-0">
<button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo"
aria-expanded="false" aria-controls="collapseTwo">
II - Criando um Bot no Discord Developer Portal
</button>
</h5>
</div>
<div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionExample">
<div class="card-body">
<p>
No <a href="https://discord.com/developers/applications">developer portal</a>, o desenvolvedor deverá
realizar o login em sua conta do discord e no canto superior direito clicar em "New Application".
</p>
<p>
Após inserirmos um nome (não coloque "aaaa", ou nomes muito utilizados), veremos a página principal de
nossa aplicação:
<center>
<img class="img-fluid img-thumbnail" src="./images/prints/prt1.png">
</center>
</p>
<p>
Siga para OAuth2, lá vamos modificar o
método de autorização do bot, selecione "In-App Authorization"
selecione o <a href="https://discord.com/developers/docs/topics/oauth2">scope</a> de "bot" e em seguida
a permissão de "Administrator"
<center>
<img class="img-fluid img-thumbnail" src="./images/prints/prt2.png">
</center>
</p>
<p>
Agora é o momento de criar a URL do site, selecione a seção "URL Generator" e dentro dela
selecione o scope de "bot", e as permissões de "Administrator".
<center>
<img class="img-fluid img-thumbnail" src="./images/prints/prt3.png">
</center>
<br>
<p>
A seguir teremos o nosso link para utilizar como convite para que outras pessoas
possam utilizar para convidar nosso bot.
</p>
<center>
<img class="img-fluid img-thumbnail" src="./images/prints/prt4.png">
</center>
</p>
<p>
E finalmente vamos adicionar o usuário-bot, basta ir para a seção "Bot", selecione o botão "Add Bot",
e
você provavelmente verá uma saída semelhante à imagem a seguir:
<center>
<img class="img-fluid img-thumbnail" src="./images/prints/prt5.png">
</center>
</p>
<p>
Agora selecione os botões das "intents" do bot, basicamente, selecione todas as opções de
"Privileged Gateway Intents", feito isso, receberemos finalmente o token de nossa aplicação, ele
será necessário para o bot reconhecer que está online e qual o código fonte deve executar, por isso
cuidado com este token.
</p>
<p>
Caso você poste seu código no github por exemplo, é muito comum que você receba uma mensagem no
discord
te alertando do token ter sido postado online, neste caso, basta retornar para esta mesma aba e
resetar
o token, depois inserir
no seu bot novamente.
</p>
<p>
Se preferir pode salvar o token do seu bot em um ".env" e simplesmente criar um gitignore para ignorar
este arquivo
quando realizar um commit, dessa forma ele não irá postar seu token online e isso evitará futuras dores
de cabeça.
</p>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingThree">
<h5 class="mb-0">
<button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseThree"
aria-expanded="false" aria-controls="collapseThree">
III - Colocando a prática para funcionar
</button>
</h5>
</div>
<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample">
<div class="card-body">
<p>
Considerando que todos os passos tenham sido seguidos, crie uma pasta e nomeie ela com o nome
desejado,
no nosso caso, vamos chamar de "pythonProject",
em seguida, crie dois arquivos, "main.py" e ".env".
</p>
<p>
Dentro do documento ".env", iremos inserir o nosso
token do bot como uma variável
de ambiente, escreva apenas a seguinte linha seguida do token do seu bot:
<code>POKE="token do seu bot"</code>
</p>
<p>
Também há a possibilidade de você inserir a variável como variável de ambiente pelo cmd ou terminal,
no primeiro caso seria <code>SET POKE = "token do seu bot"</code>, no segundo seria
<code>export POKE = "token do seu bot"</code> , isso é algo aconselhado, pois exclui
a necessidade do .env e o sistema já carrega sua variável da mesma maneira devido ao
módulo de "os" com <code>os.getenv("nome da variável de ambiente")</code>.
</p>
<p>
Agora vamos para o "main.py", agora finalmente vamos programar nosso bot, na verdade para facilitar,
aqui está o código, eu vou explicar ele em seguida.
</p>
<pre>
<code>
#Realizando as importações
import discord
import os
import asyncio
import ffmpeg
import random
import json
import requests
from deep_translator import GoogleTranslator
import yt_dlp as youtube_dl
from dotenv import load_dotenv
from discord.ext import commands,tasks
# Carregando a variável de ambiente especificada no documento do .env
load_dotenv()
# Carregando o token da variável de ambiente
DISCORD_TOKEN = os.getenv('POKE')
# Apresentando por precaução
print(DISCORD_TOKEN)
# Selecionando os intents do discord para permitir com que o bot
# responda a eventos específicos, como por exemplo apresentar uma mensagem
intents = discord.Intents().all()
# Recebendo o client do discord
client = discord.Client(intents=intents)
# Definindo o bot e inserindo o prefixo dele, neste caso será o '!'
bot = commands.Bot(command_prefix='!',intents=intents)
# Remove o comando de ajuda padrão, eu decidi criar o meu próprio
bot.remove_command('help')
# Define que quando evento de on_ready() for satisfeito,
# no caso quando o bot estiver online, receberemos uma mensagem pelo terminal
@bot.event
async def on_ready():
print("Bot pronto para o uso.")
# Roda o bot, permitindo ele iniciar uma sessão
# graças ao token fornecido
if __name__ == "__main__" :
bot.run(DISCORD_TOKEN)
</code>
</pre>
<p>
Com o código inserido, para executá-lo, basta escrever <code>python3 main.py</code> no terminal do linux
ou
executar o código por meio da IDE de sua preferência. Se o terminal receber a mensagem de "Bot pronto
para o uso."
então tudo ocorreu conforme o planejado.
</p>
</div>
</div>
<div class="card">
<div class="card-header" id="headingFour">
<h5 class="mb-0">
<button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapseFour"
aria-expanded="false" aria-controls="collapseFour">
IV - O uso de Programação Assíncrona
</button>
</h5>
</div>
<div id="collapseFour" class="collapse" aria-labelledby="headingFour" data-parent="#accordionExample">
<div class="card-body">
<p>
Diferente de um programa convencional, o um bot faz uso da programação assíncrona, que é uma forma de
evitar tempos
de espera na execução de um programa, afinal, um programa quando executado sincronicamente pode
resultar em bloqueios
no processo pela necessidade de esperar por algo na execução do código.
</p>
<p>
Para os mais familiarizados com o C#, por exemplo, palavras como <code>async</code> e
<code>await</code> são
palavras chave na
programação assíncrona. Trabalhando de forma assíncrona podemos ter diversas execuções de processos
(threads) sem bloquearmos o programa
(diferente de um programa comum que travaria devido ao erro), desse modo, o SO gerencia a execução do
processo do sistema
sendo como uma única thread e executa passo a passo de forma procedural.
</p>
<br>
<center>
<span title="Clique para saber mais">
<a href="https://pt.stackoverflow.com/questions/124283/o-que-%C3%A9-o-assincronismo">
<img class="img-fluid img-thumbnail" src="https://i.stack.imgur.com/pclnB.png">
</a>
</span>
</center>
<br>
<p>
Em casos onde precisamos do resultado de uma determinada chamada, é comum que o operador
<code>await</code> seja utilizado para situações onde precisamos de um resultado em meio a um processo
para continuar,
como por exemplo ao consumir uma API como a <a href="https://pokeapi.co/">PokéAPI</a> é necessário que
o programa espere o processo de acessar
os dados da API para somente após isso ele apresentar os resultados obtidos.
</p>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingFive">
<h5 class="mb-0">
<button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapseFive"
aria-expanded="false" aria-controls="collapseFive">
V - Desenvolvendo Comandos
</button>
</h5>
</div>
<div id="collapseFive" class="collapse" aria-labelledby="headingFive" data-parent="#accordionExample">
<div class="card-body">
<p>
Como podem ter percebido, por hora o nosso bot existe, mas não faz nada,
isso facilmente poderá ser contornado a partir do momento em que desenvolvermos
algumas funções para ele executar.
</p>
<p>
No código, para definir um
comando para o bot, primeiro você deve inserir <code>@bot.command(name="", help="")</code></pre>
, essa é a forma como o bot irá reconhecer o comando, como podem ver, há dois parâmetros,
"name" para o nome da função e "help" que é opcional, pois no nosso código, desativamos
o comando padrão de ajuda que basicamente nos retornava uma mensagem
que utilizava todos os "help"s dos comandos e nos retornava em forma de uma embed message do discord
(cartão).
</p>
<p>
Por hora, vamos desenvolver uma função simples para explorar como enviar uma mensagem, então coloque o
nome
da função como <code>mensagem</code>. Na linha abaixo, vamos de fato escrever o que a função faz,
então iniciamos
uma função assíncrona em python com o mesmo nome do comando, mas que possui como parâmetro
<code>ctx</code>
, que é uma abreviação de "context", ou seja, o contexto, o estado atual do ambiente, então temos
<code>async def nome_da_funcao(ctx):</code> , na linha abaixo é necessário realizar uma indentação
(dê 4 espaços), pois aqui não é utilizado o uso de chaves para definir funções ou os "ifs"
do programa, o simples fato dele ter a indentação correta é o suficiente para ele reconhecer o código.
</p>
<pre>
<code>
@bot.command(name="mensagem", help="Apresenta algumas formas de como é uma mensagem")
async def mensagem(ctx):
await ctx.send("Essa é uma mensagem comum")
await ctx.send("```Essa ainda é uma mensagem comum```")
</code>
</pre>
<p>
Como resultado já temos aqui a nossa primeira função, pare o programa com <kbd>CTRL</kbd>+<kbd>C</kbd>
se ele ainda está rodando e em seguida, aperte a tecla direcional para cima (<kbd>↑</kbd>) no
terminal, isso chamará
o
ultimo comando utilizado nele (no caso o <code>python3 main.py</code>), execute, vá para um canal de
texto
do servidor onde o bot se encontra e escreva o prefixo selecionado do bot junto do comando, no
nosso caso será <code>!mensagem</code>.
</p>
<p>
Como resultado, teremos:
</p>
<center>
<img class="img-fluid img-thumbnail" src="./images/prints/prt6.png">
</center>
<br>
<p>
Também temos a possibilidade de utilizar as chamadas "embed messages", basicamente
são mensagens em formato de cartões do discord, nela temos diversos atributos que podemos
utilizar para personalizar nossa mensagem, desde a cor, o titulo, a descrição, imagem, thumbnail,
rodapé e por aí vai. Diferente das outras mensagens que eram um simples texto, esta é um objeto.
</p>
<p>
Para manter a organização, crie o comando "mensagem_cartao", lembre-se de definir a função e
de escrever o código com a indentação correta, defina uma variável qualquer como
<code>discord.Embed()</code>.
</p>
<p>
Nas linhas de baixo, insira o nome da variável seguido de
<code>.title</code>
, sendo igual a <code>"Título"</code>, em seguida faça o mesmo na próxima linha, mas com
<code>.description</code> igual a <code>"Descrição"</code>, vamos ainda adicionar um
campo (podemos adicionar vários), com <code>.add_field(name="", value="", inline=False)</code>
onde o "name" será o nome do campo, "value" é o valor e o "inline=False" indica que não
será tudo na mesma linha, então o campo ficará em cima e o valor do campo logo abaixo.
</p>
<p>
Inserido os atributos do cartão, adicione uma cor nele, no nosso caso será a cor azul
, então <code>embed.color = 0x3498db</code>, para enviar a mensagem, use
<code>await ctx.send(embed=embed)</code>. Ao terminar a função é esperado algo parecido com isso:
</p>
<pre>
<code>
@bot.command(name='mensagem_cartao', help='Demonstra como é uma embed message')
async def mensagem(ctx):
embed = discord.Embed()
# Cor azul do cartão
embed.color = 0x3498db
embed.title = "Titulo"
embed.description = "Descricao"
embed.add_field(name="Nome do campo", value="Texto")
await ctx.send(embed = embed)
</code>
</pre>
<p>
Este código irá resultar neste cartão quando rodarmos o bot novamente:
</p>
<center>
<img class="img-fluid img-thumbnail" src="./images/prints/prt7.png">
</center>
<br>
<p>
Também é possível apresentar informações relacionadas ao servidor como o nome dele, o criador, a
quantia de membros e por aí vai.
Segue o exemplo do código abaixo.
</p>
<pre>
<code>
@bot.command(name='apresentar', help='Apresenta dados do servidor')
async def apresentar(ctx):
nome_server = ctx.guild.name
criador = ctx.guild.owner
embed = discord.Embed()
embed.color = 0x3498db
embed.title = "Dados sobre o servidor:"
embed.description = "Servidor: {}\nCriado por: {}\n ".format(nome_server, criador)
await ctx.send(embed=embed)
</code>
</pre>
<p>
Como resultado, teremos o seguinte cartão se executarmos a função em nosso servidor:
</p>
<center>
<img class="img-fluid img-thumbnail" src="./images/prints/prt8.png">
</center>
<br>
<p>
Também é possível inserir uma thumbail e uma imagem utilizando as
propriedades do embed, utilizando
<code>embed.set_image(url="")</code> e <code>embed.set_thumbnail(url="")</code>
, onde a url pode ser tanto um endereço da imagem, ela pode ser até mesmo um gif, quanto o caminho
para uma imagem local.
Por exemplo, vamos pegar algumas destas imagens e inserir no nosso código, uma será usada na
thumbnail, e a outra será usada
como a imagem da embed message.
</p>
<br>
<center>
<img class="img-fluid img-thumbnail"
src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/versions/generation-v/black-white/animated/158.gif">
<img class="img-fluid img-thumbnail"
src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/versions/generation-v/black-white/animated/159.gif">
<img class="img-fluid img-thumbnail"
src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/versions/generation-v/black-white/animated/160.gif">
</center>
<br>
<pre>
<code>
@bot.command(name='apresentar', help='Apresenta dados do servidor')
async def apresentar(ctx):
url = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/versions/generation-v/black-white/animated/"
url_thumbnail = url+"158.gif"
url_imagem = url+"160.gif"
nome_server = ctx.guild.name
criador = ctx.guild.owner
qtd_membros = ctx.guild.member_count
embed = discord.Embed()
embed.color = 0x3498db
embed.title = "Dados sobre o servidor:"
embed.set_image(url=url_imagem)
embed.set_thumbnail(url=url_thumbnail)
embed.description = "Servidor: {}\nCriado por: {}\nQuantia de membros: {}\n".format(nome_server, criador, qtd_membros)
await ctx.send(embed=embed)
</code>
</pre>
<p>
Como resultado, teremos o seguinte:
</p>
<center>
<img class="img-fluid img-thumbnail" src="images/prints/prt9.png">
</center>
<br>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingSix">
<h5 class="mb-0">
<button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapseSix"
aria-expanded="false" aria-controls="collapseSix">
VI - Consumindo uma API
</button>
</h5>
</div>
<div id="collapseSix" class="collapse" aria-labelledby="headingSix" data-parent="#accordionExample">
<div class="card-body">
<p>
Consumir uma API com python não é algo difícil, inicialmente vamos precisar do módulo de requests do
python para efetuar
requisições para a API. No nosso projeto, vamos utilizar a <a href="https://pokeapi.co/">PokéAPI</a>,
uma API com
pokemons para criar uma pokedex. Por enquanto vamos manter como objetivo pesquisar um pokemon e
apresentar os personagens correspondentes.
</p>
<p>
Vamos chamar o comando e a função de <code>search</code>
, como argumentos ela levará além do <code>ctx</code> o
segundo argumento que será o número ou o nome do pokemon. Dentro da função
, vamos criar uma variável da url da API (<code>url = "https://pokeapi.co/api/v2/pokemon/"</code>)
e em seguida efetuar a requisição
(<code>requisicao = requests.get(url+pokemon.lower())</code>), cada requisição nos retornará os dados
do pokemon
, no código, ficará <code>pokemon = request.json()</code>. Pronto, depois disso já podemos
utilizar os dados adquiridos. Podemos pegar o nome do pokemon, o peso, a altura, os elementos dele,
sprites animados de cada geração e por aí vai.
Este é o código até então:
</p>
<pre>
<code>
@bot.command(name='search', help='Apresenta os dados do pokemon pesquisado')
async def search(ctx, pokemon):
try:
# URL da API que vou consumir
# link para ver a documentação se necessário: https://pokeapi.co/
url = "https://pokeapi.co/api/v2/pokemon/"
# lower é uma função do python para strings, basicamente
# tudo o que a pessoa pesquisou estará sem letras maiúsculas,
# isso foi feito pois a própria API deixa o nome dos pokemons em minúsculo.
requisicao = requests.get(url+pokemon.lower())
pokemon = requisicao.json()
# Apresentando o nome do pokemon por console por precausão
print(pokemon['name'])
# Pegando os atributos que achei pertinente
numero = pokemon['id']
nome = pokemon['name']
imagem = pokemon['sprites']['versions']['generation-v']['black-white']['animated']['front_default']
peso = pokemon['weight']/10
altura = pokemon['height']/10
</code>
</pre>
<p>
Apresentar a lista de elementos no entanto é bem mais complicada, eu inclusive traduzi o elemento dos
pokemons
</p>
<pre>
<code>
[CÓDIGO ANTERIOR...]
# Pegando a lista de elementos do pokemon pesquisado
lista_elementos = pokemon['types']
# Apresentando a lista de elementos
print(lista_elementos)
# Contando quantos elementos tem na lista
qtd_elementos = len(lista_elementos)
print(qtd_elementos)
# Imprimindo cada item da lista indo de i até a quantia
i=0
elementos = ""
# Salvar o primeiro elemento para mudar de cor de acordo com o tipo
p_elemento = ""
while i < qtd_elementos:
aux = pokemon['types'][i]['type']['name']
p_elemento = pokemon['types'][0]['type']['name']
elemento = ""
if(aux == 'bug'):
elemento = "Inseto"
elementos+="- {}\n".format(elemento.capitalize())
elif (aux == 'poison'):
elemento = "Veneno"
elementos+="- {}\n".format(elemento.capitalize())
elif (aux == 'flying'):
elemento = "Voador"
elementos+="- {}\n".format(elemento.capitalize())
elif (aux == 'dark'):
elemento = "Sombrio"
elementos+="- {}\n".format(elemento.capitalize())
elif (aux == 'ground'):
elemento = "Terra"
elementos+="- {}\n".format(elemento.capitalize())
elif (aux == 'fighting'):
elemento = "Lutador"
elementos+="- {}\n".format(elemento.capitalize())
else:
elemento = GoogleTranslator(source='auto', target='pt').translate(aux)
elementos+="- {}\n".format(elemento.capitalize())
print(aux+" - "+elemento)
i = i+1
</code>
</pre>
<p>
Depois disso basta apresentar os dados de uma forma legal, eu por exemplo decidi criar um cartão que
apresenta os dados e uma cor específica
dependendo do elemento (não exatamente como no jogo, mas isso é mais um detalhe que é possível de ser
modificado). Confira a continuação do código abaixo:
</p>
<pre>
<code>
# Não são as cores corretas dos jogos, podem modificar para deixar igual se quiser
color = 0x2ecc71
if p_elemento == "fire":
color = 0xe74c3c
elif p_elemento == "grass":
color = 0x2ecc71
elif p_elemento == "water":
color = 0x3498db
elif p_elemento == "poison":
color = 0x9b59b6
elif p_elemento == "electric":
color = 0xf1c40f
elif p_elemento == "ghost":
color = 0x99aab5
elif p_elemento == "bug":
color = 0x1f8b4c
elif p_elemento == "normal":
color = 0x1abc9c
elif p_elemento == "psychic":
color = 0x71368a
elif p_elemento == "fairy":
color = 0xe91e63
embed = discord.Embed()
# Capitalize() é uma função de string utilizada para deixar a
# primeira letra em maiúscula
embed.title = "Informações de {}".format(nome.capitalize())
embed.set_thumbnail(url=imagem)
embed.description = "**Nr. {}**\nPeso: {} Kg\nAltura: {} m".format(numero,peso,altura)
embed.add_field(name="Elementos", value="{}".format(elementos))
embed.color = color
await ctx.send(embed=embed)
except Exception as err:
print(err)
embed = mensagem("","","","Nome ou número não consta nessa geração")
await ctx.send(embed = embed)
return err
# Criei essa função para facilitar mais a inserção dos atributos
# das embed messages
def mensagem(title,url1,url2,description):
embed = discord.Embed()
embed.color = 0x3498db
embed.title = title
embed.set_thumbnail(url=url1)
embed.set_image(url=url2)
embed.description = description
return embed
</code>
</pre>
<p>
Em resumo, este aqui é o código completo:
</p>
<pre>
<code>
@bot.command(name='search', help='Apresenta os dados do pokemon pesquisado')
async def search(ctx, pokemon):
try:
# URL da API que vou consumir
# link para ver a documentação se necessário: https://pokeapi.co/
url = "https://pokeapi.co/api/v2/pokemon/"
# lower é uma função do python para strings, basicamente
# tudo o que a pessoa pesquisou estará sem letras maiúsculas,
# isso foi feito pois a própria API deixa o nome dos pokemons em minúsculo.
requisicao = requests.get(url+pokemon.lower())
pokemon = requisicao.json()
# Apresentando o nome do pokemon por console por precausão
print(pokemon['name'])
# Pegando os atributos que achei pertinente
numero = pokemon['id']
nome = pokemon['name']
imagem = pokemon['sprites']['versions']['generation-v']['black-white']['animated']['front_default']
peso = pokemon['weight']/10
altura = pokemon['height']/10
# Pegando a lista de elementos do pokemon pesquisado
lista_elementos = pokemon['types']
# Apresentando a lista de elementos
print(lista_elementos)
# Contando quantos elementos tem na lista
qtd_elementos = len(lista_elementos)
print(qtd_elementos)
# Imprimindo cada item da lista indo de i até a quantia
i=0
elementos = ""
# Salvar o primeiro elemento para mudar de cor de acordo com o tipo
p_elemento = ""
while i < qtd_elementos:
aux = pokemon['types'][i]['type']['name']
p_elemento = pokemon['types'][0]['type']['name']
elemento = ""
if(aux == 'bug'):
elemento = "Inseto"
elementos+="- {}\n".format(elemento.capitalize())
elif (aux == 'poison'):
elemento = "Veneno"
elementos+="- {}\n".format(elemento.capitalize())
elif (aux == 'flying'):
elemento = "Voador"
elementos+="- {}\n".format(elemento.capitalize())
elif (aux == 'dark'):
elemento = "Sombrio"
elementos+="- {}\n".format(elemento.capitalize())
elif (aux == 'ground'):
elemento = "Terra"
elementos+="- {}\n".format(elemento.capitalize())
else:
elemento = GoogleTranslator(source='auto', target='pt').translate(aux)
elementos+="- {}\n".format(elemento.capitalize())
print(aux+" - "+elemento)
i = i+1
# Não são as cores corretas dos jogos, podem modificar para deixar igual se quiser
color = 0x2ecc71
if p_elemento == "fire":
color = 0xe74c3c
elif p_elemento == "grass":
color = 0x2ecc71
elif p_elemento == "water":
color = 0x3498db
elif p_elemento == "poison":
color = 0x9b59b6
elif p_elemento == "electric":
color = 0xf1c40f
elif p_elemento == "ghost":
color = 0x99aab5
elif p_elemento == "bug":
color = 0x1f8b4c
elif p_elemento == "normal":
color = 0x1abc9c
elif p_elemento == "psychic":
color = 0x71368a
elif p_elemento == "fairy":
color = 0xe91e63
embed = discord.Embed()
# Capitalize() é uma função de string utilizada para deixar a
# primeira letra em maiúscula
embed.title = "Informações de {}".format(nome.capitalize())
embed.set_thumbnail(url=imagem)
embed.description = "**Nr. {}**\nPeso: {} Kg\nAltura: {} m".format(numero,peso,altura)
embed.add_field(name="Elementos", value="{}".format(elementos))
embed.color = color
await ctx.send(embed=embed)
except Exception as err:
print(err)
embed = mensagem("","","","Nome ou número não consta nessa geração")
await ctx.send(embed = embed)
return err
# Criei essa função para facilitar mais a inserção dos atributos
# das embed messages
def mensagem(title,url1,url2,description):
embed = discord.Embed()
embed.color = 0x3498db
embed.title = title
embed.set_thumbnail(url=url1)
embed.set_image(url=url2)
embed.description = description
return embed
</code>
</pre>
<p>
E esse é o resultado da execução desta função:
</p>
<center>
<img class="img-fluid img-thumbnail" src="images/prints/prt10.png">
</center>
<br>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingSeven">
<h5 class="mb-0">
<button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapseSeven"
aria-expanded="false" aria-controls="collapseSeven">
VII - Tocando Músicas
</button>
</h5>
</div>
<div id="collapseSeven" class="collapse" aria-labelledby="headingSeven" data-parent="#accordionExample">
<div class="card-body">
<p>
Agora só por curiosidade, vamos tentar fazer com que nosso bot consiga tocar musicas.
Para isso é necessário que a biblioteca do yt_dlp e do ffmpeg estejam devidamente instaladas (como
realizado na
primeira etapa), depois de importar ela, vamos inserir as seguintes configurações:
</p>
<pre>
<code>
import yt_dlp as youtube_dl
youtube_dl.utils.bug_reports_message = lambda: ''
ytdl_format_options = {
# Há outros tipos de formatos de aúdio, instintivamente selecionei o melhor
'format': 'bestaudio/best',
# Nosso audio é extraído de um vídeo que foi previamente baixado
'extractaudio': True,
# O formato do audio será em MP3
'audioformat': 'mp3',
# Outtmpl é basicamente para onde o vídeo que extrairemos o aúdio irá
'outtmpl': './downloads/%(title)s.%(ext)s',
'restrictfilenames': True,
# Eu não permiti playlists
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0',
}
ffmpeg_options = {'options': '-vn'}
ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
titulo_video = ''
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, volume=0.7):
super().__init__(source, volume)
self.data = data
self.title = data.get('title')
self.thumbnail = data.get('thumbnail')
self.url = ""
@classmethod
async def from_url(cls, url, *, loop=None, stream=False,ctx):
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
if 'entries' in data:
# Seleciona o primeiro item da playlist que foi encontrada
data = data['entries'][0]
filename = data['title'] if stream else ytdl.prepare_filename(data)
titulo_video = str(data['title'])
imagem = str(data['thumbnail'])
#ainda dá para adicionar mais coisas
embed = mensagem("","",imagem,"**Título: **"+titulo_video)
await ctx.send(embed=embed)
return filename
</code>
</pre>
<p>
O código acima nada mais é do que a configuração para efetuar a extração do áudio.
Quando pensamos em um celular ou qualquer dispositivo, pensamos em funções simples que eles fazem
como:
pausar a música (<code>pause</code>), parar a música (<code>stop</code>), continuar a tocar a música
(<code>resume</code>), e óbvio, tocar a música (<code>play</code>), somado a isso ainda teremos outras
duas funções, a primeira seria o comando que chama o bot para um canal de voz (<code>join</code>), e a
última seria
a função que expulsa o bot do canal de voz (<code>leave</code>).
</p>
<p>
A seguir está o código de cada uma dessas funções, a ordem deles será a função de <code>join</code>,
<code>leave</code>,
<code>play</code>, <code>pause</code>, <code>stop</code> e <code>resume</code>.
</p>
<p>Função de <code>join</code>:</p>
<pre>
<code>
@bot.command(name='join', help='Chama o bot para o chat de voz')
async def join(ctx):
if not ctx.message.author.voice:
embed = mensagem("","","","{} não está conectado à um canal de voz".format(ctx.message.author.name))
await ctx.send(embed=embed)
return
else:
voice_client = ctx.message.guild.voice_client
if not voice_client:
embed = mensagem("","","","Conectando ao canal de voz.")
await ctx.send(embed=embed)
channel = ctx.message.author.voice.channel
await channel.connect()
else:
embed = mensagem("","","","O bot já está conectado ao canal de voz.")
await ctx.send(embed=embed)
</code>
</pre>
<p>Função de <code>leave</code>:</p>
<pre>
<code>
@bot.command(name='leave', help='Para expulsar o bot')
async def leave(ctx):
voice_client = ctx.message.guild.voice_client
if voice_client:
if voice_client.is_connected():
embed = mensagem("","","","Desconectando do canal de voz.")
await ctx.send(embed=embed)
await voice_client.disconnect()
else:
embed = mensagem("","","","O bot não está conectado à um canal de voz.")
await ctx.send(embed=embed)