01 IntroductionWprowadzenie
discord.py is a modern, asynchronous Python library for the Discord API. It's how bots like GiphyFy read messages, register commands, and send files back. If you know a little Python, you already know enough to start.
discord.py to nowoczesna, asynchroniczna biblioteka Pythona do API Discorda. To dzięki niej boty takie jak GiphyFy czytają wiadomości, rejestrują komendy i odsyłają pliki. Jeśli znasz trochę Pythona, masz już wystarczającą wiedzę, by zacząć.
New to Python? Start with Lesson 1: Python basics for bots, then come back here.
Dopiero zaczynasz z Pythonem? Zacznij od Lekcji 1: Podstawy Pythona dla botów, a potem wróć tutaj.
02 Try it liveWypróbuj na żywo
Before the code, get a feel for what a bot does. Click a command below and watch a simulated GiphyFy respond — just like in a real Discord channel.
Zanim przejdziesz do kodu, poczuj, co bot robi. Kliknij komendę poniżej i zobacz, jak symulowane GiphyFy odpowiada — zupełnie jak na prawdziwym kanale Discord.
Each of those is built from a few lines of Python. Let's write them.
Każda z nich powstaje z kilku linijek Pythona. Napiszmy je.
03 SetupPrzygotowanie
- Install Python 3.10+ from python.org.
- Install the library (see the command below).
- Create an application in the Discord Developer Portal and add a Bot.
- Copy the bot token — keep it secret.
- Invite the bot to a test server with the
applications.commandsscope.
- Zainstaluj Pythona 3.10+ ze strony python.org.
- Zainstaluj bibliotekę (zobacz komendę poniżej).
- Utwórz aplikację w Portalu Deweloperskim Discorda i dodaj Bota.
- Skopiuj token bota — trzymaj go w tajemnicy.
- Zaproś bota na serwer testowy z uprawnieniem
applications.commands.
python -m pip install -U discord.py
Keep your token secret. Never hard-code it in your source — anyone who sees it can control your bot. Load it from an environment variable instead (below).
Trzymaj token w tajemnicy. Nigdy nie wpisuj go na stałe w kodzie — kto go zobaczy, przejmie twojego bota. Zamiast tego wczytaj go ze zmiennej środowiskowej (poniżej).
import os
# Read the token from an environment variable, never from the code
bot.run(os.environ["DISCORD_TOKEN"])
04 Your first botTwój pierwszy bot
Here's the smallest complete bot. on_ready runs once the bot connects; we sync the command tree so your slash commands actually appear in Discord.
Oto najmniejszy kompletny bot. on_ready uruchamia się po połączeniu bota; wywołujemy sync na drzewie komend, aby twoje komendy slash faktycznie pojawiły się w Discordzie.
import discord
from discord.ext import commands
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
await bot.tree.sync()
print(f"Logged in as {bot.user}")
bot.run("YOUR_TOKEN") # better: os.environ["DISCORD_TOKEN"]
Syncing can take a moment to show up in Discord. While developing, many people sync to a single test guild for instant updates.
Synchronizacja może chwilę potrwać, zanim komendy pojawią się w Discordzie. Podczas tworzenia wiele osób synchronizuje komendy z jednym serwerem testowym, by widzieć zmiany natychmiast.
05 Slash commandsKomendy slash
Slash commands are the modern way to add commands. GiphyFy's /giphyfy works exactly like this — a command with typed options. (Try the /hello button in the simulator above.)
Komendy slash to nowoczesny sposób dodawania komend. /giphyfy w GiphyFy działa dokładnie tak — to komenda z typowanymi opcjami. (Wypróbuj przycisk /hello w symulatorze powyżej.)
import discord
@bot.tree.command(name="hello", description="Say hello")
@discord.app_commands.describe(name="Who to greet")
async def hello(interaction: discord.Interaction, name: str):
await interaction.response.send_message(f"Hello, {name}!")
Options with choicesOpcje z listą wyboru
Want a dropdown of fixed options? Use choices. GiphyFy's quality setting (High / Sharp) is exactly this.
Chcesz rozwijaną listę stałych opcji? Użyj choices. Ustawienie quality (High / Sharp) w GiphyFy to dokładnie to.
import discord
@bot.tree.command(name="convert", description="Pick a quality")
@discord.app_commands.choices(quality=[
discord.app_commands.Choice(name="High (smooth)", value="high"),
discord.app_commands.Choice(name="Sharp (no dithering)", value="sharp"),
])
async def convert(interaction: discord.Interaction,
quality: discord.app_commands.Choice[str]):
await interaction.response.send_message(f"Quality: {quality.value}")
06 Context-menu commandsKomendy z menu kontekstowego
Context-menu commands appear when you right-click a message (the Apps menu). This is exactly how GiphyFy's 📸 Screenshot GIF works — it receives the message you clicked. (Try the "Quote a message" button above.)
Komendy z menu kontekstowego pojawiają się po kliknięciu wiadomości prawym przyciskiem (menu Aplikacje). Dokładnie tak działa 📸 Screenshot GIF w GiphyFy — otrzymuje wiadomość, którą kliknięto. (Wypróbuj przycisk „Cytuj wiadomość” powyżej.)
import discord
@bot.tree.context_menu(name="Quote message")
async def quote(interaction: discord.Interaction, message: discord.Message):
await interaction.response.send_message(f"> {message.content}")
07 Sending files (GIFs)Wysyłanie plików (GIF-y)
To send a file back — like a generated GIF — wrap it in discord.File. GiphyFy builds a GIF in memory and sends it the same way, then attaches a delete button. (That's the /send_gif button above.)
Aby odesłać plik — np. wygenerowany GIF — opakuj go w discord.File. GiphyFy tworzy GIF w pamięci i wysyła go w ten sam sposób, a następnie dołącza przycisk usuwania. (To przycisk /send_gif powyżej.)
import discord
@bot.tree.command(name="send_gif", description="Send a GIF file")
async def send_gif(interaction: discord.Interaction):
file = discord.File("output.gif", filename="output.gif")
await interaction.response.send_message(file=file)
Want to generate images in code, the way GiphyFy does? That's Lesson 4: Images & GIFs with Pillow.
Chcesz generować obrazy w kodzie, tak jak robi to GiphyFy? To Lekcja 4: Obrazy i GIF-y z Pillow.
08 Test yourselfSprawdź się
Three quick questions. Pick an answer to see if you're right — and why.
Trzy szybkie pytania. Wybierz odpowiedź, aby sprawdzić, czy jest poprawna — i dlaczego.
@bot.tree.command registers an application (slash) command on the bot's command tree.@bot.tree.command rejestruje komendę aplikacji (slash) w drzewie komend bota.context_menu commands appear in the right-click Apps menu and receive the clicked message.Komendy context_menu pojawiają się w menu Aplikacje po kliknięciu PPM i otrzymują wskazaną wiadomość.