· 6 years ago · Sep 19, 2019, 07:18 AM
1#!/usr/bin/env python2
2# -*- coding: utf-8 -*-
3
4### DB Schema
5# CREATE TABLE `pics` ( `id`INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, `filename`TEXT NOT NULL UNIQUE, `description`TEXT NOT NULL DEFAULT '東山奈央', `added`INTEGER NOT NULL DEFAULT 0, `lastTimeTweeted`INTEGER NOT NULL DEFAULT 0 )
6
7from TwitterAPI import TwitterAPI
8import warnings, random, time, sqlite3, sys
9
10### Variables
11# Time between each picture in seconds, this is just for checks, the script runs from a cronjob with a lower interval (for new pictures, eg every 30 minutes)
12tweetEvery = 3500
13
14### Functions
15def log(message):
16 print time.strftime("%Y/%m/%d %H:%M:%S") + " ~ " + message
17
18### DB
19conn = sqlite3.connect('pics/up/naobou.db')
20c = conn.cursor()
21
22#Set up things for Twitter
23CONSUMER_KEY = ''
24CONSUMER_SECRET = ''
25ACCESS_KEY = ''
26ACCESS_SECRET = ''
27api = TwitterAPI(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)
28
29filename = ""
30
31# Get oldest recently added pic
32c.execute("SELECT * FROM pics WHERE lastTimeTweeted = 0 ORDER BY added ASC LIMIT 1;")
33row = c.fetchone()
34# If there is an oldest new pic, set the variables
35if row:
36 filename = row[1]
37 status = row[2]
38else:
39 # Else check when was the last pic tweeted
40 c.execute("SELECT lastTimeTweeted FROM pics ORDER BY lastTimeTweeted DESC LIMIT 1;")
41 row = c.fetchone()
42 lastTimeTweeted = row[0]
43 # If it's more than the interval tweet a random one
44 if lastTimeTweeted < (time.time() - tweetEvery):
45 c.execute("SELECT * FROM pics WHERE lastTimeTweeted < (strftime('%s', 'now') - 300000) ORDER BY RANDOM() LIMIT 1;")
46 row = c.fetchone()
47 filename = row[1]
48 status = row[2]
49
50# If nothing is set, exit, otherwise tweet
51if not filename:
52 sys.exit()
53
54done = 0
55
56while done != 1:
57 try:
58 log("Trying to tweet " + filename)
59 file_path = "./pics/" + filename
60 file = open(file_path, 'rb')
61 data = file.read()
62 #r = 200
63 r = api.request('media/upload', None, {'media': data})
64
65 if r.status_code == 200:
66 media_id = r.json()['media_id']
67 #r = 200
68 r = api.request('statuses/update', {'status': status, 'media_ids': media_id})
69 if r.status_code == 200:
70 log("Tweeted " + filename)
71 done = 1
72 c.execute("UPDATE pics SET lastTimeTweeted = strftime('%s', 'now') WHERE filename=?;", (filename,))
73 conn.commit()
74 else:
75 time.sleep(30)
76 except:
77 log("nope... retrying in a bit...")
78 time.sleep(60)
79
80conn.close()