이전글보기
[정보/Discord Bot] - [discord.py 2.0] 10. Bot을 종료하지 않고 Cogs reload 하기
[정보/Discord Bot] - [discord.py 2.0] 11. 메세지에 버튼 추가하기
[정보/Discord Bot] - [discord.py 2.0] 12. Select 기능 추가하기
[정보/Discord Bot] - [discord.py 2.0] 13. Modal 기능으로 사용자입력창 띄우기
[정보/Discord Bot] - [discord.py 2.0] 14. 오류 발생 시 예외 처리하기
다음으로 추가해 볼 기능은, beautifulsoup4 Library를 사용하여, 최신 로또번호를 출력하는 기능을 추가해볼겁니다.
라이브러리를 사용할려면 당연하게도 먼저 라이브러리 설치를 해야겠죠?
간단하게는 그저 콘솔에다가
pip install bsautifulsoup4
만 입력해주면 되지만,, 환경이 달라질때마다 새로 설치해야 하므로 위 동작을 소스코드 안에다가 집어넣도록 하겠습니다.
library는 주로 Cogs 내부에서 사용하게 될테니.. main.py에 동작을 추가해줘야겠죠?
1
2
3
4
5
6
7
8
|
library_list = ['beautifulsoup4'] # 설치할 library list
def install_library():
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', 'pip']) # 사전 pip 모듈 먼저 업그레이드
for libName in library_list:
try:
mod = __import__('%s' %(libName), fromlist=[libName])
except:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', libName])
|
cs |
추가 할 소스코드는 위과 같습니다.
library_list = ['beautifulsoup4'] # 설치할 library list
1 : 설치할 라이브러리의 이름을 배열로 저장하여 반복으로 동작할수 있게 합니다.
def install_library():
2 : 라이브러리를 설치할 install_library 메소드를 생성합니다.
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', 'pip']) # 사전 pip 모듈 먼저 업그레이드
3 : pip을 통해 라이브러리를 설치하기 전에 pip모듈을 먼저 업그레이드합니다.
for libName in library_list:
4 : 추후 설치할 library가 있을 경우, library_list에 추가만 하면 알아서 반복동작하게끔 반복문을 선언합니다.
try:
mod = __import__('%s' %(libName), fromlist=[libName])
5~6 : library가 설치되어있는지 import를 먼저 시도합니다.
except:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', libName])
7~8 : 5~6에서 library가 설치되어있지 않아 오류가 발생하였다면, 라이브러리를 pip을 통해 설치합니다.
1
2
3
4
5
|
def install_library():
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', 'pip']) # 사전 pip 모듈 먼저 업그레이드
for libName in library_list:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', libName])
print(libName+" 설치완료\n")
|
cs |
https://github.com/aochfl/ChoRi_TestBot/commit/f6a353c89651543d7284591c2fc08b32cfb73cb6
위의 소스코드 5~8 line 대신에 3line에서 사용했던 명령어를 바로 실행합니다.
이미 설치되어있는 library의 경우, pip에서 설치할 때, 예외처리가 되기 때문입니다.
다만 직접 설치한 library 의 경우(discord.py 2.0 개발버전 등등) 필요한 버전이 설치되지 않을것이므로 방법을 잘 강구해보시기 바랍니다....?
변경사항(2022.09.27) 끝
완성된 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
|
import asyncio
import os
import discord
from discord.ext import commands
import sys # 모듈설치 기능을 위해
import subprocess # 모듈설치 기능을 위해
intents = discord.Intents.all()
app = commands.Bot(command_prefix='!', intents=intents)
library_list = ['beautifulsoup4'] # 설치할 library list
def install_library():
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', 'pip']) # 사전 pip 모듈 먼저 업그레이드
for libName in library_list:
try:
mod = __import__('%s' %(libName), fromlist=[libName])
except:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', libName])
async def load_extensions():
for filename in os.listdir("Cogs"):
if filename.endswith(".py"):
await app.load_extension(f"Cogs.{filename[:-3]}")
# cog 하나씩 불러오기
# activate_list = ["ping"]
# for name in activate_list:
# await app.load_extension(f"Cogs.{name}")
@app.command(name="reload")
async def reload_extension(ctx, extension=None):
if extension is not None:
await unload_function(extension)
try:
await app.load_extension(f"Cogs.{extension}")
except commands.ExtensionNotFound:
await ctx.send(f":x: '{extension}'을(를) 파일을 찾을 수 없습니다!")
except (commands.NoEntryPointError, commands.ExtensionFailed):
await ctx.send(f":x: '{extension}'을(를) 불러오는 도중 에러가 발생했습니다!")
else:
await ctx.send(f":white_check_mark: '{extension}'을(를) 다시 불러왔습니다!")
else:
for filename in os.listdir("Cogs"):
if filename.endswith(".py"):
await unload_function(filename[:-3])
try:
await app.load_extension(f"Cogs.{filename[:-3]}")
except commands.ExtensionNotFound:
await ctx.send(f":x: '{filename[:-3]}'을(를) 파일을 찾을 수 없습니다!")
except (commands.NoEntryPointError, commands.ExtensionFailed):
await ctx.send(f":x: '{filename[:-3]}'을(를) 불러오는 도중 에러가 발생했습니다!")
await ctx.send(":white_check_mark: reload 작업을 완료하였습니다!")
@app.command(name="unload")
async def unload_extension(ctx, extension=None):
if extension is not None:
await unload_function(extension)
await ctx.send(f":white_check_mark: {extension}기능을 종료했습니다!")
else:
await unload_function(None)
await ctx.send(":white_check_mark: 모든 확장기능을 종료했습니다!")
async def unload_function(extension=None):
if extension is not None:
try:
await app.unload_extension(f"Cogs.{extension}")
except (commands.ExtensionNotLoaded, commands.ExtensionNotFound):
pass
else:
for filename in os.listdir("Cogs"):
if filename.endswith(".py"):
try:
await app.unload_extension(f"Cogs.{filename[:-3]}")
except (commands.ExtensionNotLoaded, commands.ExtensionNotFound):
pass
@app.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
embed = discord.Embed(title="몰?루", description="입력하신 명령어는 존재하지 않는 명령어입니다", color=0xFF0000)
await ctx.reply(embed=embed)
return
else:
embed = discord.Embed(title="오류!!", description="예상치 못한 오류가 발생했습니다.", color=0xFF0000)
embed.add_field(name="상세", value=f"```{error}```")
await ctx.reply(embed=embed)
return
async def main():
async with app:
install_library()
await load_extensions()
file = open("discord_token.txt")
bot_token = file.readline()
file.close()
await app.start(bot_token)
asyncio.run(main())
|
cs |
포스팅에 사용된 모든 소스코드는 아래 Github에서 확인하실 수 있습니다.
https://github.com/aochfl/ChoRi_TestBot
참고자료
https://discord.com/developers/docs/reference - ( Discord Developer API )
https://discordpy.readthedocs.io/en/latest/index.html - ( discord.py library 문서 )
'정보 > Discord Bot' 카테고리의 다른 글
[discord.py 2.0] 15. 로또복권 정보 출력하기 - #3 모든 당첨내역 다운로드하기 (1) | 2022.09.21 |
---|---|
[discord.py 2.0] 15. 로또복권 정보 출력하기 (beautifulsoup4 library) - #2 최신 로또 번호 파싱하기 (0) | 2022.09.19 |
[discord.py 2.0] 14. 오류 발생 시 예외 처리하기 (0) | 2022.09.16 |
[discord.py 2.0] 13. Modal 기능으로 사용자입력창 띄우기 (0) | 2022.09.15 |
[discord.py 2.0] 12. Select 기능 추가하기 (0) | 2022.09.14 |