[PYTHON] I converted the time to an integer, factored it into prime factors, and made a bot to tweet the result (xkcd material)

Introduction

It's been three months since I registered for the application with enthusiasm, "I'll use Twitter with Python!" When I was thinking that I had to make something, I found this story on xkcd. Factoring the Time - xkcd.com factoring_the_time.png I created a bot that automates the work of factoring the time into prime factors, which this man (?) Was killing time, and tweeting the result. It works like this. bot.jpg

environment

procedure

Anyway, it is application registration. Since many articles have been written, I will omit it here. If you google for "twitter python registration", you should see some.

Create a file called token and write the obtained character string to it.

token


"Consumer Key"
"Consumer Secret"
"Access Token"
"Access Secret"

After writing like this, create main.py in the same directory and edit it.

main.py


# coding:utf-8
import tweepy
from datetime import datetime
import sympy
import time


def login():
    with open("token") as f:
        (consumer_key,
         consumer_secret,
         access_token,
         access_secret) = f.read().split("\n")[:4]
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_secret)
    api = tweepy.API(auth)
    return api


def get_factor_by_string(i):
    d = sympy.factorint(i)
    return "*".join(str(fact) for fact in d for num in range(d[fact]))


def get_time_by_int():
    return int(datetime.now().strftime('%H%M'))


def main():
    api = login()
    old = get_time_by_int()
    while True:
        now = get_time_by_int()
        if now != old and now != 0 and now != 1:
            old = now
            factor = get_factor_by_string(now)
            if "*" in factor:
                text = str(now) + "=" + factor
            else:
                text = str(now) + " is a prime number"
            api.update_status(text)
        time.sleep(0.1)


if __name__ == '__main__':
    main()

When executed, it will tweet the result of factoring the time almost every minute. You did it!

Commentary

I don't think it's necessary, but for the time being ... The flow of the program is like this ① twitter authentication with tweepy ② Get the current time with datetime ③ Return to ② if the time has already been tweeted ④ Prime factorization and format change with sympy ⑤ Tweet the result (return to ②) Twitter is authenticated using the information in token with login (). Use datetime.now (). Strftime () with get_time_by_int () to get the number of the present tense and the present tense (like 12:30 → 1230). Here, if the time has already been tweeted, or if the number returned is 0 or 1, the next process will not start. I use sympy.factorint () for prime factorization. The result is returned in the dictionary type {prime factor: exponent, prime factor: exponent ...}, so use for to convert it to a form of multiplication without exponent. Finally, change the message depending on whether the result of prime factorization contains * (whether the time number is a prime number) and tweet with ʻapi.update.status ()`. As a result of relying on the library for almost all of the processing, it fits in less than 50 lines. Python is amazing.

in conclusion

It was my first bot creation, but I found that it was fairly easy to create a simple one. I'm running it properly, so it sometimes stops, but I want to move it for a few more days.

Recommended Posts

I converted the time to an integer, factored it into prime factors, and made a bot to tweet the result (xkcd material)
I made a POST script to create an issue on Github and register it in the Project
I ran GhostScript with python, split the PDF into pages, and converted it to a JPEG image.
I don't like to be frustrated with the release of Pokemon Go, so I made a script to detect the release and tweet it
An easy way to view the time taken in Python and a smarter way to improve it
I made a Line bot that guesses the gender and age of a person from an image
I want to record the execution time and keep a log.
I made a chatbot with Tensor2Tensor and this time it worked
I started to work at different times, so I made a bot that tells me the time to leave
I made a tool to estimate the execution time of cron (+ PyPI debut)
I made a tool to notify Slack of Connpass events and made it Terraform
I want to make a music player and file music at the same time
I made an appdo command to execute a command in the context of the app
I made an image classification model and tried to move it on mobile
I want to store the result of% time, %% time, etc. in an object (variable)
I made a tool in Python that right-clicks an Excel file and divides it into files for each sheet.
I made a program to convert images into ASCII art with Python and OpenCV
A Python beginner made a chat bot, so I tried to summarize how to make it.
How to test the current time with Go (I made a very thin library)
I made a program in Python that changes the 1-minute data of FX to an arbitrary time frame (1 hour frame, etc.)
I made a LINE BOT with Python and Heroku
I made a tool that makes it a little easier to create and install a public key.
I made a class to get the analysis result by MeCab in ndarray 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 made a method to automatically select and visualize an appropriate graph for pandas DataFrame