[PYTHON] I made a Docker Image that reads RSS and automatically tweets regularly and released it.

Introduction

I was implementing RSS regular tweets with ifttt, but I made it myself because the restrictions were strict.

Finished product

https://hub.docker.com/r/hashito/tweetrss

docker run -it --rm \
    -e RSS_URL=https://news.google.com/rss/search?hl=ja&gl=JP&ceid=JP:ja&q=twitter \
    -e CONSUMER_KEY=x \
    -e CONSUMER_SECRET=x \
    -e ACCESS_TOKEN=x \
    -e ACCESS_TOKEN_SECRET=x \
    -e 'ADD_TEXT="#rss2tweet"' \
    hashito/tweetrss

From above

You can do it by inserting. If you want to change the Tweet cycle, play with SCAN_SPAN and TWEET_DELAY. (Both are seconds) Be careful as you get angry if you tweet too much ...

Also, if you have a cash value internally and rebuild it, you will forget how far you read RSS last time.

Let's create a file like the one below and mount it.

contents


{}

-v {you chash file}:/root/cash

(It's awkward around here ... I'll fix it someday)

Source code

The source is simple. Read RSS and Tweet it regularly. RSS retains the ID and does not target the same ID. If the same ID is not received for a certain period of time, the ID will be discarded.

import feedparser
import json
import os
import time
import datetime
import json
from requests_oauthlib import OAuth1Session

RSS_URL=os.environ["RSS_URL"]
CONSUMER_KEY=os.environ["CONSUMER_KEY"]
CONSUMER_SECRET=os.environ["CONSUMER_SECRET"]
ACCESS_TOKEN=os.environ["ACCESS_TOKEN"]
ACCESS_TOKEN_SECRET=os.environ["ACCESS_TOKEN_SECRET"]

CASH_FILE=os.environ["CASH_FILE"]
ADD_TEXT=os.environ["ADD_TEXT"]
SCAN_SPAN=int(os.environ["SCAN_SPAN"])
TWEET_DELAY=int(os.environ["TWEET_DELAY"])


def cash_read():
    with open(CASH_FILE) as f:
        return json.loads(f.read())

def cash_write(data):
    with open(CASH_FILE,mode="w") as f:
        f.write(json.dumps(data,ensure_ascii=False))

def read_rss():
    return feedparser.parse(RSS_URL)
    
def send_tweet(text):
    twitter = OAuth1Session(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) #Authentication process
    url = "https://api.twitter.com/1.1/statuses/update.json" #Tweet post endpoint
    params = {"status" : text}
    res = twitter.post(url, params = params) #post send
    return res.status_code == 200

if(__name__ == '__main__'):
    cash=cash_read()
    print("cash:",cash)
    while(1):
        tm=datetime.datetime.now().timestamp()
        rss=read_rss()
        for i in rss["entries"]:
            if(not i["id"] in cash):
                print("tweet:",f"{i['title']} {i['link']} {ADD_TEXT}")
                send_tweet(f"{i['title']} {i['link']} {ADD_TEXT}")
                time.sleep(TWEET_DELAY)
            cash[i["id"]]=tm
            cash_write(cash)
        for k in list(cash.keys()):
            if((cash[k]+60)<tm):
                print("delete:",k,cash[k],tm)
                cash.pop(k)
        time.sleep(SCAN_SPAN)

docker file This is also simple. Install requirements.txt using the image of python3. It's like preparing environment variables and starting them.

  
FROM python:3
COPY . /root/

RUN pip install -r /root/requirements.txt

ENV RSS_URL=https://news.google.com/rss/search?hl=ja&gl=JP&ceid=JP:ja&q=twitter \
    CONSUMER_KEY=x \
    CONSUMER_SECRET=x \
    ACCESS_TOKEN=x \
    ACCESS_TOKEN_SECRET=x \
    CASH_FILE=/root/cash \
    ADD_TEXT="#rss2tweet" \
    SCAN_SPAN=600 \
    TWEET_DELAY=150

CMD ["python","/root/main.py"]

Recommended Posts

I made a Docker Image that reads RSS and automatically tweets regularly and released it.
I made a Docker image that can call FBX SDK Python from Node.js
I made a system that automatically decides whether to run tomorrow with Python and adds it to Google Calendar.
I made a web application that maps IT event information with Vue and Flask
I made a tool that makes it a little easier to create and install a public key.
Steps to create a Job that pulls a Docker image and tests it with Github Actions
[Python3] I made a decorator that declares undefined functions and methods.
I want to create a pipfile and reflect it in docker
I made a program that automatically calculates the zodiac with tkinter
I made a chatbot with Tensor2Tensor and this time it worked
I made a calendar that automatically updates the distribution schedule of Vtuber
I made a Discord bot in Python that translates when it reacts
A python program that resizes a video and turns it into an image
I made a program in Python that reads CSV data of FX and creates a large amount of chart images
[Python] I made a script that automatically cuts and pastes files on a local PC to an external SSD.
I made a LINE BOT that returns a terrorist image using the Flickr API
I made a tool to notify Slack of Connpass events and made it Terraform
[Python] I made a LINE Bot that detects faces and performs mosaic processing.
I made an image classification model and tried to move it on mobile
I made a system with Raspberry Pi that regularly measures the discomfort index of the room and sends a LINE notification if it is a dangerous value
I made a tool in Python that right-clicks an Excel file and divides it into files for each sheet.
I made a simple RSS reader ~ C edition ~
I made a QR code image with CuteR
A Python script that crawls RSS in Azure Status and posts it to Hipchat
I made a KMEANS initialization process that is faster and more accurate than random.
A simple system that automatically shoots with object detection and sends it to LINE
Image processing with Python (I tried binarizing it into a mosaic art of 0 and 1)
I made a calendar that automatically updates the distribution schedule of Vtuber (Google Calendar edition)
I made a twitter app that identifies and saves the image of a specific character on the twitter timeline by pytorch transfer learning
I made a tool to automatically generate a state transition diagram that can be used for both web development and application development
I made a ready-to-use syslog server with Play with Docker
I made a VM that runs OpenCV for Python
I made a LINE BOT with Python and Heroku
[Python] I made a function that decrypts AES encryption just by throwing it with pycrypto.
I made a toolsver that spits out OS, Python, modules and tool versions to Markdown
A story that I wondered if it stopped working at mglearn.plots.plot_nmf_faces and was an error?
When I deploy a Django app with Apache2 and it no longer reads static files
I made a program to collect images in tweets that I liked on twitter with Python
I made a server with Python socket and ssl and tried to access it from a browser
I made a function to crop the image of python openCV, so please use it.
I tried to make a bot that randomly acquires Wikipedia articles and tweets once a day
A story that made it possible to automatically create anison playlists from your music files
I made a tool that makes it convenient to set parameters for machine learning models.
I made a method to automatically select and visualize an appropriate graph for pandas DataFrame
I automatically collected my Qiita post data with Raspberry Pi and notified it regularly with Slack
I tried to make a script that traces the tweets of a specific user on Twitter and saves the posted image at once