[PYTHON] Create a bot to retweet coronavirus information

Deliverables

Twitterbot that automatically retweets coronavirus-related tweets sent by Japanese public institutions

https://twitter.com/CovidJaGovRT

Background and purpose

Is there anything I can do on my own with growing anxiety about the coronavirus every day? I thought. Therefore, I recently created an app that uses the twitter API, and I think it can be used to spread correct coronavirus information. However, since I don't have any knowledge of viruses, I can't judge what is the correct information, let alone spread the wrong information and confuse it, so I want to avoid it. Among them, I came up with the idea that I could use the coronavirus information sent by local governments and ministries that are public institutions. I want you to be accurate and to know more about the information provided by people who work for residents in public institutions. With that in mind, I created a bot that retweets tweets about coronavirus information from public institutions.

Main technologies used

Overview

--Get a tweet with "Corona" or "COVID" from your timeline on Twitter and like RT --Follow only public institutions so that only public institutions can be output on the timeline --Matching is done with regular expressions --Start every 20 minutes using AWSCloudWatchEvents cron

Applicable source

serverless.yml


service: gov-info-COVID-19

plugins:
  - serverless-python-requirements

provider:
  name: aws
  runtime: python3.8
  stage: prod
  region: ap-northeast-1

custom:
  defaultStage: prod
  profiles:
    prod: sls
  otherfile:
    environment:
      prod: ${file(env.yml)}

functions:
  RT_bot:
    handler: handler.main
    events:
      - schedule: cron(*/20 * * * ? *)
    environment:
      CONSUMER_KEY: ${self:custom.otherfile.environment.${self:provider.stage}.CONSUMER_KEY}
      CONSUMER_SECRET: ${self:custom.otherfile.environment.${self:provider.stage}.CONSUMER_SECRET}
      ACCESS_TOKEN: ${self:custom.otherfile.environment.${self:provider.stage}.ACCESS_TOKEN}
      ACCESS_TOKEN_SECRET: ${self:custom.otherfile.environment.${self:provider.stage}.ACCESS_TOKEN_SECRET}

handler.py


import configparser
import json
import os
import sys
import re
import logging
import traceback
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
from lib import tweepy

#For local development
OAUTH_INI = configparser.ConfigParser()
OAUTH_INI.read('oauth.ini', encoding='utf-8')
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']


def main(event, context):
    tweepy_api = tweepy_oath()
    retweet(tweepy_api)

#twitter API authentication
def tweepy_oath():
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
    return tweepy.API(auth)

#Retweet tweets containing the target word from your timeline
def retweet(tweepy_api):
    exclude_exp_obj = re.compile(r'.*(corona|COVID)(.|\s)*$')

    for tweet in tweepy_api.home_timeline(count=200):
        if exclude_exp_obj.match(tweet.text):
            id = tweet.id

            try:
                tweepy_api.create_favorite(id)
                tweepy_api.retweet(id)
            #Exception occurrence leaves only log and does not stop processing
            except:
                logging.error(traceback.format_exc())
                pass

in conclusion

I sincerely hope that the coronavirus will settle down and return to peace as soon as possible.

Recommended Posts

Create a bot to retweet coronavirus information
Create a slack bot
Steps to create a Twitter bot with python
Create a Mastodon bot with a function to automatically reply with Python
I tried to create a bot for PES event notification
Steps to create a Django project
How to make a slack bot
How to create a Conda package
How to create a virtual bridge
How to create a Dockerfile (basic)
5 Ways to Create a Python Chatbot
How to create a config file
Create a LINE Bot in Django
I tried to create a linebot (implementation)
How to create a clone from Github
How to create a git clone folder
I tried to create a linebot (preparation)
[Python] [LINE Bot] Create a parrot return LINE Bot
Various ways to create a dictionary (memories)
How to create a repository from media
Script to create a Mac dictionary file
Create a bot that boosts Twitter trends
Create a bot that posts the number of people positive for the new coronavirus in Tokyo to Slack
[Python] List Comprehension Various ways to create a list
Edit Excel from Python to create a PivotTable
I want to easily create a Noise Model
How to create a Python virtual environment (venv)
How to create a function object from a string
Create a LINE BOT with Minette for Python
I want to create a window in Python
Randomly sample MNIST data to create a dataset
How to create a JSON file in Python
[Note] Discord Bot ① Create Bot-Reply to specific content
If you want to create a Word Cloud.
Create a command to encode / decode Splunk base64
Use click to create a sub-sub command --netsted sub-sub command -
Try to create a new command on linux
How to create a shortcut command for LINUX
I want to create a plug-in type implementation
[Note] How to create a Ruby development environment
How to create a Kivy 1-line input box
How to create a multi-platform app with kivy
How to create a Rest Api in Django
[LINE WORKS version Trello Bot] How to create a private talk room including a talk bot
Create a command to get the work log
[Note] How to create a Mac development environment
I tried scraping food recall information with Python to create a pandas data frame
Read the Python-Markdown source: How to create a parser
Create a dataset of images to use for learning
A memo to create a virtual environment (venv) before Django
Create a data collection bot in Python using Selenium
I tried to create a table only with Django
Create a function to visualize / evaluate the clustering result
How to create a submenu with the [Blender] plugin
Try to dynamically create a Checkbutton with Python's Tkinter
Scraping your Qiita articles to create a word cloud
Create a plugin to run Python Doctest in Vim (2)
[Go] How to create a custom error for Sentry
Create a plugin to run Python Doctest in Vim (1)
How to create a local repository for Linux OS
I want to manually create a legend with matplotlib