01 Variables & typesZmienne i typy
A variable is a name for a value. Python figures out the type for you. The four you'll meet most in a bot:
Zmienna to nazwa dla wartości. Python sam rozpoznaje typ. Cztery, które spotkasz najczęściej w bocie:
name = "GiphyFy" # str (text)
fps = 8 # int (whole number)
ratio = 1.5 # float (decimal)
formats = ["png", "mp4"] # list (ordered collection)
You'll pass values like these around as command options — for example a quality string or an fps number.
Takie wartości będziesz przekazywać jako opcje komend — na przykład tekst quality albo liczbę fps.
02 FunctionsFunkcje
A function is reusable block of code. You give it inputs (parameters) and it can return a value. Every command you write is a function.
Funkcja to wielokrotnie używalny blok kodu. Podajesz jej dane wejściowe (parametry), a ona może zwrócić wartość. Każda komenda, którą napiszesz, jest funkcją.
def greet(user):
return f"Hello, {user}!"
print(greet("Kai")) # Hello, Kai!
03 async / awaitasync / await
Bots spend most of their time waiting — for Discord, for the network, for a file to convert. async lets a bot wait for one thing without freezing everything else. You'll see two keywords:
Boty spędzają większość czasu, czekając — na Discord, na sieć, na konwersję pliku. async pozwala botowi czekać na jedną rzecz, nie zamrażając całej reszty. Zobaczysz dwa słowa kluczowe:
async def— defines a function that can pause and resume.await— pauses until the awaited thing is done, then continues.
async def— definiuje funkcję, która może się wstrzymać i wznowić.await— wstrzymuje, aż dana rzecz się zakończy, a potem kontynuuje.
import asyncio
async def make_gif():
await asyncio.sleep(1) # pretend the work takes a second
return "done"
In discord.py, command handlers are async def and you await things like interaction.response.send_message(...). That's 90% of the async you need.
W discord.py funkcje obsługujące komendy to async def, a rzeczy takie jak interaction.response.send_message(...) poprzedzasz await. To 90% asynchroniczności, której potrzebujesz.
04 f-stringsf-stringi
An f-string drops variables straight into text. Put an f before the quotes and wrap variables in { }. Bots use these constantly to build replies.
f-string wstawia zmienne prosto do tekstu. Dodaj f przed cudzysłowem i otocz zmienne nawiasami { }. Boty używają ich bez przerwy do budowania odpowiedzi.
user = "Kai"
count = 3
print(f"{user} made {count} GIFs") # Kai made 3 GIFs
05 Test yourselfSprawdź się
await do?Co robi await?await waits for an async operation to complete without blocking the rest of the bot.await czeka na zakończenie operacji asynchronicznej, nie blokując reszty bota.f prefix and { } around the variable.f-string potrzebuje przedrostka f i nawiasów { } wokół zmiennej.