# Discord Bot講義 -5 ## 學習內容 1. 使用datetime獲得現在時間 2. 增加機器人查詢時間的功能 ## 使用datetime獲得現在時間 Python 的內建函式庫已經包含datetime, 所以只要import datetime就能使用,不需額外安裝套件。 首先輸入以下程式碼⬇️ ```py= import datetime now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8))) print(f'現在是 {now.strftime("%m 月 %d 日 %H點%M分%S秒")}') ``` ## 增加機器人查詢時間的功能 我們要使用斜線指令的方式查詢時間 所以要輸入以下程式碼⬇️ ```py= import discord import datetime bot = discord.Bot(intents=discord.Intents.all()) @bot.event async def on_ready(): print(f"「{bot.user}」已登入") @bot.slash_command(description="回答時間") async def time(ctx): now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8))) await ctx.respond(f'現在是 {now.strftime("%m 月 %d 日 %H點%M分%S秒")}') bot.run("bot_token") ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up