python 毎日英语の名言をでつぶやく机器人
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 毎日英语の名言をでつぶやく机器人相关的知识,希望对你有一定的参考价值。
# -*- coding: utf-8 -*-
from peewee import *
from datetime import datetime
from enum import Enum
import tweepy
import yaml
"""
Tweet English Quotes.
Copyright 2017 sawada makoto.
"""
# Sqlite3
database = SqliteDatabase('e://Programming/quotes.db')
# Define Models.
class Author(Model):
'''
Authors
'''
name = CharField(unique=True)
created_at = DateTimeField(default=datetime.now)
class Meta:
database = database
class Quote(Model):
'''
Quotes
'''
author = ForeignKeyField(Author, related_name='quotes')
quote = TextField()
created_at = DateTimeField(default=datetime.now)
class Meta:
database = database
class TweetHistory(Model):
'''
Tweet History.
'''
message = TextField()
created_at = DateTimeField(default=datetime.now)
class Meta:
database = database
class Log(Model):
'''
Application Log.
'''
Level = CharField()
message = TextField()
created_at = DateTimeField(default=datetime.now)
class Meta:
database = database
# LogLevel
LogLevel = Enum('LogLevel', 'trace debug info warn error')
# Attached Hashtag
HASH_TAG = '#el_ec'
def main():
'''
Main
'''
# Create Table If Not Exists.
database.connect()
create_tables_if_not_exists([Author, Quote, TweetHistory, Log])
log(LogLevel.info, 'English Quotes Tweet Bot Start.')
# Config
config = yaml.load(open('e://Programming/el-twitter-english-quotes-bot/config.yaml', 'r+'))
log(LogLevel.debug, config)
# Get Random Quote 1 Record From Quotes Table.
quote = Quote.select().order_by(fn.Random()).limit(1).first()
try:
quote_with_author = '{quote}ー{author}'.format(quote=quote.quote, author=quote.author.name)
log(LogLevel.debug, quote_with_author)
# Tweet
tweet(config, quote_with_author)
except Exception as e:
log(LogLevel.error, "Failed Tweet. MESSAGE={msg}".format(msg=e))
log(LogLevel.info, "English Quotes Tweet Bot End.")
def create_tables_if_not_exists(models):
'''
Create Table If Not Exists.
'''
for model in models:
if not model.table_exists():
model.create_table()
def tweet(config, quote):
'''
Tweet
'''
# Get Tweepy API.
auth = tweepy.OAuthHandler(config['twitter']['consumer_key'], config['twitter']['consumer_key_secret'])
auth.set_access_token(config['twitter']['access_token'], config['twitter']['access_token_secret'])
api = tweepy.API(auth)
# Tweet Quote.
api.update_status(quote + ' ' + HASH_TAG)
pass
def log(level, message):
'''
Log To STDOUT And Database.
'''
print('[{level}]Time={time} Message={message}'.format(time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), level=level.name.ljust(5), message=message))
Log(Level=level.name, message=message).save()
if __name__ == '__main__':
main()
以上是关于python 毎日英语の名言をでつぶやく机器人的主要内容,如果未能解决你的问题,请参考以下文章