telegram 機器人_學習使用Python在Telegram中構建您的第一個機器人

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_USERNAMEhttps://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 機器人

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/392542.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/392542.shtml
英文地址,請注明出處:http://en.pswp.cn/news/392542.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

判斷輸入的字符串是否為回文_刷題之路(九)--判斷數字是否回文

Palindrome Number問題簡介:判斷輸入數字是否是回文,不是返回0,負數返回0舉例:1:輸入: 121輸出: true2:輸入: -121輸出: false解釋: 回文為121-,所以負數都不符合3:輸入: 10輸出: false解釋: 倒序為01,不符合要求解法一:這道題比較…

python + selenium 搭建環境步驟

介紹在windows下,selenium python的安裝以及配置。1、首先要下載必要的安裝工具。 下載python,我安裝的python3.0版本,根據你自己的需要安裝下載setuptools下載pip(python的安裝包管理工具) 配置系統的環境變量 python,需要配置2個環境變量C:\Users\AppD…

VirtualBox 虛擬機復制

本文簡單講兩種情況下的復制方式 1 跨電腦復制 2 同一virtrul box下 虛擬機復制 ---------------------------------------------- 1 跨電腦復制 a虛擬機 是老的虛擬機 b虛擬機 是新的虛擬機 新虛擬機b 新建, 點擊下一步會生成 相應的文件夾 找到老虛擬機a的 vdi 文…

javascript實用庫_編寫實用JavaScript的實用指南

javascript實用庫by Nadeesha Cabral通過Nadeesha Cabral 編寫實用JavaScript的實用指南 (A practical guide to writing more functional JavaScript) Functional programming is great. With the introduction of React, more and more JavaScript front-end code is being …

數據庫數據過長避免_為什么要避免使用商業數據科學平臺

數據庫數據過長避免讓我們從一個類比開始 (Lets start with an analogy) Stick with me, I promise it’s relevant.堅持下去,我保證這很重要。 If your selling vegetables in a grocery store your business value lies in your loyal customers and your positi…

mysql case快捷方法_MySQL case when使用方法實例解析

首先我們創建數據庫表: CREATE TABLE t_demo (id int(32) NOT NULL,name varchar(255) DEFAULT NULL,age int(2) DEFAULT NULL,num int(3) DEFAULT NULL,PRIMARY KEY (id)) ENGINEInnoDB DEFAULT CHARSETutf8;插入數據:INSERT INTO t_demo VALUES (1, 張…

【~~~】POJ-1006

很簡單的一道題目,但是引出了很多知識點。 這是一道中國剩余問題,先貼一下1006的代碼。 #include "stdio.h" #define MAX 21252 int main() { int p , e , i , d , n 1 , days 0; while(1) { scanf("%d %d %d %d",&p,&e,&…

Java快速掃盲指南

文章轉自:https://segmentfault.com/a/1190000004817465#articleHeader22 JDK,JRE和 JVM 的區別 JVM:java 虛擬機,負責將編譯產生的字節碼轉換為特定機器代碼,實現一次編譯多處執行; JRE:java運…

xcode擴展_如何將Xcode插件轉換為Xcode擴展名

xcode擴展by Khoa Pham通過Khoa Pham 如何將Xcode插件轉換為Xcode擴展名 (How to convert your Xcode plugins to Xcode extensions) Xcode is an indispensable IDE for iOS and macOS developers. From the early days, the ability to build and install custom plugins ha…

leetcode 861. 翻轉矩陣后的得分(貪心算法)

有一個二維矩陣 A 其中每個元素的值為 0 或 1 。 移動是指選擇任一行或列,并轉換該行或列中的每一個值:將所有 0 都更改為 1,將所有 1 都更改為 0。 在做出任意次數的移動后,將該矩陣的每一行都按照二進制數來解釋,矩…

數據分析團隊的價值_您的數據科學團隊的價值

數據分析團隊的價值This is the first article in a 2-part series!!這是分兩部分的系列文章中的第一篇! 組織數據科學 (Organisational Data Science) Few would argue against the importance of data in today’s highly competitive corporate world. The tech…

mysql 保留5位小數_小猿圈分享-MySQL保留幾位小數的4種方法

今天小猿圈給大家分享的是MySQL使用中4種保留小數的方法,希望可以幫助到大家,讓大家的工作更加方便。1 round(x,d)用于數據x的四舍五入, round(x) ,其實就是round(x,0),也就是默認d為0;這里有個值得注意的地方是,d可以是負數&…

leetcode 842. 將數組拆分成斐波那契序列(回溯算法)

給定一個數字字符串 S&#xff0c;比如 S “123456579”&#xff0c;我們可以將它分成斐波那契式的序列 [123, 456, 579]。 形式上&#xff0c;斐波那契式序列是一個非負整數列表 F&#xff0c;且滿足&#xff1a; 0 < F[i] < 2^31 - 1&#xff0c;&#xff08;也就是…

博主簡介

面向各層次&#xff08;從中學到博士&#xff09;提供GIS和Python GIS案例實驗實習培訓&#xff0c;以解決問題為導向&#xff0c;以項目實戰為主線&#xff0c;以科學研究為思維&#xff0c;不講概念&#xff0c;不局限理論&#xff0c;簡單照做&#xff0c;即學即會。 研究背…

自定義Toast 很簡單就可以達到一些對話框的效果 使用起來很方便

自定義一個layout布局 通過toast.setView 設置布局彈出一些警示框 等一些不會改變的提示框 很方便public class CustomToast {public static void showUSBToast(Context context) {//加載Toast布局 View toastRoot LayoutInflater.from(context).inflate(R.layout.toas…

微信小程序阻止冒泡點擊_微信小程序bindtap事件與冒泡阻止詳解

bindtap就是點擊事件在.wxml文件綁定:cilck here在一個組件的屬性上添加bindtap并賦予一個值(一個函數名)當點擊該組件時, 會觸發相應的函數執行在后臺.js文件中定義tapMessage函數://index.jsPage({data: {mo: Hello World!!,userid : 1234,},// 定義函數tapMessage: function…

同情機器人_同情心如何幫助您建立更好的工作文化

同情機器人Empathy is one of those things that can help in any part of life whether it’s your family, friends, that special person and even also at work. Understanding what empathy is and how it effects people took me long time. I struggle with human inter…

數據庫課程設計結論_結論

數據庫課程設計結論When writing about learning or breaking into data science, I always advise building projects.在撰寫有關學習或涉足數據科學的文章時&#xff0c;我總是建議構建項目。 It is the best way to learn as well as showcase your skills.這是學習和展示技…

mongo基本使用方法

mongo與關系型數據庫的概念對比&#xff0c;區分大小寫&#xff0c;_id為主鍵。 1.數據庫操作 >show dbs #查看所有數據庫 >use dbname #創建和切換數據庫&#xff08;如果dbname存在則切換到該數據庫&#xff0c;不存在則創建并切換到該數據庫&#xff1b;新創建的…

leetcode 62. 不同路徑(dp)

一個機器人位于一個 m x n 網格的左上角 &#xff08;起始點在下圖中標記為“Start” &#xff09;。 機器人每次只能向下或者向右移動一步。機器人試圖達到網格的右下角&#xff08;在下圖中標記為“Finish”&#xff09;。 問總共有多少條不同的路徑&#xff1f; 例如&…