<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Marie Lauture on Medium]]></title>
        <description><![CDATA[Stories by Marie Lauture on Medium]]></description>
        <link>https://medium.com/@marie.lauture?source=rss-3d2eee78e704------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Marie Lauture on Medium</title>
            <link>https://medium.com/@marie.lauture?source=rss-3d2eee78e704------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:10:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marie.lauture/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Tutorial : How to build a news bot to track your interests using Apache Airflow, Python and…]]></title>
            <link>https://medium.com/@marie.lauture/tutorial-how-to-build-a-news-bot-to-track-your-interests-using-apache-airflow-python-and-d1cc2eb353a1?source=rss-3d2eee78e704------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1cc2eb353a1</guid>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[google-search-api]]></category>
            <dc:creator><![CDATA[Marie Lauture]]></dc:creator>
            <pubDate>Fri, 30 Aug 2024 14:19:55 GMT</pubDate>
            <atom:updated>2024-08-30T14:19:55.167Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tutorial : How to build a news bot to track your interests using Apache Airflow, Python and PostgreSQL with the Google Search API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ywfmEbN9VoGWhlmnqgg3w.png" /></figure><h3>Table of Contents</h3><ul><li><a href="https://medium.com/@marie.lauture/d1cc2eb353a1#791a">Introduction</a></li><li><a href="https://medium.com/@marie.lauture/d1cc2eb353a1#d963">Prerequisites</a></li><li><a href="https://medium.com/@marie.lauture/d1cc2eb353a1#a157">Create a search engine and get an API key</a></li><li><a href="https://medium.com/@marie.lauture/d1cc2eb353a1#be43">Enable airflow virtual environment</a></li><li><a href="https://medium.com/@marie.lauture/d1cc2eb353a1#568d">Define our search terms</a></li><li><a href="https://medium.com/@marie.lauture/d1cc2eb353a1#232a">Set up the DAG</a></li><li><a href="https://medium.com/@marie.lauture/d1cc2eb353a1#e274">Read search queries</a></li><li><a href="https://medium.com/@marie.lauture/d1cc2eb353a1#aa71">Get Results</a></li><li><a href="https://medium.com/@marie.lauture/d1cc2eb353a1#a248">Clean results</a></li><li><a href="https://medium.com/@marie.lauture/d1cc2eb353a1#b730">Store results</a></li><li><a href="https://medium.com/@marie.lauture/d1cc2eb353a1#b392">Define User Queries</a></li><li><a href="https://medium.com/@marie.lauture/d1cc2eb353a1#8dea">Generate and Send Emails</a></li><li><a href="https://medium.com/@marie.lauture/d1cc2eb353a1#883f">Define task execution order</a></li></ul><h3><strong>Introduction</strong></h3><p>In this story, we’ll build a news bot using Apache Airflow to automate the process of collecting, cleaning, storing, and emailing relevant news articles to specific users. We’ll use technologies such as Python, PostgreSQL, the Google Custom Search API, and various Airflow tools such as Python and Email operators.</p><h3>Prerequisites</h3><ul><li><strong>Apache Airflow :</strong> First, we need to set up Apache Airflow on our working environment. Here’s a tutorial for Ubuntu users : <a href="https://medium.com/@j3amail/discover-apache-airflow-by-setting-up-a-working-environment-on-ubuntu-with-postgresql-and-ssl-6fbe2e0d5440">https://medium.com/@j3amail/discover-apache-airflow-by-setting-up-a-working-environment-on-ubuntu-with-postgresql-and-ssl-6fbe2e0d5440</a></li><li><strong>Python libraries :</strong> Make sure you have these libraries on your workspace :</li></ul><pre>requests<br>psycopg2<br>pendulum<br>google-api-python-client<br>datetime<br>json<br>logging<br>psycopg2<br>re<br>os</pre><ul><li><strong>PostgreSQL</strong></li></ul><h3><strong>Create a search engine and get an API key</strong></h3><p>To retrieve our articles, we’ll use the Google Search API, the free version of which allows up to 100 free queries per day. All we need to use it is a Google account.</p><p>To create our search engine, we go to this page :</p><p><a href="https://programmablesearchengine.google.com/controlpanel/all?hl=en">Sign in</a></p><figure><img alt="Custom Search Engine home page" src="https://cdn-images-1.medium.com/max/1024/1*EiJ49uJA5-0Wfo4re15gaQ.png" /><figcaption>This is the home page, if we already had search engines they would be displayed here but let’s go through the steps to create one. 1. Click on the “Add” button.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*ng8YJkt02vmbTLU-qsomdQ.png" /><figcaption>2. We enter the name we want for our search engine, then make sure we select “search the entire web” so that our news bot will get results from everywhere.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*kaQWVg29g_5bYjTNKeob_w.png" /><figcaption>3. Now our search engine is functional ! Click on “Customize” to get an overview of its characteristics.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*fIIxCeQOIqJWcwx442baJw.png" /><figcaption>4. Here we can get our Search Engine ID</figcaption></figure><p>Now we need to get our API Key, we’ll use this page :</p><p><a href="https://developers.google.com/custom-search/v1/overview?hl=en">Custom Search JSON API | Programmable Search Engine | Google for Developers</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*0VEj9ZZ0quRCBLkX28Dgqw.png" /><figcaption>We need to scroll down and click on the “Get a Key” button.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*p9_s_bqBw48ELPMFbhhmAQ.png" /><figcaption>Here we can choose from existing projects, or create one. We’ll click on “Create a new project”, then choose a name and click “Next”.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*_6i7vQmZzj2-4PezvOAoHg.png" /><figcaption>Now we can get our API key.</figcaption></figure><h3>Enable airflow virtual environment</h3><pre>source path/to/airflow/airflow-env/bin/activate</pre><h3><strong>Define our search terms</strong></h3><p>We group the queries we think are interesting in a JSON file based on this template (search_queries.json):</p><pre>[<br>    {<br>        &quot;label&quot;: &quot;About XXX&quot;,<br>        &quot;query&quot;: &quot;after:YYYY-MM-DD AND (XXX  OR YYY OR  ZZZ)&quot;<br>    },{<br>        &quot;label&quot;: &quot;About YYY&quot;,<br>        &quot;query&quot;: &quot;after:YYYY-MM-DD AND (site:XXX OR site:YYY OR site:ZZZ)&quot;<br>    },{<br>        &quot;label&quot;: &quot;About ZZZ&quot;,<br>        &quot;query&quot;: &quot;after:YYYY-MM-DD AND (site:XXX OR site:YYY OR site:ZZZ) AND (XXX  OR YYY OR  ZZZ)&quot;<br>    }<br>]</pre><ul><li>Label : Allows users to choose which search they want to subscribe to</li><li>Query : based on Google search syntax (here is a page that can help you refine your search)</li></ul><p><a href="https://www.google.com/advanced_search">Google Advanced Search</a></p><h3>Set up the DAG</h3><p>Create a ‘newsbot’ directory in the ‘dags’ directory of your Airflow installation, then create a file and name it ‘main.py’. Create, a ‘data’ directory (we can put our queries file there), and finally set up the basic structure :</p><pre>from airflow import DAG<br>from airflow.operators.python import PythonOperator<br>from airflow.operators.email import EmailOperator<br>from airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator<br>from airflow.hooks.base import BaseHook<br>from airflow.utils.dates import days_ago<br>from datetime import datetime, timedelta<br>import json<br>import requests<br>import pendulum<br>import logging<br>import psycopg2<br>import re<br>import os<br><br>DATA_DIRECTORY=&quot;/path/to/airflow/dags/newsbot/data/&quot;<br>API_KEY = YOUR_API_KEY<br>CX = YOUR_CX_ID<br><br>default_args = {<br>    &#39;owner&#39;: &#39;YOUR_NAME&#39;,<br>    &#39;start_date&#39;: days_ago(1),<br>    &#39;retries&#39;: 5,<br>    &#39;retry_delay&#39;: timedelta(minutes=5),<br>}<br><br># We&#39;ll add our functions here<br><br>with DAG(<br>    &#39;Newsbot&#39;, <br>    default_args=default_args, <br>    schedule_interval=&#39;0 6* * *&#39;, #To be ran at 6:00 am everyday<br>    catchup=False,<br>) as dag:<br>    # We&#39;ll add our tasks here</pre><h3><strong>Read search queries</strong></h3><p>Define a function to read search queries from a JSON file:</p><pre># Function<br>def read_queries_from_json(ti, search_queries_file):<br>    with open(search_queries_file, &#39;r&#39;, encoding=&#39;utf-8&#39;) as f:<br>        search_queries_data = json.load(f)<br>    queries_list = [{&#39;label&#39;: q[&#39;label&#39;], &#39;query&#39;: q[&#39;query&#39;].replace(&#39;YYYY-MM-DD&#39;, pendulum.now().subtract(days=1).to_date_string())} for q in search_queries_data]<br>    ti.xcom_push(key=&#39;queries_list&#39;, value=queries_list)<br><br># Task<br>read_search_terms_task = PythonOperator(<br>    task_id=&#39;read_queries&#39;,<br>    python_callable=read_queries_from_json,<br>    op_kwargs={&#39;search_queries_file&#39;: &#39;/path/to/search_queries.json&#39;}<br>)</pre><h3>Get Results</h3><pre># Function<br>def search_names_on_internet(ti):<br>    queries_list = ti.xcom_pull(task_ids=&#39;read_queries&#39;, key=&#39;queries_list&#39;)<br>    search_results = {}<br>    for query_info in queries_list:<br>        response = requests.get(<br>            &quot;https://www.googleapis.com/customsearch/v1&quot;,<br>            params={&quot;q&quot;: query_info[&#39;query&#39;], &quot;key&quot;: &#39;YOUR_API_KEY&#39;, &quot;cx&quot;: &#39;YOUR_CX_ID&#39;, &quot;sort&quot;: &quot;date&quot;, &quot;num&quot;: 5} # For each query, we want the 5 latest articles<br>        )<br>        if response.status_code == 200:<br>            search_results[query_info[&#39;label&#39;]] = response.json()<br>    ti.xcom_push(key=&#39;search_results&#39;, value=json.dumps(search_results))<br><br># Task<br>search_task = PythonOperator(<br>    task_id=&#39;search_names&#39;,<br>    python_callable=search_names_on_internet<br>)</pre><h3><strong>Clean results</strong></h3><p>We only want a bunch of information from the results, like for example the title, link, date, and a short snippet, so we only take those before continuing</p><pre># Function<br>def clean_search_results(ti):<br>    search_results = json.loads(ti.xcom_pull(task_ids=&#39;search_names&#39;, key=&#39;search_results&#39;))<br>    cleaned_results = {label: [{&#39;title&#39;: item[&#39;title&#39;], &#39;link&#39;: item[&#39;link&#39;], &#39;snippet&#39;: item[&#39;snippet&#39;]} for item in results.get(&#39;items&#39;, [])] for label, results in search_results.items()}<br>    ti.xcom_push(key=&#39;cleaned_results&#39;, value=cleaned_results)<br><br># Task<br>clean_results_task = PythonOperator(<br>    task_id=&#39;clean_results&#39;,<br>    python_callable=clean_search_results<br>)</pre><h3><strong>Store results</strong></h3><p>We’ll store the search results so that we can have an history in case there’s an error with emails</p><pre># Function<br>def store_in_postgres(ti):<br>    cleaned_results = ti.xcom_pull(task_ids=&#39;clean_results&#39;, key=&#39;cleaned_results&#39;)<br>    conn = BaseHook.get_connection(&#39;postgres_default&#39;)<br>    db_conn = psycopg2.connect(<br>        dbname=conn.schema, user=conn.login, password=conn.password, host=conn.host, port=conn.port<br>    )<br>    cursor = db_conn.cursor()<br>    for label, results in cleaned_results.items():<br>        for result in results:<br>            cursor.execute(<br>                &quot;INSERT INTO search_results (label, title, link, snippet, date) VALUES (%s, %s, %s, %s, %s)&quot;,<br>                (label, result[&#39;title&#39;], result[&#39;link&#39;], result[&#39;snippet&#39;], pendulum.now().subtract(days=1).to_date_string())<br>            )<br>    db_conn.commit()<br>    cursor.close()<br>    db_conn.close()<br><br># Task<br>store_results_in_postgres = PythonOperator(<br>    task_id=&#39;store_results_in_postgres&#39;,<br>    python_callable=store_in_postgres<br>)</pre><h3>Define User Queries</h3><p>We write each users interests in a JSON file based on this template (user_queries.json) :</p><pre>[<br>    {<br>        &quot;email&quot;: &quot;email1@example.com&quot;,<br>        &quot;queries&quot;: [<br>            &quot;About XXX&quot;,<br>            &quot;About YYY&quot;,<br>            &quot;About ZZZ&quot;<br>        ]<br>    },<br>    {<br>        &quot;email&quot;: &quot;email2@example.com&quot;,<br>        &quot;queries&quot;: [<br>            &quot;About XXX&quot;,<br>            &quot;About ZZZ&quot;<br>        ]<br>    },<br>    {<br>        &quot;email&quot;: &quot;email3@example.com&quot;,<br>        &quot;queries&quot;: [<br>            &quot;About XXX&quot;,<br>            &quot;About YYY&quot;,<br>        ]<br>    }<br>]</pre><h3>Generate and Send Emails</h3><p>Define functions to read user queries, filter articles, and generate email content:</p><pre># Functions<br>def read_user_queries_from_json():<br>    with open(&#39;/path/to/user_queries.json&#39;, &#39;r&#39;, encoding=&#39;utf-8&#39;) as f:<br>        return json.load(f)<br><br>def generate_email_content(user_email, filtered_articles):<br>    email_content = &quot;&lt;html&gt;&lt;body&gt;&lt;h1&gt;Daily Newsletter&lt;/h1&gt;&quot;<br>    for article in filtered_articles:<br>        email_content += f&quot;&lt;div&gt;&lt;h2&gt;{article[&#39;title&#39;]}&lt;/h2&gt;&lt;p&gt;{article[&#39;snippet&#39;]}&lt;/p&gt;&lt;a href=&#39;{article[&#39;link&#39;]}&#39;&gt;{article[&#39;link&#39;]}&lt;/a&gt;&lt;/div&gt;&quot;<br>    email_content += &quot;&lt;/body&gt;&lt;/html&gt;&quot;<br>    return email_content<br><br># Task<br>read_user_queries_task = PythonOperator(<br>    task_id=&#39;read_user_queries_from_json&#39;,<br>    python_callable=read_user_queries_from_json,<br>)</pre><h4>Dynamic Email Tasks</h4><p>Create dynamic email tasks for each user so that each user recieves a personnalized email</p><pre># Tasks<br><br>user_queries = read_user_queries_from_json()<br>email_tasks = []<br>for user in user_queries:<br>    email = user[&#39;email&#39;]<br>    queries = user[&#39;queries&#39;]<br>    filtered_articles = filter_articles_for_user(email, queries, articles)<br>    email_content = generate_email_content(email, filtered_articles)<br><br>    send_email_task = EmailOperator(<br>        task_id=f&#39;send_email_to_{email.replace(&quot;@&quot;, &quot;_&quot;).replace(&quot;.&quot;, &quot;_&quot;)}&#39;,<br>        to=email,<br>        subject=&#39;Daily Newsletter&#39;,<br>        html_content=email_content,<br>    )<br>    email_tasks.append(send_email_task)<br>    read_user_queries_task &gt;&gt; send_email_task</pre><h3>Define task execution order</h3><pre>with DAG(<br>    ...<br>) as dag:<br><br>    ...<br><br>    read_search_terms_task &gt;&gt; search_task &gt;&gt; clean_results_task &gt;&gt; store_results_in_postgres &gt;&gt; read_user_queries_task</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1cc2eb353a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>