Hi everyone :) Today I am beginning a new series of posts specifically aimed at Python beginners. The concept is rather simple: I'll do a fun project, in as few lines of code as possible, and will try out as many new tools as possible.

大家好:)今天,我开始专门针对Python初学者的一系列新文章。 这个概念非常简单:我将用尽可能少的代码行来完成一个有趣的项目,并将尝试尽可能多的新工具。

For example, today we will learn to use the Twilio API, the Twitch API, and we'll see how to deploy the project on Heroku. I'll show you how you can have your own "Twitch Live" SMS notifier, in 30 lines of codes, and for 12 cents a month.

例如,今天我们将学习使用Twilio API和Twitch API,并且将了解如何在Heroku上部署项目。 我将向您展示如何以30行代码,每月12美分的价格拥有自己的“ Twitch Live” SMS通知程序。

Prerequisite: You only need to know how to run Python on your machine and some basic commands in git (commit & push). If you need help with these, I can recommend these 2 articles to you:

先决条件 :您只需要知道如何在计算机上运行Python以及git中的一些基本命令(提交和推送)。 如果您需要这些方面的帮助,我可以向您推荐以下2篇文章:

Python 3 Installation & Setup Guide

Python 3安装和设置指南

The Ultimate Git Command Tutorial for Beginners from Adrian Hajdin.

来自Adrian Hajdin的 初学者终极Git命令教程 。

What you'll learn:

您将学到的内容

  • Twitch APITwitch API
  • Twilio APITwilio API
  • Deploying on Heroku在Heroku上部署
  • Setting up a scheduler on Heroku在Heroku上设置调度程序

What you will build:

您将构建什么:

The specifications are simple: we want to receive an SMS as soon as a specific Twitcher is live streaming. We want to know when this person is going live and when they leave streaming. We want this whole thing to run by itself, all day long.

规范很简单:我们希望在特定的Twitcher直播后立即收到一条SMS。 我们想知道此人何时上线以及何时离开流媒体。 我们希望这件事整天独自运行。

We will split the project into 3 parts. First, we will see how to programmatically know if a particular Twitcher is online. Then we will see how to receive an SMS when this happens. We will finish by seeing how to make this piece of code run every X minutes, so we never miss another moment of our favorite streamer's life.

我们将项目分为3部分。 首先,我们将了解如何以编程方式知道特定的Twitcher是否在线。 然后,我们将看到发生这种情况时如何接收短信。 最后,我们将了解如何使这段代码每隔X分钟运行一次,因此我们再也不会错过我们喜欢的流媒体生命中的另一刻。

这是Twitcher直播吗? (Is this Twitcher live?)

To know if a Twitcher is live, we can do two things: we can go to the Twitcher URL and try to see if the badge "Live" is there.

要知道Twitcher是否处于活动状态,我们可以做两件事:我们可以转到Twitcher URL并尝试查看徽章“ Live”是否在那里。

This process involves scraping and is not easily doable in Python in less than 20 or so lines of code. Twitch runs a lot of JS code and a simple request.get() won't be enough.

此过程涉及抓取,并且在少于20行的代码中在Python中不容易实现。 Twitch运行了大量的JS代码,简单的request.get()是不够的。

For scraping to work, in this case, we would need to scrape this page inside Chrome to get the same content like what you see in the screenshot. This is doable, but it will take much more than 30 lines of code. If you'd like to learn more, don't hesitate to check my recent web scraping without getting blocked guide. (I recently launch ScrapingBee, a web-scraping tool hence my knowledge in the field ;))

在这种情况下,为了使抓取工作正常进行,我们需要在Chrome中抓取此页面,以获取与您在屏幕截图中看到的内容相同的内容。 这是可行的,但是将花费超过30行代码。 如果您想了解更多信息,请随时检查我最近的网络抓取过程,而不会受到指南的限制 。 (我最近启动了ScrapingBee,这是一个网络抓取工具,因此我在该领域的知识;)

So instead of trying to scrape Twitch, we will use their API. For those unfamiliar with the term, an API is a programmatic interface that allows websites to expose their features and data to anyone, mainly developers. In Twitch's case, their API is exposed through HTTP, witch means that we can have lots of information and do lots of things by just making a simple HTTP request.

因此,我们将尝试使用它们的API,而不是试图拖拉Twitch。 对于不熟悉该术语的人来说,API是一种编程接口,允许网站将其功能和数据公开给任何人,主要是开发人员。 在Twitch的情况下,他们的API是通过HTTP公开的,巫婆意味着我们可以通过发出一个简单的HTTP请求来获得很多信息并做很多事情。

获取您的API密钥 (Get your API key)

To do this, you have to first create a Twitch API key. Many services enforce authentication for their APIs to ensure that no one abuses them or to restrict access to certain features by certain people.

为此,您必须首先创建一个Twitch API密钥。 许多服务都对其API进行身份验证,以确保没有人滥用它们或限制某些人对某些功能的访问。

Please follow these steps to get your API key:

请按照以下步骤获取您的API密钥:

  • Create a Twitch account创建一个Twitch帐户
  • Now create a Twitch dev account -> "Signing up with Twitch" top right

    现在创建一个Twitch 开发者帐户 ->“使用Twitch注册”右上角

  • Go to your "dashboard" once logged in登录后转到“仪表盘”
  • "Register your application"“注册您的申请”
  • Name -> Whatever, Oauth redirection URL -> http://localhost, Category -> Whatever名称->任意,Oauth重定向URL-> http:// localhost,类别->任意

You should now see, at the bottom of your screen, your client-id. Keep this for later.

现在,您应该在屏幕底部看到您的客户ID。 保留以备后用。

那是Twitcher直播吗? (Is that Twitcher streaming now?)

With your API key in hand, we can now query the Twitch API to have the information we want, so let's begin to code. The following snippet just consumes the Twitch API with the correct parameters and prints the response.

有了您的API密钥,我们现在可以查询Twitch API以获取所需的信息,因此让我们开始编写代码。 以下代码段仅使用带有正确参数的Twitch API并打印响应。

# requests is the go to package in python to make http request
# https://2.python-requests.org/en/master/
import requests# This is one of the route where Twich expose data,
# They have many more: https://dev.twitch.tv/docs
endpoint = "https://api.twitch.tv/helix/streams?"# In order to authenticate we need to pass our api key through header
headers = {"Client-ID": "<YOUR-CLIENT-ID>"}# The previously set endpoint needs some parameter, here, the Twitcher we want to follow
# Disclaimer, I don't even know who this is, but he was the first one on Twich to have a live stream so I could have nice examples
params = {"user_login": "Solary"}# It is now time to make the actual request
response = request.get(endpoint, params=params, headers=headers)
print(response.json())

The output should look like this:

输出应如下所示:

{'data':[{'id':'35289543872','user_id':'174955366','user_name':'Solary','game_id':'21779','type':'live','title':"Wakz duoQ w/ Tioo - GM 400LP - On récupère le chall après les -250LP d'inactivité !",'viewer_count':4073,'started_at':'2019-08-14T07:01:59Z','language':'fr','thumbnail_url':'https://static-cdn.jtvnw.net/previews-ttv/live_user_solary-{width}x{height}.jpg','tag_ids':['6f655045-9989-4ef7-8f85-1edcec42d648']}],'pagination':{'cursor':'eyJiIjpudWxsLCJhIjp7Ik9mZnNldCI6MX19'}
}

This data format is called JSON and is easily readable. The data object is an array that contains all the currently active streams. The key type ensures that the stream is currently live. This key will be empty otherwise (in case of an error, for example).

这种数据格式称为JSON,易于阅读。 data对象是一个包含所有当前活动流的数组。 密钥type可确保流当前处于live 。 否则,该键将为空(例如,在发生错误的情况下)。

So if we want to create a boolean variable in Python that stores whether the current user is streaming, all we have to append to our code is:

因此,如果我们想在Python中创建一个布尔变量来存储当前用户是否正在流式传输,我们要做的就是添加到代码中:

json_response = response.json()# We get only streams
streams = json_response.get('data', [])# We create a small function, (a lambda), that tests if a stream is live or not
is_active = lambda stream: stream.get('type') == 'live'
# We filter our array of streams with this function so we only keep streams that are active
streams_active = filter(is_active, streams)# any returns True if streams_active has at least one element, else False
at_least_one_stream_active = any(streams_active)print(at_least_one_stream_active)

At this point, at_least_one_stream_active is True when your favourite Twitcher is live.

此时,当您最喜欢的Twitcher处于活动状态时, at_least_one_stream_active为True。

Let's now see how to get notified by SMS.

现在让我们看看如何通过SMS接收通知。

现在给我发短信! (Send me a text, NOW!)

So to send a text to ourselves, we will use the Twilio API. Just go over there and create an account. When asked to confirm your phone number, please use the phone number you want to use in this project. This way you'll be able to use the $15 of free credit Twilio offers to new users. At around 1 cent a text, it should be enough for your bot to run for one year.

因此,要向自己发送文本,我们将使用Twilio API。 只需去那边创建一个帐户即可。 当要求确认您的电话号码时,请使用您要在该项目中使用的电话号码。 这样,您就可以使用Twilio向新用户提供的$ 15免费信用。 每条文字大约1美分,足以让您的漫游器运行一年。

If you go on the console, you'll see your Account SID and your Auth Token , save them for later. Also click on the big red button "Get My Trial Number", follow the step, and save this one for later too.

如果您在控制台上 ,您将看到您的Account SID和您的Auth Token ,将其保存以备后用。 另外,单击红色的大按钮“获取我的试用号”,按照步骤操作,并将其保存下来以备后用。

Sending a text with the Twilio Python API is very easy, as they provide a package that does the annoying stuff for you. Install the package with pip install Twilio and just do:

使用Twilio Python API发送文本非常容易,因为它们提供了一个可以帮您完成烦人事情的软件包。 使用pip install Twilio安装软件包,然后执行以下操作:

from twilio.rest import Client
client = Client(<Your Account SID>, <Your Auth Token>)
client.messages.create(body='Test MSG',from_=<Your Trial Number>,to=<Your Real Number>)

And that is all you need to send yourself a text, amazing right?

这就是您需要给自己发送短信的全部了,对吗?

放在一起 (Putting everything together)

We will now put everything together, and shorten the code a bit so we manage to say under 30 lines of Python code.

现在,我们将所有内容放在一起,并缩短代码一点,以便我们设法说出少于30行的Python代码。

避免重复通知 (Avoiding double notifications)

This snippet works great, but should that snippet run every minute on a server, as soon as our favorite Twitcher goes live we will receive an SMS every minute.

该代码片段效果很好,但是如果该代码片段在服务器上每分钟运行一次,那么当我们最喜欢的Twitcher上线时,我们将每分钟收到一条SMS。

We need a way to store the fact that we were already notified that our Twitcher is live and that we don't need to be notified anymore.

我们需要一种方法来存储这样的事实,即我们已经收到通知,我们的Twitcher已启用,并且不再需要通知。

The good thing with the Twilio API is that it offers a way to retrieve our message history, so we just have to retrieve the last SMS we sent to see if we already sent a text notifying us that the twitcher is live.

使用Twilio API的好处是,它提供了一种检索消息历史记录的方法,因此我们只需要检索发送的最后一条SMS,以查看是否已经发送了文本来通知我们该twitcher处于活动状态。

Here what we are going do to in pseudocode:

这是我们要用伪代码执行的操作:

if favorite_twitcher_live and last_sent_sms is not live_notification:send_live_notification()
if not favorite_twitcher_live and last_sent_sms is live_notification:send_live_is_over_notification()

This way we will receive a text as soon as the stream starts, as well as when it is over. This way we won't get spammed - perfect right? Let's code it:

这样,我们将在流开始以及结束时接收文本。 这样我们就不会发垃圾邮件-完美吗? 让我们编写代码:

# reusing our Twilio client
last_messages_sent = client.messages.list(limit=1)
last_message_id = last_messages_sent[0].sid
last_message_data = client.messages(last_message_id).fetch()
last_message_content = last_message_data.body

Let's now put everything together again:

现在让我们再次将所有内容放在一起:

import requests
from twilio.rest import Client
client = Client(<Your Account SID>, <Your Auth Token>)endpoint = "https://api.twitch.tv/helix/streams?"
headers = {"Client-ID": "<YOUR-CLIENT-ID>"}
params = {"user_login": "Solary"}
response = request.get(endpoint, params=params, headers=headers)
json_response = response.json()
streams = json_response.get('data', [])
is_active = lambda stream:stream.get('type') == 'live'
streams_active = filter(is_active, streams)
at_least_one_stream_active = any(streams_active)last_messages_sent = client.messages.list(limit=1)
if last_messages_sent:last_message_id = last_messages_sent[0].sidlast_message_data = client.messages(last_message_id).fetch()last_message_content = last_message_data.bodyonline_notified = "LIVE" in last_message_contentoffline_notified = not online_notified
else:online_notified, offline_notified = False, Falseif at_least_one_stream_active and not online_notified:client.messages.create(body='LIVE !!!',from_=<Your Trial Number>,to=<Your Real Number>)
if not at_least_one_stream_active and not offline_notified:client.messages.create(body='OFFLINE !!!',from_=<Your Trial Number>,to=<Your Real Number>)

And voilà!

和瞧!

You now have a snippet of code, in less than 30 lines of Python, that will send you a text a soon as your favourite Twitcher goes Online / Offline and without spamming you.

现在,您拥有了不到30行Python的代码片段,当您最喜欢的Twitcher联机/脱机且不会向您发送垃圾邮件时,就会立即向您发送文本。

We just now need a way to host and run this snippet every X minutes.

现在,我们需要一种每隔X分钟托管并运行此代码段的方法。

寻找主人 (The quest for a host)

To host and run this snippet we will use Heroku. Heroku is honestly one of the easiest ways to host an app on the web. The downside is that it is really expensive compared to other solutions out there. Fortunately for us, they have a generous free plan that will allow us to do what we want for almost nothing.

要托管和运行此代码段,我们将使用Heroku。 老实说,Heroku是在网络上托管应用程序的最简单方法之一。 缺点是,与其他解决方案相比,它确实很昂贵。 对我们来说幸运的是,他们有一个慷慨的免费计划,这将使我们几乎可以做任何事情。

If you don't already, you need to create a Heroku account. You also need to download and install the Heroku client.

如果尚未安装,则需要创建一个Heroku帐户 。 您还需要下载并安装Heroku客户端 。

You now have to move your Python script to its own folder, don't forget to add a requirements.txt file in it. The content of the latter begins:

现在,您必须将Python脚本移动到其自己的文件夹中,不要忘记在其中添加requirements.txt文件。 后者的内容开始于:

cd into this folder and just do a `heroku create --app <app name>`.

cd进入这个文件夹,然后执行`heroku create --app <app name>`。

If you go on your app dashboard you'll see your new app.

如果您进入应用程序信息中心 ,则会看到新应用程序。

We now need to initialize a git repo and push the code on Heroku:

现在,我们需要初始化一个git repo并将代码推送到Heroku上:

git init
heroku git:remote -a <app name>
git add .
git commit -am 'Deploy breakthrough script'
git push heroku master

Your app is now on Heroku, but it is not doing anything. Since this little script can't accept HTTP requests, going to <app name>.herokuapp.com won't do anything. But that should not be a problem.

您的应用程序现在位于Heroku上,但没有执行任何操作。 由于此小脚本无法接受HTTP请求,因此转到<app name>.herokuapp.com将不会执行任何操作。 但这不应该是一个问题。

To have this script running 24/7 we need to use a simple Heroku add-on call "Heroku Scheduler". To install this add-on, click on the "Configure Add-ons" button on your app dashboard.

要使此脚本运行24/7,我们需要使用一个简单的Heroku附加调用“ Heroku Scheduler”。 要安装此加载项,请在您的应用仪表板上单击“配置加载项”按钮。

Then, on the search bar, look for Heroku Scheduler:

然后,在搜索栏上查找Heroku Scheduler:

Click on the result, and click on "Provision"

单击结果,然后单击“设置”

If you go back to your App dashboard, you'll see the add-on:

如果您返回到应用程序仪表板,则会看到该加载项:

Click on the "Heroku Scheduler" link to configure a job. Then click on "Create Job". Here select "10 minutes", and for run command select `python <name_of_your_script>.py`. Click on "Save job".

单击“ Heroku Scheduler”链接以配置作业。 然后单击“创建作业”。 在这里选择“ 10分钟”,并为运行命令选择“ python <您的脚本> .py”。 点击“保存工作”。

While everything we used so far on Heroku is free, the Heroku Scheduler will run the job on the $25/month instance, but prorated to the second. Since this script approximately takes 3 seconds to run, for this script to run every 10 minutes you should just have to spend 12 cents a month.

虽然我们到目前为止在Heroku上使用的所有内容都是免费的,但Heroku Scheduler会在每月25美元的实例上运行该作业,但按比例分配到第二个实例。 由于此脚本运行大约需要3秒钟,因此要使该脚本每​​10分钟运行一次,您每月只需花费12美分。

改进思路 (Ideas for improvements)

I hope you liked this project and that you had fun putting it into place. In less than 30 lines of code, we did a lot, but this whole thing is far from perfect. Here are a few ideas to improve it:

我希望您喜欢这个项目,并希望将它放置到位很开心。 在不到30行的代码中,我们做了很多事情,但是整个过程还远远不够完美。 以下是一些改进建议:

  • Send yourself more information about the current streaming (game played, number of viewers ...)向自己发送有关当前流式传输的更多信息(玩过的游戏,观看人数...)
  • Send yourself the duration of the last stream once the twitcher goes offline抽搐者离线后,向自己发送最后一个流的持续时间
  • Don't send you a text, but rather an email不要给您发短信,而是给您发送电子邮件
  • Monitor multiple twitchers at the same time同时监控多个抽搐者

Do not hesitate to tell me in the comments if you have more ideas.

如果您有更多想法,请随时在评论中告诉我。

结论 (Conclusion)

I hope that you liked this post and that you learned things reading it. I truly believe that this kind of project is one of the best ways to learn new tools and concepts, I recently launched a web scraping API where I learned a lot while making it.

我希望您喜欢这篇文章,并希望您能从中学到东西。 我坚信这种项目是学习新工具和概念的最佳方法之一,我最近发布了一个Web抓取API ,在此过程中我学到了很多东西。

Please tell me in the comments if you liked this format and if you want to do more.

如果您喜欢这种格式,并且想做更多的事情,请在评论中告诉我。

I have many other ideas, and I hope you will like them. Do not hesitate to share what other things you build with this snippet, possibilities are endless.

我还有很多其他想法,希望您会喜欢。 不要犹豫,用这个片段分享您构建的其他东西,可能性无穷无尽。

Happy Coding.

编码愉快。

Pierre

皮埃尔

不想错过我的下一篇文章: (Don't want to miss my next post:)

You can subscribe here to my newsletter.

您可以在这里订阅我的时事通讯。

翻译自: https://www.freecodecamp.org/news/20-lines-of-python-code-get-notified-by-sms-when-your-favorite-team-scores-a-goal/

一个包含30行代码的Python项目:如何在您最喜欢的Twitcher流式传输时设置SMS通知...相关推荐

  1. python制作表白神器_程序员的七夕用30行代码让Python化身表白神器

    转眼又到了咱们中国传统的情人节七夕了,今天笔者就带大家来领略一下用Python表白的方式.让程序员的恋人们感受一下IT人的浪漫. 一.词云制作 首先咱们可以用之前介绍过的wordcould包制作词云. ...

  2. 30行代码使用Python制作熊猫表情包(图片字符化)(附有源码逐行分析)

    文章目录 一.Demo 二.程序演示加讲解 三.分析程序 四.注意事项 五.程序的改进 一.Demo 相信许多的小伙伴在平时玩QQ的时候都有发过这样一张表情包,如下: 它其实是由下面的一张表情包演化而 ...

  3. 30行代码用python实现软件翻译

    先挂结果: 代码如下: # 开发人:peng # 开发时间 :2022/3/21 14:30 import urllib.request import urllib.parse import json ...

  4. 从Azure命令行流式传输诊断跟踪日志(以及Glimpse!)

    I've long said when in doubt, turn on tracing. Sometimes "got here"-debugging is a great t ...

  5. Python程序员30行代码素描表白!网友:花里胡哨

    总有人说程序员不够浪漫!其实我们只是没时间而已,等我们有时间了,还有普通人什么事儿?最近就有一个小伙伴上热搜了! 原来他用Python给可爱的女朋友画了一幅素描!不到30行代码,一起来学学给她一个惊喜 ...

  6. 用python画苹果的logo_简单几步,100行代码用Python画一个蝙蝠侠的logo

    转自:菜鸟学Python 简单几步,100行代码用Python画一个蝙蝠侠的logo-1.jpg (35.33 KB, 下载次数: 0) 2020-7-30 12:04 上传 蝙蝠侠作为DC漫画的核心 ...

  7. 初次玩pyecharts:30行代码做一个可视化广东省各地天气温度排行图

    初次玩pyecharts:30行代码做一个可视化广东省各地天气温度排行图 开篇点题,直接上效果图 开篇再点题,直接上源码 import re import requests from pyechart ...

  8. python画画100行代码_简单几步,100行代码用Python画一个蝙蝠侠的logo

    原标题:简单几步,100行代码用Python画一个蝙蝠侠的logo 转自:菜鸟学Python 蝙蝠侠作为DC漫画的核心人物之一,一直都受到广大粉丝的喜爱,而笔者作为DC的铁杆粉丝,自然也是老爷(粉丝对 ...

  9. python你TM太皮了——区区30行代码就能记录键盘的一举一动

    先看看效果 Like This↓ 一.公共WiFi 公用电脑什么的 在我们日常在线上工作.玩耍时,不论开电脑.登录淘宝.玩网游 统统都会用到键盘输入 在几乎所有网站,例如淘宝.百度.126邮箱等等 为 ...

最新文章

  1. thrift - C#(CSharp)客户端连接池(ConnectionPool)
  2. shell查找符号链接及其指向目标的方法
  3. 折叠屏市场价值在哪里?
  4. 572. 另一个树的子树
  5. C#_自动化测试 (四) 自动卸载软件
  6. How to write a custom control with NSControl ...
  7. for循环与each遍历的跳出循环方式
  8. poj 1860 Currency Exchange (SPFA、正权回路 bellman-ford)
  9. Linux下MariaDB 安装及root密码设置(修改)
  10. 一个类的类类型是Class类的实例,即类的字节码
  11. python 遗传算法 agv_遗传算法在AGV的路径规划中的应用
  12. gnuplot 入门教程 1
  13. 计算机联锁人工进路的办理,计算机联锁与6502
  14. EXCEL startup.exe 宏病毒
  15. kill linux 苹果_Linux 下的KILL函数的用法
  16. “竞速”智能网联汽车,领头雁为何是长沙?
  17. 管理者,最重要的100句话
  18. gpu虚拟化云服务器,gpu云服务器 虚拟化
  19. pHP分析网站日志,通过用数据挖掘技术来分析Web网站日志?
  20. 存储需求大幅增长,企业如何应对挑战?

热门文章

  1. 多节点单进程Nodelet
  2. 小红书爆款笔记推送周期是多久?做小红书是视频好还是图文好
  3. 7-5 分而治之 (25 分)
  4. Java 敏感词过滤,Java 敏感词替换,Java 敏感词工具类
  5. 猛回头 一个华为次老员工中的华为人
  6. c语言中lookup函数功能,查询引用之王——Lookup函数实用技巧解读!
  7. alibaba.jym.item.external.goods.batch.offsale( 交易猫外部商家批量下架商品接口 )
  8. 抽样技术--简单随机抽样
  9. win7喇叭红叉耳机扬声器已拔出驱动无法修复
  10. 如何通过 Apple Watch 解锁 Mac !