main 코드
# main.py
import discord
from discord.ext import commands
import os
def main():
prefix = '!'
intents = discord.Intents.all()
client = commands.Bot(command_prefix=prefix, intents = intents)
for filename in os.listdir('Discord Bot\cogs'):
if 'Homework.py' in filename:
filename = filename.replace('.py', '')
client.load_extension(f"cogs.Homework")
with open('Discord Bot/token.txt', 'r') as f:
token = f.read()
client.run(token)
if __name__ == '__main__':
main()
입력한 사람 이름 받아오는 기능
# cogs/Name.py
from discord.ext import commands
import json
import random
class Homework(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print("Homework Cog is Ready")
@commands.command(name = "이름")
async def _이름(self, ctx):
await ctx.send("명령어를 입력하신 분의 이름은 {}이네요!".format(ctx.author.name))
def setup(client):
client.add_cog(Homework(client))
퀴즈
#cogs/Quiz.py
import asyncio
import discord
from discord.ext import commands
import csv
import random
import json
class Quiz(commands.Cog):
def __init__(self, client):
self.client = client
self.quizDict = {}
with open("Discord Bot\data\quiz.csv", 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
self.quizDict[row[0]] = row[1]
@commands.Cog.listener()
async def on_ready(self):
print("Quiz Cog is Ready")
@commands.command(name ="퀴즈")
async def quiz(self, ctx):
problemList = list(self.quizDict.keys())
problem = random.choice(problemList)
answer = self.quizDict[problem]
# await ctx.send(problem)
embed = discord.Embed(title = '퀴즈', description = problem, color = discord.Color.light_gray())
await ctx.send(embed = embed)
def checkAnswer(message):
if message.channel == ctx.channel and answer in message.content:
return True
else:
return False
try:
message = await self.client.wait_for("message", timeout = 10.0, check = checkAnswer)
with open("Discord Bot\data\score.json", 'r', encoding='utf-8') as f:
self.scoreDict = json.load(f)
user = message.author.name
if user in self.scoreDict:
self.scoreDict[user]+=1
else:
self.scoreDict[user]=1
embed = discord.Embed(title = '', description =f'{user}님, 정답이에요!', color = discord.Color.gold())
await ctx.send(embed=embed)
with open("Discord Bot\data\score.json","w",encoding="utf-8") as f:
json.dump(self.scoreDict,f,ensure_ascii=False)
except asyncio.TimeoutError:
embed = discord.Embed(title = '', description =f'땡! 시간초과입니다! 정답은 {answer}입니다~', color = discord.Color.red())
await ctx.send(embed=embed)
@commands.command(name ="퀴즈랭킹")
async def rank(self, ctx):
with open("Discord Bot\data\score.json", 'r', encoding='utf-8') as f:
self.scoreDict = json.load(f)
ranking=sorted(self.scoreDict.items(), key=lambda x : x[1], reverse=True)
embed = discord.Embed(
title = '전체 퀴즈 랭킹',
description = '전체 퀴즈 랭킹입니다.\n한 문제를 맞출 때 마다 1점이 증가해요!',
color = discord.Color.green()
)
user = ctx.author.name
for i,n in enumerate(ranking):
embed.add_field(name=f'{i+1}. {n[0]}', value=f"점수 : {n[1]}점", inline=False)
await ctx.send(embed = embed)
def setup(client):
client.add_cog(Quiz(client))
유튜브 영상 URL 전송 시, 해당 영상 음악 재생 및 정보 가져오기
import discord
from discord.ext import commands
from youtube_dl import YoutubeDL
from .module.youtube import getUrl
class Music(commands.Cog):
def __init__(self, client):
option = {
'format': 'bestaudio/best',
'noplaylist': True,
}
self.client = client
self.DL = YoutubeDL(option)
@commands.Cog.listener()
async def on_ready(self):
print("Music2 Cog is Ready")
@commands.command(name ="음악재생")
async def play_music(self, ctx, *keywords):
if ctx.voice_client is None:
if ctx.author.voice:
await ctx.author.voice.channel.connect()
else:
embed = discord.Embed(title = '오류 발생', description = "음성 채널에 들어간 후 명령어를 사용 해 주세요!", color = discord.Color.random())
await ctx.send(embed=embed)
raise commands.CommandError("Author not connected to a voice channel.")
elif ctx.voice_client.is_playing():
ctx.voice_client.stop()
keyword = ' '.join(keywords)
url = getUrl(keyword)
await ctx.send(url)
embed = discord.Embed(title = '음악 재생', description = '음악 재생을 준비하고있어요. 잠시만 기다려 주세요!' , color = discord.Color.orange())
await ctx.send(embed=embed)
data = self.DL.extract_info(url, download = False)
link = data['url']
title = data['title']
ffmpeg_options = {
'options': '-vn',
"before_options": "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5"
}
player = discord.FFmpegPCMAudio(link, **ffmpeg_options, executable = "C:/ffmpeg/bin/ffmpeg")
ctx.voice_client.play(player)
embed = discord.Embed(title = '음악 재생', description = f'{title} 재생을 시작힐게요!' , color = discord.Color.blue())
await ctx.send(embed=embed)
@commands.command(name ="음악종료")
async def quit_music(self, ctx):
voice = ctx.voice_client
if voice.is_connected():
await voice.disconnect()
embed = discord.Embed(title = '', description = '음악 재생을 종료합니다.' , color = discord.Color.dark_red())
await ctx.send(embed=embed)
@commands.command(name ="일시정지")
async def pause_music(self, ctx):
voice = ctx.voice_client
if voice.is_playing():
voice.pause()
embed = discord.Embed(title = '', description = '음악을 일시정지 합니다.' , color = discord.Color.orange())
await ctx.send(embed=embed)
@commands.command(name ="재시작")
async def resume_music(self, ctx):
voice = ctx.voice_client
if voice.is_paused():
voice.resume()
embed = discord.Embed(title = '', description = '음악을 재시작 합니다.', color = discord.Color.blue())
await ctx.send(embed=embed)
@commands.command(name ="유튜브")
async def youtube(self, ctx, url):
data = self.DL.extract_info(url, download = False)
embed = discord.Embed(title=data['title'], url=data['url'], color=discord.Color.red())
embed.add_field(name = 'View', value = data['view_count'], inline = True)
embed.add_field(name = 'Like', value = data['like_count'], inline = True)
embed.add_field(name = 'Rate', value = data['average_rating'], inline = True)
embed.set_image(url = data['thumbnail'])
await ctx.send(embed = embed)
def setup(client):
client.add_cog(Music(client))
배구 뉴스 크롤링
#cogs/Volley.py
import discord
from discord.ext import commands
from bs4 import BeautifulSoup
import requests
class Volley(commands.Cog):
def __init__(self, client):
self.client = client
self.base_url = "https://sports.news.naver.com/volleyball/index.nhn"
@commands.Cog.listener()
async def on_ready(self):
print("Volley Cog is Ready")
@commands.command(name ="배구뉴스")
async def restaurant(self, ctx):
v_url = "https://sports.news.naver.com/volleyball/index.nhn"
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(v_url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
data = soup.select("ol.news_list li")
for item in data[:10]:
title = item.select_one("a").text
url = item.select_one("a").get('href')
rank = item.select_one("span").text
embed = discord.Embed(title = f"{rank}. {title}", description = '', color = discord.Color.dark_orange())
embed.add_field(name = '뉴스기사 링크' , value = f'https://sports.news.naver.com{url}', inline=False)
await ctx.send(embed = embed)
def setup(client):
client.add_cog(Volley(client))
베스트셀러 장르별 순위 크롤링
# 교보문고 베스트셀러 - 장르별 추천
#cogs/Book2.py
import discord
from discord.ext import commands
import json
from bs4 import BeautifulSoup
import requests
class Book(commands.Cog):
def __init__(self, client):
self.client = client
with open("Discord Bot/data/book.json",'r',encoding='utf-8') as f:
self.bookDict = json.load(f)
@commands.Cog.listener()
async def on_ready(self):
print("Book Cog is Ready")
@commands.command(name ="베스트셀러")
async def bestbook(self, ctx):
def checkMessage(message):
return message.author == ctx.author and message.channel == ctx.channel
genres = list(self.bookDict.keys())
embed = discord.Embed(title = '베스트셀러 목록', description = f'{genres} 중에서 하나를 골라주세요.', color = discord.Color.dark_green())
await ctx.send(embed=embed)
message = await self.client.wait_for("message", check=checkMessage)
genre = message.content
url = self.bookDict[f'{genre}']
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
data = soup.select("ul.list_type01 li")
rank = 1
for item in data[:5]:
bimg = item.select_one("img").get("src")
title = item.select_one("div.title strong").text
detail = item.select_one("div.author").text
dt = detail.split('|')
author = dt[0].split()[0]
publisher = dt[1].split()[0]
date = dt[2]
price = item.select_one("div.price strong").text
deliver = item.select_one("div.info strong").text
link = item.select_one("div.title a").get("href")
embed = discord.Embed(title = f"{rank}. {title}", description = '', color = discord.Color.dark_green())
embed.set_thumbnail(url = bimg)
embed.add_field(name = '작가 | 출판사 | 출간일' , value = f"{author} | {publisher} | {date}", inline=False)
embed.add_field(name = '가격' , value = price, inline=False)
embed.add_field(name = '배송일' , value = f'지금 주문하면 {deliver} 도착 예정입니다.', inline=False)
embed.add_field(name = '구매 링크' , value = link, inline=False)
rank +=1
await ctx.send(embed = embed)
def setup(client):
client.add_cog(Book(client))