discord.py 프로젝트 3: 임의 개 사진! 🐕
이 게시물을 마치면 다음 방법을 알게 됩니다.
footer
및 image
필드를 사용하십시오. 명령이 사용되는 곳마다 다음과 유사한 포함을 보냅니다.
시작하려면 봇을 초기화해야 합니다. 이번에는 다시 command.Bot을 사용합니다. 하나의 기능인 dog 명령이 있기 때문입니다.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!")
@client.event
async def on_ready():
print("Ready")
client.run('token')
지금까지 접두사가
!
인 봇이 있습니다. 준비가 되면 콘솔에 Ready
가 인쇄됩니다!이제 개 명령을 만들어 봅시다!
aiohttp
및 json
필요한 모듈을 가져오는 것으로 시작하겠습니다.Note: type
pip install aiohttp
before running the code!
import discord
from discord.ext import commands
import aiohttp
client = commands.Bot(command_prefix="!")
@client.event
async def on_ready():
print("Ready")
client.run('token')
이제 다음 명령을 생성합니다.
import discord
from discord.ext import commands
import aiohttp
client = commands.Bot(command_prefix="!")
@client.event
async def on_ready():
print("Ready")
@client.command()
async def dog(ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://some-random-api.ml/img/dog')
dogjson = await request.json()
client.run('token')
이제
dogjson
는 별칭 목록인 사전을 포함하는 변수가 됩니다.사전이 무엇인가요?
사전을 사용하는 위치의 예는 대체 암호입니다. a1z26을 만들 수 있습니다(여기서
a
는 1
가 되고, b
는 2
가 됩니다. 등). 따라서 사전을 쉽게 만들 수 있습니다.azdict = {'a':'1', 'b':'2', 'c':'3'}
이제 이것을 사용하여 다음을 대체할 수 있습니다.
my_string = "abc abc"
for index, letter in enumerate(my_string): # Iterate through each letter
if letter in azdict.keys(): # iterate through the key and not the value (e.g. a, b, c, and so on)
my_string[index] = azdict[letter]
print(my_string)
>> '123 123'
사전이 다음과 같이 구성되어 있음을 알고 있습니다.
우리는
link
키를 사용하고 싶다는 것을 알고 있습니다.이제 할 수 있습니다.
import discord
from discord.ext import commands
import aiohttp
client = commands.Bot(command_prefix="!")
@client.event
async def on_ready():
print("Ready")
@client.command()
async def dog(ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://some-random-api.ml/img/dog') # Make a request
dogjson = await request.json() # Convert it to a JSON dictionary
embed = discord.Embed(title="Doggo!", color=discord.Color.purple()) # Create embed
embed.set_image(url=dogjson['link']) # Set the embed image to the value of the 'link' key
await ctx.send(embed=embed) # Send the embed
client.run('token')
이제 bot 명령을 사용하면 다음과 같은 결과가 표시됩니다.
이제 개 팩트도 보내도록 합시다! SomeRandomAPI에는 개에 대한 임의의 사실을 얻을 수 있는 개 사실 엔드포인트도 있습니다!
@client.command()
async def dog(ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://some-random-api.ml/img/dog')
dogjson = await request.json()
# This time we'll get the fact request as well!
request2 = await session.get('https://some-random-api.ml/facts/dog')
factjson = await request2.json()
embed = discord.Embed(title="Doggo!", color=discord.Color.purple())
embed.set_image(url=dogjson['link'])
embed.set_footer(text=factjson['fact'])
await ctx.send(embed=embed)
그러면 다음이 생성됩니다!
질문이 있으십니까? 다음 게시물에 대해 수행할 작업에 대한 제안이 있습니까?
댓글로 알려주시면 답변해드리겠습니다!
Reference
이 문제에 관하여(discord.py 프로젝트 3: 임의 개 사진! 🐕), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/mikeywastaken/discord-py-project-3-random-dog-pics-3b4a텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)