---
title: "[社課共筆]20251127-Discord Bot 入門指南"
description:
tags:
- 社課
- 共筆
---
:::success
# Discord Bot 入門指南
**時間:** 2025/11/27(星期四)18:30 ~ 20:30
**地點:** 挺生大樓 A3-200 教室
**簡報:** [連結](https://slides.com/speedcubing/discord/)
**回饋表單:** [連結](https://forms.gle/PAeTW1YEZ81MqSae6)

:::
> 從這裡開始
[toc]
### up runnin
```py=
import discord
import os
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
bot = discord.Bot(intents=discord.Intents.all())
if __name__ == "__main__":
bot.run(TOKEN)
```
### events
```py
@bot.event
async def on_ready():
print("The bot is ready.")
@bot.event
async def on_member_join(member: discord.Member):
await bot.get_channel(1443555690307260507).send("welcome")
@bot.event
async def on_message(message: discord.Message):
if message.author == bot.user:
return
await message.channel.send("shut up")
```
### slash command
```py
@bot.slash_command()
async def ping(ctx):
await ctx.respond("pong")
```
```py
@bot.slash_command(name="ping")
async def ping_command(ctx):
await ctx.respond("pong")
```
(optional param)
```py
@bot.slash_command()
async def ping(ctx, text: str = "hello"):
await ctx.respond("pong " + text)
```
(desc)
```py
from discord import Option
```
### Embed Message
```py
# import datetime
@bot.slash_command()
async def ping(ctx):
embed = discord.Embed(
title="Title",
description="Description",
color=discord.Color.red(),
url="https://github.com/"),
# timestamp=datetime.datetime.now(datetime.UTC)
embed.add_field(name="Name", value="value")
await ctx.respond(embed=embed)
```
### btn
```py
@bot.event
async def on_message(message: discord.Message):
if message.author == bot.user:
return
await message.channel.send(content="shut up", view=Test())
class Test(discord.ui.View):
@discord.ui.button(label="Click me",style=discord.ButtonStyle.primary)
async def onClick(self, button, interaction: discord.Interaction):
await interaction.response.send_message("hi")
```
```py
class TestView(discord.ui.View):
def __init__(self, id1, id2, n1, n2):
super().__init__()
self.players = [id1, id2]
self.names = [n1, n2]
self.choices = {}
async def handle(self, interaction, choice):
if interaction.user.id in self.choices:
await interaction.response.send_message("選過了啦", ephemeral=True)
return
if interaction.user.id not in self.players:
await interaction.response.send_message("關你什麼事?", ephemeral=True)
return
if len(self.choices) != 2:
self.choices[interaction.user.id] = choice
await interaction.response.send_message("Waiting...", ephemeral=True)
if len(self.choices) == 2:
p1, p2 = self.players
c1, c2 = self.choices[p1], self.choices[p2]
if c1 == c2:
result = "Draw!"
elif (c1 == "剪刀" and c2 == "布") or \
(c1 == "石頭" and c2 == "剪刀") or \
(c1 == "布" and c2 == "石頭"):
result = f"{self.names[0]} Win!"
else:
result = f"{self.names[1]} Win!"
await interaction.message.channel.send(
f"**Game Over.**\n"
f"{self.names[0]} 出 **{c1}**\n"
f"{self.names[1]} 出 **{c2}**\n"
f"Result = {result}"
)
self.stop()
@discord.ui.button(label="剪刀", style=discord.ButtonStyle.primary)
async def click1(self, button: discord.ui.Button, interaction: discord.Interaction):
await self.handle(interaction, "剪刀")
@discord.ui.button(label="石頭", style=discord.ButtonStyle.primary)
async def click2(self, button: discord.ui.Button, interaction: discord.Interaction):
await self.handle(interaction, "石頭")
@discord.ui.button(label="布", style=discord.ButtonStyle.primary)
async def click3(self, button: discord.ui.Button, interaction: discord.Interaction):
await self.handle(interaction, "布")
@bot.slash_command(name="rcs")
async def ping_command(ctx, target: discord.Member):
await ctx.respond(f"{target.name} vs {ctx.author.name}", view=TestView(ctx.author.id, target.id, ctx.author.name, target.name))
```
```py
@bot.slash_command(name="dns")
async def dns_command(
ctx: discord.ApplicationContext,
text: str
):
orig = text
dns_list = []
dns_type = []
while True:
try:
cname_records = dns.resolver.resolve(text, "CNAME")
if cname_records:
for r in cname_records:
print("CNAME Record found: " + str(r))
dns_list.append(str(r))
dns_type.append("CNAME")
text = str(r.target)[:-1]
else:
break
except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
break
a_records = dns.resolver.resolve(text)
if a_records:
for r in a_records:
print("A Record found: " + str(r)[:-1])
dns_list.append(str(r))
dns_type.append("A")
text = str(a_records[0])
embed = discord.Embed(
title=f"DNS Query: {orig}",
color=discord.Color.from_rgb(0xAA, 0,0)
)
if dns_list:
i = 0
for record in dns_list:
embed.add_field(name=dns_type[i], value=record, inline=False)
i = i + 1
await ctx.respond(embed=embed)
```