# Discord Bot講義-6 ## 學習內容 1. 使用python爬蟲從網站獲得天氣資料 2. 增加機器人查詢任何地點天氣的功能 ## 使用python爬蟲從網站獲得天氣資料 Python爬蟲是一種程式工具,是透過爬蟲(Spider)模擬使用者瀏覽目標網頁,自動抓取網頁中的資料。Python爬蟲可以有效地針對資料類別與名稱,快速擷取使用者想要的資訊。 我們使用的天氣網站是[OpenWeather](https://openweathermap.org/) 需要先[註冊](https://home.openweathermap.org/users/sign_up)並驗證電子郵件,然後[查看API金鑰](https://home.openweathermap.org/api_keys)並複製API金鑰。  如果要使用Python爬蟲,需要先使用CMD安裝**requests**函式庫⬇️ ```bat= pip install requests ``` 接著打入以下程式碼⬇️(記得將Weather_api 替換成你自己的) ```py= import requests 城市 = input("請輸入城市名稱:") Weather_api = "XXXXXXXXXXXXXXXXXXX" 網址 = f"https://api.openweathermap.org/data/2.5/weather?q={城市}&appid={Weather_api}" 天氣資料 = requests.get(網址) 氣溫 = int(天氣資料.json()["main"]["temp"]-273.15) 濕度 = int(天氣資料.json()["main"]["humidity"]) print(f"{城市}目前的氣溫是{氣溫}℃、濕度是{濕度}%") ``` 這樣就可以輸入城市查詢溫度 ## 增加機器人查詢任何地點天氣的功能 如果要講將此功能加到Discord Bot 裡面需要使用指令的方式獲得溫度 ```py= import discord import requests bot = discord.Bot(intents=discord.Intents.all()) Weather_api = "XXXXXXXXXXXXXXXXXXX" @bot.event async def on_ready(): print(f"「{bot.user}」已登入") @bot.command() async def weather(ctx,城市:str): 網址 = f"https://api.openweathermap.org/data/2.5/weather?q={城市}&appid={Weather_api}" 天氣資料 = requests.get(網址) 氣溫 = int(天氣資料.json()["main"]["temp"]-273.15) 濕度 = int(天氣資料.json()["main"]["humidity"]) await ctx.respond(f"{城市}目前的氣溫是{氣溫}℃、濕度是{濕度}%") 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