telegram 機器人
Imagine this, there is a message bot that will send you a random cute dog image whenever you want, sounds cool right? Let’s make one!
想象一下,有一個消息機器人可以隨時隨地向您發送隨機的可愛狗圖像,聽起來很酷吧? 讓我們做一個!
For this tutorial, we are going to use Python 3, python-telegram-bot, and public API RandomDog.
在本教程中,我們將使用Python 3, python-telegram-bot和公共API RandomDog 。
At the end of this tutorial, you will have a stress relieving bot that will send you cute dog images every time you need it, yay!
在本教程的最后,您將擁有一個緩解壓力的機器人,每次您需要時,它都會向您發送可愛的狗圖像,是的!
入門 (Getting started)
Before we start to write the program, we need to generate a token for our bot. The token is needed to access the Telegram API, and install the necessary dependencies.
在開始編寫程序之前,我們需要為機器人生成令牌。 需要令牌來訪問Telegram API,并安裝必要的依賴項。
1.在BotFather中創建一個新的機器人 (1. Create a new bot in BotFather)
If you want to make a bot in Telegram, you have to “register” your bot first before using it. When we “register” our bot, we will get the token to access the Telegram API.
如果要在Telegram中制作機器人,則必須在使用機器人之前先對其進行“注冊”。 當我們“注冊”我們的機器人時,我們將獲得令牌來訪問Telegram API。
Go to the BotFather (if you open it in desktop, make sure you have the Telegram app), then create new bot by sending the /newbot
command. Follow the steps until you get the username and token for your bot. You can go to your bot by accessing this URL: https://telegram.me/YOUR_BOT_USERNAME
and your token should looks like this.
轉到BotFather (如果您在桌面上打開它,請確保您具有Telegram應用程序),然后通過發送/newbot
命令來創建新的bot。 按照步驟操作,直到獲得機器人的用戶名和令牌。 您可以通過訪問以下URL進入機器人: https://telegram.me/YOUR_BOT_USERNAME
: https://telegram.me/YOUR_BOT_USERNAME
,令牌應如下所示。
704418931:AAEtcZ*************
2.安裝庫 (2. Install the library)
Since we are going to use a library for this tutorial, install it using this command.
由于本教程將使用庫,因此請使用此命令進行安裝。
pip3 install python-telegram-bot
If the library is successfully installed, then we are good to go.
如果該庫已成功安裝,那么我們很好。
編寫程序 (Write the program)
Let’s make our first bot. This bot should return a dog image when we send the /bop
command. To be able to do this, we can use the public API from RandomDog to help us generate random dog images.
讓我們做第一個機器人。 當我們發送/bop
命令時,該機器人應返回狗圖像。 為此,我們可以使用RandomDog的公共API 幫助我們生成隨機的狗圖像。
The workflow of our bot is as simple as this:
我們的機器人的工作流程非常簡單:
access the API -> get the image URL -> send the image
訪問API->獲取圖像URL->發送圖像
1.導入庫 (1. Import the libraries)
First, import all the libraries we need.
首先,導入我們需要的所有庫。
from telegram.ext import Updater, CommandHandler
import requests
import re
2.訪問API并獲取圖像URL (2. Access the API and get the image URL)
Let’s create a function to get the URL. Using the requests library, we can access the API and get the json data.
讓我們創建一個獲取URL的函數。 使用請求庫,我們可以訪問API并獲取json數據。
contents = requests.get('https://random.dog/woof.json').json()
You can check the json data by accessing that URL: https://random.dog/woof.json
in your browser. You will see something like this on your screen:
您可以通過在瀏覽器中訪問以下URL來檢查json數據: https://random.dog/woof.json
: https://random.dog/woof.json
。 您將在屏幕上看到以下內容:
{“url":"https://random.dog/*****.JPG"}
Get the image URL since we need that parameter to be able to send the image.
獲取圖像URL,因為我們需要該參數才能發送圖像。
image_url = contents['url']
Wrap this code into a function called get_url()
.
將此代碼包裝到名為get_url()
的函數中。
def get_url():contents = requests.get('https://random.dog/woof.json').json() url = contents['url']return url
3.發送圖片 (3. Send the image)
To send a message/image we need two parameters, the image URL and the recipient’s ID — this can be group ID or user ID.
要發送消息/圖像,我們需要兩個參數,圖像URL和接收者的ID(可以是組ID或用戶ID)。
We can get the image URL by calling our get_url()
function.
我們可以通過調用get_url()
函數來獲取圖像URL。
url = get_url()
Get the recipient’s ID using this code:
使用以下代碼獲取收件人的ID:
chat_id = update.message.chat_id
After we get the image URL and the recipient’s ID, it’s time to send the message, which is an image.
獲取圖像URL和收件人的ID之后,就該發送消息,即圖像。
bot.send_photo(chat_id=chat_id, photo=url)
Wrap that code in a function called bop
, and make sure your code looks like this:
將該代碼包裝在一個名為bop
的函數中,并確保您的代碼如下所示:
def bop(bot, update):url = get_url()chat_id = update.message.chat_idbot.send_photo(chat_id=chat_id, photo=url)
4. Main program
(4. Main program
)
Lastly, create another function called main
to run our program. Don’t forget to change YOUR_TOKEN
with the token that we generated earlier in this tutorial.
最后,創建另一個名為main
函數以運行我們的程序。 不要忘記使用我們在本教程前面生成的令牌來更改 YOUR_TOKEN
。
def main():updater = Updater('YOUR_TOKEN')dp = updater.dispatcherdp.add_handler(CommandHandler('bop',bop))updater.start_polling()updater.idle()if __name__ == '__main__':main()
At the end your code should look like this:
最后,您的代碼應如下所示:
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
import requests
import redef get_url():contents = requests.get('https://random.dog/woof.json').json() url = contents['url']return urldef bop(bot, update):url = get_url()chat_id = update.message.chat_idbot.send_photo(chat_id=chat_id, photo=url)def main():updater = Updater('YOUR_TOKEN')dp = updater.dispatcherdp.add_handler(CommandHandler('bop',bop))updater.start_polling()updater.idle()if __name__ == '__main__':main()
5.運行程序 (5. Run the program)
Awesome! You finished your first program. Now let’s check if it works. Save the file, name it main.py
, then run it using this command.
太棒了! 您完成了第一個程序。 現在,讓我們檢查一下是否可行。 保存文件,將其命名為main.py
,然后使用此命令運行它。
python3 main.py
Go to your telegram bot by accessing this URL: https://telegram.me/YOUR_BOT_USERNAME
. Send the /bop
command. If everything runs perfectly the bot will reply with a random dog image. Cute right?
通過訪問以下URL轉到電報機器人: https://telegram.me/YOUR_BOT_USERNAME
: https://telegram.me/YOUR_BOT_USERNAME
。 發送/bop
命令。 如果一切運行正常,機器人將以隨機的狗圖像進行回復。 可愛吧?
處理錯誤 (Handling errors)
Great! Now you have a bot that will send you a cute dog image whenever you want.
大! 現在,您有了一個機器人,可以隨時隨地向您發送可愛的狗圖像。
There is more! The RandomDog API not only generates images, but also videos and GIFs. If we access the API and we get a video or GIF, there is an error and the bot won’t send it to you.
還有更多! 隨機犬 API不僅會生成圖像,還會生成視頻和GIF。 如果我們訪問API并獲得視頻或GIF,則出現錯誤,該漫游器不會將其發送給您。
Let’s fix this so the bot will only send a message with an image attachment. If we get a video or GIF then we will call the API again until we get an image.
讓我們對其進行修復,以便該機器人僅發送帶有圖片附件的消息。 如果獲得視頻或GIF,則將再次調用API,直到獲得圖像。
1.使用正則表達式匹配文件擴展名 (1. Match the file extension using regex)
We are going to use a regex to solve this problem.
我們將使用正則表達式解決此問題。
To distinguish an image from video or GIF, we can take a look at the file extension. We only need the last part of our URL.
為了區分圖像與視頻或GIF,我們可以看一下文件擴展名。 我們只需要URL的最后一部分。
https://random.dog/*****.JPG
We need to define, first, what file extensions are allowed in our program.
首先,我們需要定義程序中允許的文件擴展名。
allowed_extension = ['jpg','jpeg','png']
Then use the regex to extract the file extension from the URL.
然后使用正則表達式從URL中提取文件擴展名。
file_extension = re.search("([^.]*)$",url).group(1).lower()
Using that code, make a function called get_image_url()
to iterate the URL until we get the file extension that we want (jpg,jpeg,png).
使用該代碼,創建一個名為get_image_url()
的函數以迭代URL,直到獲得所需的文件擴展名(jpg,jpeg,png)。
def get_image_url():allowed_extension = ['jpg','jpeg','png']file_extension = ''while file_extension not in allowed_extension:url = get_url()file_extension = re.search("([^.]*)$",url).group(1).lower()return url
2.修改您的代碼 (2. Modify your code)
Great! Now for the last part, replace the url = get_url()
line in the bop()
function with url = get_image_url()
, and your code should look like this:
大! 現在,對于最后一部分,將bop()
函數中的url = get_url()
行替換為url = get_url()
url = get_image_url()
,您的代碼應如下所示:
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
import requests
import redef get_url():contents = requests.get('https://random.dog/woof.json').json() url = contents['url']return urldef get_image_url():allowed_extension = ['jpg','jpeg','png']file_extension = ''while file_extension not in allowed_extension:url = get_url()file_extension = re.search("([^.]*)$",url).group(1).lower()return urldef bop(bot, update):url = get_image_url()chat_id = update.message.chat_idbot.send_photo(chat_id=chat_id, photo=url)def main():updater = Updater('YOUR_TOKEN')dp = updater.dispatcherdp.add_handler(CommandHandler('bop',bop))updater.start_polling()updater.idle()if __name__ == '__main__':main()
Nice! Everything should run perfectly. You can also check out my GitHub account to get the code.
真好! 一切都應該完美運行。 您也可以簽出我的GitHub帳戶以獲取代碼。
Finally, congratulations for finishing this tutorial, plus you have a cool Telegram bot now.
最后,恭喜您完成了本教程,并且您現在擁有一個很棒的Telegram機器人。
Please leave a comment if you think there are any errors in my code or writing, because I’m still learning and I want to get better.
如果您認為我的代碼或編寫中有任何錯誤,請發表評論,因為我仍在學習,并且我希望自己變得更好。
Thank you and good luck practicing! :)
謝謝你,祝你好運! :)
翻譯自: https://www.freecodecamp.org/news/learn-to-build-your-first-bot-in-telegram-with-python-4c99526765e4/
telegram 機器人