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!
在本教程的最后,您将拥有一个缓解压力的机器人,每次您需要时,它都会向您发送可爱的狗图像,是的!
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,并安装必要的依赖项。
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*************
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.
如果该库已成功安装,那么我们很好。
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->发送图像
First, import all the libraries we need.
首先,导入我们需要的所有库。
from telegram.ext import Updater, CommandHandler
import requests
import re
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
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_id
bot.send_photo(chat_id=chat_id, photo=url)
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.dispatcher
dp.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 re
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def bop(bot, update):
url = get_url()
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def main():
updater = Updater('YOUR_TOKEN')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
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
命令。 如果一切运行正常,机器人将以随机的狗图像进行回复。 可爱吧?
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,直到获得图像。
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
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 re
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
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
def bop(bot, update):
url = get_image_url()
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def main():
updater = Updater('YOUR_TOKEN')
dp = updater.dispatcher
dp.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 机器人