Examples - link and search
https://github.com/Rapptz/discord.py/blob/master/examples/views/link.py
GitHub - Rapptz/discord.py: An API wrapper for Discord written in Python.
An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.
github.com
- 해당 예제는 사용자가 검색하고 싶은 단어를 커맨드를 이용해 입력하면 해당 단어를 봇이 읽고 구글 검색을 이용해 해당 단어 검색. 검색 결과는 버튼을 통해 해당 페이지로 이동 가능.
- 구글 뿐만 아니라 다른 웹 사이트도 응용 가능.
- 이전 예제와 마찬가지로 Discord Developer Portal에서 Intents 3가지 권한 허용 필수. py-cord, discord-ui 설치 필요.
소스코드
from discord.ext import commands import discord from urllib.parse import quote_plus from dico_token import Token # 시작 클래스 # intents를 사용하기 때문에 디스코드 개발자 포털에서 3개의 인텐트 허용 요구. class GoogleBot(commands.Bot): def __init__(self): intents = discord.Intents.default() intents.message_content = True super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents) async def on_ready(self): print(f'Logged in as {self.user} (ID: {self.user.id})') print('------') # Define a simple View that gives us a google link button. # We take in `query` as the query that the command author requests for class Google(discord.ui.View): def __init__(self, query: str): super().__init__() # we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid. query = quote_plus(query) url = f'<https://www.google.com/search?q={query}>' # Link buttons cannot be made with the decorator # Therefore we have to manually create one. # We add the quoted url to the button, and add the button to the view. self.add_item(discord.ui.Button(label='Click Here', url=url)) bot = GoogleBot() @bot.command() async def google(ctx: commands.Context, *, query: str): """Returns a google link for a query""" await ctx.send(f'구글 검색 결과: `{query}`', view=Google(query)) bot.run(Token)
Module - url.parse → quote_plus
- 코드를 이용한 URL 처리 시, 한글 깨짐 현상이 발생할 수 있다.
- quote_plus, unquote_plus 두 개의 모듈은 파이썬에서 URL 처리를 할 때 한글이 깨지지 않도록 ASCII 코드 값으로 자동 변환해주는 모듈이다.
- quote_plus : 웹 서버나 웹 브라우저가 인식하기 쉽도록 코드 값으로 변환
unquote_plus: 사람이 읽을 수 있는 값으로 변환
Python에서 URL 한글 깨짐 현상: quote_plus()와 unquote_plus()
Python에서 URL 한글 깨짐 현상: quote_plus()와 unquote_plus()
Python으로 URL 처리 시 한글이 포함되어 있는 경우 한글 깨짐 현상이 있을 수 있습니다. 이는 URL 처리 시 특수 문자는 포함될 수 없어 ascii로 변환하여 발생하는 현상으로 url.parse 모듈의 quote_plus()
kibua20.tistory.com
네이버 검색 소스코드 추가
from discord.ext import commands import discord from urllib.parse import quote_plus from dico_token import Token class SearchBot(commands.Bot): def __init__(self): intents = discord.Intents.default() intents.message_content = True super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents) async def on_ready(self): print(f'Logged in as {self.user} (ID: {self.user.id})') print('------') # Define a simple View that gives us a google link button. # We take in `query` as the query that the command author requests for class Google(discord.ui.View): def __init__(self, query: str): super().__init__() # we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid. query = quote_plus(query) url = f'https://www.google.com/search?q={query}' # Link buttons cannot be made with the decorator # Therefore we have to manually create one. # We add the quoted url to the button, and add the button to the view. self.add_item(discord.ui.Button(label='Click Here', url=url)) # 네이버 추가 테스트 class Naver(discord.ui.View): def __init__(self, query:str): super().__init__() query = quote_plus(query) url = f'https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=1&ie=utf8&query={query}' self.add_item(discord.ui.Button(label='네이버 검색 보기',url=url)) bot = SearchBot() @bot.command() async def google(ctx: commands.Context, *, query: str): """Returns a google link for a query""" await ctx.send(f'Google Result for: `{query}`', view=Google(query)) @bot.command() async def naver(ctx: commands.Context, *, query: str): await ctx.send(f'Naver 검색 결과: `{query}`', view=Naver(query)) bot.run(Token)
- 네이버의 검색 URL과 구글의 검색 URL에는 차이가 있기 때문에 URL부분만 네이버 검색에 맞게끔 수정.
- 커맨드의 시작은 ‘$’로 시작하며, bot.command 어노테이션이 적용된 부분의 함수명이 커맨드명이 된다.
- ex)
$google 디스코드 → 구글에서 디스코드 검색
$naver 디스코드 → 네이버에서 디스코드 검색
결과




반응형
'Discord > Discord Bot Python' 카테고리의 다른 글
Examples - 디스코드 봇 길드 기본(discord py) (0) | 2023.08.13 |
---|---|
Examples - Ephemeral, Confirm (0) | 2023.07.20 |
Discord 봇 만들기 - Dropdown (0) | 2023.06.16 |
디스코드 봇 개발 시 Error 관련 (7) | 2023.05.30 |
Discord Bot 만들기 - 유튜브 음악 재생 봇 (18) | 2023.05.18 |