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.mzph.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; 例如&…