日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

telegram 机器人_学习使用Python在Telegram中构建您的第一个机器人

發(fā)布時間:2023/11/29 python 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 telegram 机器人_学习使用Python在Telegram中构建您的第一个机器人 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

telegram 機(jī)器人

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!

想象一下,有一個消息機(jī)器人可以隨時隨地向您發(fā)送隨機(jī)的可愛狗圖像,聽起來很酷吧? 讓我們做一個!

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!

在本教程的最后,您將擁有一個緩解壓力的機(jī)器人,每次您需要時,它都會向您發(fā)送可愛的狗圖像,是的!

入門 (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.

在開始編寫程序之前,我們需要為機(jī)器人生成令牌。 需要令牌來訪問Telegram API,并安裝必要的依賴項。

1.在BotFather中創(chuàng)建一個新的機(jī)器人 (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中制作機(jī)器人,則必須在使用機(jī)器人之前先對其進(jìn)行“注冊”。 當(dāng)我們“注冊”我們的機(jī)器人時,我們將獲得令牌來訪問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.

轉(zhuǎn)到BotFather (如果您在桌面上打開它,請確保您具有Telegram應(yīng)用程序),然后通過發(fā)送/newbot命令來創(chuàng)建新的bot。 按照步驟操作,直到獲得機(jī)器人的用戶名和令牌。 您可以通過訪問以下URL進(jìn)入機(jī)器人: https://telegram.me/YOUR_BOT_USERNAME : https://telegram.me/YOUR_BOT_USERNAME ,令牌應(yīng)如下所示。

704418931:AAEtcZ*************

2.安裝庫 (2. Install the library)

Since we are going to use a library for this tutorial, install it using this command.

由于本教程將使用庫,因此請使用此命令進(jìn)行安裝。

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.

讓我們做第一個機(jī)器人。 當(dāng)我們發(fā)送/bop命令時,該機(jī)器人應(yīng)返回狗圖像。 為此,我們可以使用RandomDog的公共API 幫助我們生成隨機(jī)的狗圖像。

The workflow of our bot is as simple as this:

我們的機(jī)器人的工作流程非常簡單:

access the API -> get the image URL -> send the image訪問API->獲取圖像URL->發(fā)送圖像

1.導(dǎo)入庫 (1. Import the libraries)

First, import all the libraries we need.

首先,導(dǎo)入我們需要的所有庫。

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.

讓我們創(chuàng)建一個獲取URL的函數(shù)。 使用請求庫,我們可以訪問API并獲取json數(shù)據(jù)。

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數(shù)據(jù): https://random.dog/woof.json : https://random.dog/woof.json 。 您將在屏幕上看到以下內(nèi)容:

{“url":"https://random.dog/*****.JPG"}

Get the image URL since we need that parameter to be able to send the image.

獲取圖像URL,因為我們需要該參數(shù)才能發(fā)送圖像。

image_url = contents['url']

Wrap this code into a function called get_url() .

將此代碼包裝到名為get_url()的函數(shù)中。

def get_url():contents = requests.get('https://random.dog/woof.json').json() url = contents['url']return url

3.發(fā)送圖片 (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.

要發(fā)送消息/圖像,我們需要兩個參數(shù),圖像URL和接收者的ID(可以是組ID或用戶ID)。

We can get the image URL by calling our get_url() function.

我們可以通過調(diào)用get_url()函數(shù)來獲取圖像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之后,就該發(fā)送消息,即圖像。

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的函數(shù)中,并確保您的代碼如下所示:

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.

最后,創(chuàng)建另一個名為main函數(shù)以運(yùn)行我們的程序。 不要忘記使用我們在本教程前面生成的令牌來更改 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:

最后,您的代碼應(yīng)如下所示:

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.運(yùn)行程序 (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.

太棒了! 您完成了第一個程序。 現(xiàn)在,讓我們檢查一下是否可行。 保存文件,將其命名為main.py ,然后使用此命令運(yùn)行它。

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轉(zhuǎn)到電報機(jī)器人: https://telegram.me/YOUR_BOT_USERNAME : https://telegram.me/YOUR_BOT_USERNAME 。 發(fā)送/bop命令。 如果一切運(yùn)行正常,機(jī)器人將以隨機(jī)的狗圖像進(jìn)行回復(fù)。 可愛吧?

處理錯誤 (Handling errors)

Great! Now you have a bot that will send you a cute dog image whenever you want.

大! 現(xiàn)在,您有了一個機(jī)器人,可以隨時隨地向您發(fā)送可愛的狗圖像。

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.

還有更多! 隨機(jī)犬 API不僅會生成圖像,還會生成視頻和GIF。 如果我們訪問API并獲得視頻或GIF,則出現(xiàn)錯誤,該漫游器不會將其發(fā)送給您。

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.

讓我們對其進(jìn)行修復(fù),以便該機(jī)器人僅發(fā)送帶有圖片附件的消息。 如果獲得視頻或GIF,則將再次調(diào)用API,直到獲得圖像。

1.使用正則表達(dá)式匹配文件擴(kuò)展名 (1. Match the file extension using regex)

We are going to use a regex to solve this problem.

我們將使用正則表達(dá)式解決此問題。

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.

為了區(qū)分圖像與視頻或GIF,我們可以看一下文件擴(kuò)展名。 我們只需要URL的最后一部分。

https://random.dog/*****.JPG

We need to define, first, what file extensions are allowed in our program.

首先,我們需要定義程序中允許的文件擴(kuò)展名。

allowed_extension = ['jpg','jpeg','png']

Then use the regex to extract the file extension from the URL.

然后使用正則表達(dá)式從URL中提取文件擴(kuò)展名。

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).

使用該代碼,創(chuàng)建一個名為get_image_url()的函數(shù)以迭代URL,直到獲得所需的文件擴(kuò)展名(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:

大! 現(xiàn)在,對于最后一部分,將bop()函數(shù)中的url = get_url()行替換為url = get_url() url = get_image_url() ,您的代碼應(yīng)如下所示:

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.

真好! 一切都應(yīng)該完美運(yùn)行。 您也可以簽出我的GitHub帳戶以獲取代碼。

Finally, congratulations for finishing this tutorial, plus you have a cool Telegram bot now.

最后,恭喜您完成了本教程,并且您現(xiàn)在擁有一個很棒的Telegram機(jī)器人。

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.

如果您認(rèn)為我的代碼或編寫中有任何錯誤,請發(fā)表評論,因為我仍在學(xué)習(xí),并且我希望自己變得更好。

Thank you and good luck practicing! :)

謝謝你,祝你好運(yùn)! :)

翻譯自: https://www.freecodecamp.org/news/learn-to-build-your-first-bot-in-telegram-with-python-4c99526765e4/

telegram 機(jī)器人

總結(jié)

以上是生活随笔為你收集整理的telegram 机器人_学习使用Python在Telegram中构建您的第一个机器人的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。