by Nikita Kholin

通过尼基塔·霍林(Nikita Kholin)

如何在Telegram机器人中设置推送通知 (How to set up push notifications in your Telegram bot)

Telegram is a great platform with lots of great users (I’m a Telegram user myself). And what would be the best way for Telegram users to receive notifications? We can’t know for sure. Maybe they like email or something else. But we can guess that sending notifications to Telegram would be pretty convenient.

Telegram是一个很棒的平台,拥有很多很棒的用户(我自己也是Telegram用户)。 电报用户接收通知的最佳方式是什么? 我们不能确定。 也许他们喜欢电子邮件或其他东西。 但是我们可以猜测,将通知发送到Telegram将非常方便。

If you would like to send Telegram notifications from your application, you’ve come to the right place. I’ve added this feature to my application and I love it.

如果您想从应用程序发送电报通知,那么您来对地方了。 我已经将此功能添加到我的应用程序中,并且我喜欢它。

One quick note. In this article I provide examples of code in Python. But the ideas are not Python-specific and can be translated into another language without any hastle.

快速说明。 在本文中,我提供了Python代码示例。 但是这些想法不是特定于Python的,可以毫不费力地将其翻译成另一种语言。

So without further ado, let’s dive into how we can do it.

因此,事不宜迟,让我们深入研究如何做到这一点。

创建一个电报机器人 (Create a Telegram bot)

First of all, you need to create a Telegram bot. To do this you need to use another Telegram bot, BotFather. Just talk to him (press start).

首先,您需要创建一个Telegram机器人。 为此,您需要使用另一个Telegram机器人BotFather 。 只是和他说话(按开始)。

Now you see what it can do. But what interests us is creating a new bot, so that’s what we’re going to choose (/newbot).

现在您知道它可以做什么。 但是,我们感兴趣的是创建一个新的bot,因此我们将选择( /newbot )。

You’re quickly going to find out that bot’s name should end with “bot”. And since you’re like me and coming to the game too late, most bot names are already taken.

您很快就会发现bot的名称应以“ bot”结尾。 而且由于您和我一样,并且来不及参加游戏,因此大多数机器人名称已经被采用。

But eventually, you’re going to find a name for your bot and get an access token we’re going to need.

但是最终,您将为您的机器人找到一个名称,并获得我们需要的访问令牌。

Now that you have a bot, Telegram users can find and use it. But there is one problem — you can’t associate users that come from Telegram to the users in your application. Let me show you why.

现在您有了一个机器人,Telegram用户可以找到并使用它。 但是有一个问题-您无法将来自Telegram的用户与应用程序中的用户相关联。 让我告诉你为什么。

Once a user presses the “Start” button on your bot, you will receive an “update”. You can check all bot’s updates even in your browser by visiting the following URL https://api.telegram.org/bot{bot_token}/getUpdates (don’t forget to use your access token in the URL). Here’s what I got:

用户按下机器人上的“开始”按钮后,您将收到“更新”。 您甚至可以通过访问以下URL https://api.telegram.org/bot{bot_token}/getUpdates {bot_token} / https://api.telegram.org/bot{bot_token}/getUpdates (甚至不要在URL中使用访问令牌)来检查所有bot的更新,甚至在浏览器中也是如此。 这是我得到的:

Can’t read anything? Don’t worry. You can fix it by installing some JSON prettifier extension in your browser. I use JSON Formatter for Chrome. It looks so much better.

看不到任何东西? 不用担心 您可以通过在浏览器中安装一些JSON前缀扩展程序来修复它。 我将JSON Formatter用于Chrome。 看起来好多了。

So as you can see we don’t get that much information about the person. From this information, we can get their full name. But it would be lucky if the user would provide their full name in your application, and doesn’t guarantee uniqueness of it. So we can’t use that to find a user in your applications.

因此,正如您所看到的,我们没有得到有关此人的太多信息。 从这些信息中,我们可以获得他们的全名。 但是,如果用户在您的应用程序中提供其全名,并且不保证其唯一性,那将是幸运的。 因此,我们不能使用它在您的应用程序中找到用户。

Another piece of information we get is the username. That is more useful as it is unique between all Telegram users. But most likely you don’t have that available in your applications. So we would need to ask a user to enter their username somewhere in the application. It’s just too much work that I’m not sure anyone would do.

我们获得的另一条信息是用户名。 这是有用的,因为它在所有Telegram用户之间都是唯一的。 但是很可能您的应用程序中没有可用的功能。 因此,我们需要让用户在应用程序中的某个位置输入其用户名。 我不确定任何人都会做太多的工作。

Another option to associate a user would be to ask them to provide the email that they used in your application to the bot. But this has too many flaws: the user can make a typo while entering the email, the user can enter the email of another user and exploit the system. This is just too bad.

关联用户的另一种选择是要求他们向机器人提供他们在您的应用程序中使用的电子邮件。 但这有很多缺陷:用户可以在输入电子邮件时输入错误,用户可以输入其他用户的电子邮件并利用系统。 这太糟糕了。

Can we do better?

我们可以做得更好吗?

关联用户 (Associating a user)

Of course we can. To associate the user, we’ll use a technique called deep linking.

当然,我们可以。 为了关联用户,我们将使用一种称为深度链接的技术。

First, you need to create a random unique token for each user. I’ve used the following code to generate the token using Python:

首先,您需要为每个用户创建一个随机的唯一令牌。 我使用以下代码使用Python生成令牌:

from secrets import token_urlsafetoken = token_urlsafe(8)token# => 'uEDbtJFHxKc'

Then you need to save that token to be able to find a user with it later. You can save it to your database or use some other place like a cache for example. I have a Notification model so I added a field to a model’s table.

然后,您需要保存该令牌,以便以后可以找到它的用户。 您可以将其保存到数据库中,也可以使用其他地方,例如缓存。 我有一个Notification模型,所以我在模型的表中添加了一个字段。

class Notification(models.Model):    user = models.ForeignKey(User, on_delete=models.CASCADE)   # ...    connect_token = models.CharField(max_length=64, null=True)

So we’ve generated uEDbtJFHxKc token and saved it. Now we need to use this token in a URL to the telegram bot which the user needs to click to make it all work:

因此,我们生成了uEDbtJFHxKc令牌并将其保存。 现在,我们需要在电报机器人的URL中使用此令牌,用户需要单击该URL才能使其全部工作:

telegram_url = 'https://www.telegram.me'bot_name = 'music_notification_bot'token = 'uEDbtJFHxKc'url = f'{telegram_url}/{bot_name}?start={token}'

Now that we have our URL, 'https://telegram.me/music_notification_bot?start=uEDbtJFHxKc', it’s time to show it to the user. Just display it in any place of your application and wait for the user to click on it.

现在我们有了URL'https 'https://telegram.me/music_notification_bot?start=uEDbtJFHxKc' ,现在该向用户展示它了。 只需将其显示在应用程序的任何位置,然后等待用户单击它即可。

Once the user takes the bait and clicks “Start” you should receive another update:

一旦用户采取了诱饵并单击“开始”,您将收到另一个更新:

{    "ok": true,    "result": [        // ...        // previous updates        // ...      {           "update_id": 599162365,           "message": {                "message_id": 174,                "from": { ... },                "chat": { ... },                "date": 1549788357,                "text": "/start uEDbtJFHxKc",                "entities": [ ... ]           }        }    ]}

We can finally identify our user. The text field now contains our user token. Let’s go ahead and take it out of this field:

我们最终可以确定我们的用户。 现在, text字段包含我们的用户令牌。 让我们继续将其移出该领域:

bot_token = 'your_bot_token'updates_url = f'https://api.telegram.org/bot{bot_token}/getUpdates'import requestsresponse = requests.get(updates_url).json()text = response['result'][0]['message']['text']text# => '/start uEDbtJFHxKc'splitted_text = text.split(' ')# => ['/start', 'uEDbtJFHxKc']token = splitted_text[-1]# => 'uEDbtJFHxKc'

This token can be used to find the user. Your implementation depends on the way you saved the token in the first place. But here’s how I do it:

该令牌可用于查找用户。 您的实现取决于一开始保存令牌的方式。 但是,这是我的方法:

notification = Notification.objects.get(channel='telegram', connect_token=token)user = notification.user

So the user had pressed the “Start” button. But they see that nothing happened. Let’s welcome them at least.

因此,用户已按下“开始”按钮。 但是他们看到什么也没发生。 让我们至少欢迎他们。

To welcome the user we need to discover that the user had started a conversation with our bot. There are two options for how we can do that: polling and webhooks.

为了欢迎用户,我们需要发现该用户已开始与我们的机器人进行对话。 有两种方法可以实现此目的:轮询和webhooks。

You already know what polling is. You’ve already done it. Or at least have seen me do it. Once we’ve checked out the https://api.telegram.org/bot{bot_token}/getUpdates page we did one poll. Polling is checking for updates constantly, every 2 seconds for example. This way we can always know when someone interacted with the bot.

您已经知道轮询是什么。 您已经完成了。 或者至少看到我这样做了。 检出https://api.telegram.org/bot{bot_token}/getUpdates页面后,我们进行了一次民意调查。 轮询是不断检查更新,例如每2秒检查一次。 这样,我们总是可以知道何时有人与机器人进行了交互。

Webhooks take a bit of a different direction. Instead of checking every 2 seconds for updates, we just wait for an update to happen. And when it happens Telegram will send a request with the update data to a URL that we specify. This way we can give both our and Telegram servers some rest and just wait for the update to come.

Webhooks采取了不同的方向。 无需等待每2秒检查一次更新,而是等待更新发生。 当发生这种情况时,Telegram会将带有更新数据的请求发送到我们指定的URL。 这样,我们可以让我们的和Telegram服务器都得到一些休息,然后等待更新来临。

Polling can be better if you’ve got high traffic but, unfortunately, it’s rather an exception so I’ve decided to go with the webhook.

如果通信量大,轮询可能会更好,但不幸的是,这是一个例外,因此我决定使用网络挂钩。

网络挂钩 (Webhooks)

Setting a webhook in Telegram is very easy. You just need to send a request to https://api.telegram.org/bot{bot_token}/setWebhook?url={your_server_url}. Opening this link in your browser works too. your_server_url is the URL Telegram will send updates to. Here’s what you should get in the response:

在Telegram中设置Webhook非常容易。 您只需要向https://api.telegram.org/bot{bot_token}/setWebhook?url={your_server_url}发送请求。 在浏览器中打开此链接也可以。 your_server_url是将电报发送到的URL。 这是您应该在响应中得到的:

{    "ok": true,    "result": true,    "description": "Webhook was set"}

If you don’t trust yourself you can visit https://api.telegram.org/bot{bot_token}/getWebhookInfo just to doublecheck that everything is OK. You should see something like this:

如果您不信任自己,则可以访问https://api.telegram.org/bot{bot_token}/getWebhookInfo ,以再次确认一切正常。 您应该会看到以下内容:

{    "ok": true,    "result": {        "url": "https://example.com/your_server_endpoint",        "has_custom_certificate": false,        "pending_update_count": 0,        "max_connections": 40    }}

Now. If something is not OK (like you’ve set a wrong URL) you can always delete the webhook by visiting https://api.telegram.org/bot{bot_token}/deleteWebhook and then setting the webhook again.

现在。 如果出现问题(例如您设置了错误的URL),则可以随时访问https://api.telegram.org/bot{bot_token}/deleteWebhook并再次设置该Webhook来删除该Webhook。

当地发展 (Local development)

Before continuing I would like to say a few words about local development. Webhooks are not very suitable for it. Webhooks are sent to a URL and most likely you don’t know your computer’s URL. Also, a Telegram webhook requires the URL to be secure (HTTPS).

在继续之前,我想谈一谈地方发展。 Webhooks不太适合它。 Webhook被发送到URL,很可能您不知道计算机的URL。 另外,Telegram Webhook要求URL是安全的(HTTPS)。

But there is a solution to this problem: ngrok. ngrok is a tool that exposes your local environment to the world. Download ngrok, install it and start it with the port your server is running on. My server is running on 8000 port so I would need to run in a console

但是有一个解决方案: ngrok 。 ngrok是将您的本地环境暴露给全世界的工具。 下载ngrok ,安装它,并从服务器正在运行的端口启动它。 我的服务器在8000端口上运行,因此我需要在控制台中运行

/path/to/ngrok http 8000

Then ngrok should give you a URL that you can use to set a webhook up.

然后,ngrok应该为您提供一个URL,可用于设置网络连接。

欢迎用户 (Welcoming a user)

Now that you’re ready to develop, let’s welcome our user — they’re waiting for it.

现在您已经准备好开发,欢迎我们的用户-他们正在等待它。

Once the user clicks “Start”, your Telegram will send an update to your server’s URL. The interesting parts of the update should look like this:

用户单击“开始”后,您的电报将向服务器的URL发送更新。 更新的有趣部分应如下所示:

{    "message": {        "chat": {            "id": 457        },       "text": "/start uEDbtJFHxKc",    }}

This is a perfect time to associate the user using message text. There is also an interesting piece of information, chat ID. Chat ID is what we need to send a message to that user. Telegram has an API endpoint to send a message that looks like this https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={text}. I’m not sure I need to explain how to use it but here’s what my code that processes the webhook looks like:

这是使用消息文本关联用户的理想时机。 还有一条有趣的信息,即聊天ID。 聊天ID是我们向该用户发送消息所需要的。 Telegram有一个API端点来发送看起来像https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={text}的消息。 我不确定我需要解释如何使用它,但这是处理Webhook的代码如下所示:

import jsonimport requestsdef callback(request):    body = json.loads(request.body)    text = body['message']['text']    token = text.split(' ')[-1]    associate_user_by_token(token)    bot_key = os.environ.get('TELEGRAM_API_KEY')    chat_id = body['message']['chat']['id'] text = "Welcome!"    send_message_url = f'https://api.telegram.org/bot{bot_key}/sendMessage?chat_id={chat_id}&text={text}'  requests.post(send_message_url)

If we send a welcome message after the user clicked the famous “Start” button, the user won’t have any second thoughts whether everything is working or not.

如果我们在用户单击著名的“开始”按钮后发送欢迎消息,则用户将不会再有任何想法,不管是否一切正常。

推送通知 (Pushing notifications)

Finally, we get to the point why we’re doing all of this — push notifications. You may want to notify the user about some information that happened in your application. For example, someone liked the user’s post or whatever. I use Telegram to notify about new music releases from the user’s favorite artists.

最后,我们要说明为什么要执行所有这些操作-推送通知。 您可能想通知用户有关应用程序中发生的某些信息。 例如,某人喜欢用户的帖子或其他内容。 我使用Telegram来通知用户最喜欢的艺术家发布的新音乐 。

You already know how to send notifications. You just need to send a message using https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={notification_text}.

您已经知道如何发送通知。 您只需要使用https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={notification_text}发送消息。

Of course, if you’re planning to send notifications not only when the user interacts with the bot, you need to save chat_id in your database.

当然,如果您打算不仅在用户与漫游器进行交互时发送通知,还需要在数据库中保存chat_id

You might also want to include links or some other formatting in your message. In this case, you would need to add another parameter to the send message URL, parse_mode. There are 2 parsing options: Markdown or HTML. I use Markdown since I find it simpler to use. If you’re not familiar with Markdown you can use HMTL, but I would recommend reading how easy Markdown is.

您可能还希望在邮件中包含链接或其他格式。 在这种情况下,您需要向发送消息URL添加另一个参数parse_mode 。 有2个解析选项:Markdown或HTML。 我使用Markdown是因为我发现它更易于使用。 如果您不熟悉Markdown,可以使用HMTL,但我建议您阅读Markdown有多么容易 。

Here’s how the send message URL looks with parse_mode parameter https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={notification_text}&parse_mode=markdown.

这是带有parse_mode参数https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={notification_text}&parse_mode=markdown的发送消息URL的外观。

I add links to new releases to the notifications text like so {release.date}: {release.artist.name} - [{release.title}]({release.url}). You can read more about how to format you messages here.

我在通知文本中添加了指向新发行版的链接,例如{release.date}: {release.artist.name} - [{release.title}]({release.url}) 。 您可以在此处阅读有关如何格式化消息的更多信息。

Also, there are more parameters available for the send message URL like disable_notification. There is always a place to explore.

此外,还有更多可用于发送消息URL的参数 ,例如disable_notification 。 总有一个值得探索的地方。

结论 (Conclusion)

Now you should know how to

现在您应该知道如何

  • create a bot in Telegram using BotFather使用BotFather在Telegram中创建一个机器人
  • check for updates (and what is a better way — webhooks or polling)检查更新(还有什么更好的方法–网络钩子或轮询)
  • associate user using deep linking使用深层链接来关联用户
  • send a welcome message and continue sending notifications发送欢迎消息并继续发送通知
  • format messages you send格式化您发送的消息

Hopefully, this article was useful to you. This is the fifth part of a series of articles about the MuN. Stay tuned for part 6. You can find the code of this project, as well as my other projects, on my GitHub page. Leave your comments down below and follow me if you liked this article.

希望本文对您有所帮助。 这是有关MuN的系列文章的第五部分。 请继续关注第6部分。您可以在我的GitHub页面上找到该项目的代码以及其他项目的代码 。 在下方留下您的评论,如果您喜欢本文,请关注我。

Originally published at https://kholinlabs.com/telegram-push-notifications on February 12, 2019.

最初于2019年2月12日发布在https://kholinlabs.com/telegram-push-notifications 。

翻译自: https://www.freecodecamp.org/news/telegram-push-notifications-58477e71b2c2/

如何在Telegram机器人中设置推送通知相关推荐

  1. swift通知栏推送_如何使用Swift使用推送通知构建食品交付应用

    swift通知栏推送 by Neo Ighodaro 由新Ighodaro 如何使用Swift使用推送通知构建食品交付应用 (How to build a food delivery app with ...

  2. 如何使用WordPress推送通知和智能通知插件

    什么是推送通知? 推送通知是由应用程序和网站传输的简短信息性消息,可以随时传达给受众. 与当访客在网站或浏览器上时显示的弹出窗口不同,即使访客不在网站上,也会显示推送通知. 推送通知使您可以向启用了用 ...

  3. 推送通知/传感器/UIDynamic仿真(推送通知已适配iOS10)

    推送通知/传感器/UIDynamic 一.推送通知 1.推送通知简介 什么是推送通知 此处的推送通知与NSNotification没有任何关系 可以理解为,向用户推送一条信息来通知用户某件事情 作用: ...

  4. 消息推送配置url(服务器地址),设置推送url接口

    ## 设置推送url接口 请求地址:`https://open-api.10ss.net/oauth/setpushurl` 请求方式:POST ### 所需参数 |名 称|类 型|描 述| |--- ...

  5. 关于Cordova iOS 工程极光推送通知自定义声音的设置

    前提条件:你已经在极光官网后台申请了极光推送所需要的APP_KEY,以及在苹果开发者中心在你的项目中开启了推送权限,并制作了推送证书上传到极光后台,前面这些不知道怎么设置的,请自行问度娘.没办法,io ...

  6. “iOS 推送通知”详解:从创建到设置到运行

    "iOS 推送通知"详解:从创建到设置到运行 转自 http://www.csdn.net/article/2012-02-18/311976 这是一篇编译的文章,内容均出自Par ...

  7. android设置通知在屏幕横幅显示,Android推送通知横幅未显示在某些设备中

    我试图用NotificationCompat推送通知: NotificationCompat.Builder b = new NotificationCompat.Builder(this); b.s ...

  8. swift通知栏推送_如何使用Swift和Laravel使用推送通知创建iOS加密跟踪应用

    swift通知栏推送 by Neo Ighodaro 由新Ighodaro 如何使用Swift和Laravel使用推送通知创建iOS加密跟踪应用 (How to create an iOS crypt ...

  9. 向 iOS 设备发送推送通知

    向 iOS 设备发送推送通知 直接向 iOS 应用程序提供丰富的内容 Michael Yuan 2012 年 5 月 25 日发布 背景 SMS 和 MMS 消息是由无线运营商通过设备的电话号码向特定 ...

最新文章

  1. android手机装windows,安卓手机上运行WindowsXP系统图文教程
  2. Linux空间过满无法登录,linux下磁盘空间不足导致oracle无法登录的解决方案
  3. setting an array element with a sequence
  4. P1219 八皇后 含优化 1/5
  5. SQL Server中的SQL语句优化与效率问题
  6. notepad批量删除html元素,Notepad++几个常用删除类正则表达式汇总(收藏)
  7. localhost可以访问 ip不能访问_如何解决域名可以访问80端口但访问不了其他端口的问题...
  8. 移动端适配的理解——REM方案
  9. 题目1003:A+B 使用大数相加方法解法
  10. 在Java中基于mysql驱动包连接MySQL数据库
  11. 电子政务互联互通软件平台的体系架构
  12. 智慧城市顶层设计实施工作指南
  13. Oracle 查询重复字段
  14. zyf sql语句
  15. 港科夜闻丨香港科大教授权龙:三维重建才是计算机视觉的灵魂
  16. 公开处刑,专家博主开发游戏的老王专栏抄袭事件始末
  17. Scrapy项目 - 数据简析 - 实现豆瓣 Top250 电影信息爬取的爬虫设计
  18. Volume was not properly unmounted. Some data may be corrupt
  19. Android各种轮子
  20. 百度飞桨七天训练营结营总结

热门文章

  1. 对象数组与普通数组 java 0913
  2. 爬虫-使用xpath拿36KR的数据-xpath的学习与演练
  3. centos-安装pycharm
  4. django-验证码
  5. jquery-幻灯片的移动分析
  6. 音量已经调到100%,如何再调整
  7. c++_导入/导出excel文件
  8. apache配置ssl证书
  9. Redis高可用分布式内部交流(九)
  10. 解决WIN7有限的访问权限的终极解决方案合集