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 机器人

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

  1. 学python后做什么工作好_学习完Python课程后可以做什么工作?

    Python作为人工智能.大数据的首选编程语言,也是进入编程世界的理想选择,已经成为了大家都在追求学习的语言,那么学习Python之后到底可以做什么呢?为您详细的介绍一下. 什么是Python?Pyt ...

  2. 乐高收割机器人_学习乐高机器人编程,孩子到底收获了什么?

    孩子是每个家庭的希望,教育影响着孩子的未来.面对各种辅导班兴趣班,家长们一定会感觉到眼花缭乱.相信对于每一位家长来说,报课外班最关心的问题就是在孩子到底在这里可以收获什么?今天小贝来告诉您,在&quo ...

  3. word2vec python实现_教程 | 在Python和TensorFlow上构建Word2Vec词嵌入模型

    原标题:教程 | 在Python和TensorFlow上构建Word2Vec词嵌入模型 选自adventuresinmachinelearning 参与:李诗萌.刘晓坤 本文详细介绍了 word2ve ...

  4. python 矩阵运算 for循环_如何用 Python 科学计算中的矩阵替代循环

    展开全部 因为在Mathematica中使用循环确实是低效的.32313133353236313431303231363533e78988e69d8331333361313961..... 深层次的原 ...

  5. python关键词提取_如何从Python格式字符串中提取关键字? - python

    我想在API中提供自动字符串格式,例如: my_api("path/to/{self.category}/{self.name}", ...) 可以替换为格式化字符串中标注的属性值 ...

  6. python中的func函数_如何解释python func函数中的n?

    Func函数第一次了解知道是学习闭包章节中的,而后,因为函数本身存在的意义涵盖很多知识点,所以经常使用,在调用的时候,看到一个问题,就是关于python func函数中的n是什么?大家有没有考虑过呢? ...

  7. python向数据库写入数据_如何用Python向Mysql中插入数据

    我们使用Python经常会和Postgresql进行搭配,很少将python和mysql进行搭配.下面小编给大家分享如何用Python向Mysql中插入数据. 工具/原料 Pycharm 方法/步骤 ...

  8. python中奇数怎么表示_如何在python输出数据中的奇数

    如何在python输出数据中的奇数 发布时间:2020-07-10 17:08:48 来源:亿速云 阅读:131 这篇文章将为大家详细讲解有关如何在python输出数据中的奇数,文章内容质量较高,因此 ...

  9. python在工作中怎么用_如何用python在工作中“偷懒”

    原标题:如何用python在工作中"偷懒" "偷懒还能干完活,才是本事 " 有些朋友在工作中会有这样的困惑:明明我从早忙到晚,为什么得到的评价还不高? 要知道, ...

最新文章

  1. C# WinForm使用乐器数字接口
  2. 医院信息化建设历程(5)互联互通的数字化医院阶段
  3. 【赠书】深度强化学习落地指南,来自一线工程师的经验!
  4. CentOS7 64位下载配置与安装教程(超详细图文教程)
  5. SpringBoot_web开发-扩展与全面接管SpringMVC
  6. 8个JavaScript库可更好地处理本地存储
  7. 图文并茂安装CentOS 6.7Linux系统
  8. Python学习入门基础教程(learning Python)--5 Python文件处理
  9. java实现 mysql导入_怎么用java实现mysql数据库的导入导出
  10. [WebAPI] - 使用 Ajax 提交 HTML Form Data 到 WebAPI 的方法
  11. Halcon深度学习自定义网络模型-VGG16
  12. 编译 easyMule-VeryCD
  13. ISO9000:2000 质量管理八大原则
  14. 【若依vue框架学习】4.获取登录用户信息(getInfo)
  15. 武汉纺织大学计算机科学校区在哪,武汉纺织大学阳光校区在哪 环境好不好
  16. Word中搜狗输入法不管用了怎么办?
  17. Squid中文权威指南-第10章 与其他Squid会话
  18. C语言学习笔记——(三)静态开辟内存和动态开辟内存
  19. [网鼎杯 2018]Fakebook
  20. 春天开始Spring

热门文章

  1. Java面试题及答案,java底层实现原理
  2. matlab dwt 多层分解,利用matlab对图片进行多层小波分解 会的加QQ511607771 加过作图之后积分加倍送...
  3. 测开2 - Python(文件操作)
  4. 如何在vuejs里禁用eslint语法检查工具
  5. 20155305乔磊2016-2017-2《Java程序设计》第四周学习总结
  6. 如何构建ASP.NET MVC4JQueryAJaxJSon示例
  7. WCF技术剖析之二十七: 如何将一个服务发布成WSDL[基于HTTP-GET的实现](提供模拟程序)...
  8. Python快速学习03:运算 缩进和选择
  9. Alter-有意思的小游戏
  10. word模板生成word报表文档